@@ -8,26 +8,38 @@ import (
8
8
"os/exec"
9
9
10
10
"github.com/spf13/cobra"
11
+ "sigs.k8s.io/yaml"
11
12
)
12
13
14
+ var format string
15
+
13
16
// NewCmdFetch makes a new fetch command.
14
17
func NewCmdFetch (w io.Writer ) * cobra.Command {
15
- infoCmd := cobra.Command {
18
+ fetchCmd := cobra.Command {
16
19
Use : "fetch" ,
17
20
Short : `Fetches the OpenAPI specification from the current kubernetes cluster specified
18
21
in the user's kubeconfig` ,
19
22
Example : `kustomize openapi fetch` ,
20
- Run : func (cmd * cobra.Command , args []string ) {
21
- printSchema (w )
23
+ RunE : func (cmd * cobra.Command , args []string ) error {
24
+ return printSchema (w )
22
25
},
23
26
}
24
- return & infoCmd
27
+ fetchCmd .Flags ().StringVar (
28
+ & format ,
29
+ "format" ,
30
+ "json" ,
31
+ "Specify format for fetched schema ('json' or 'yaml')" )
32
+ return & fetchCmd
25
33
}
26
34
27
- func printSchema (w io.Writer ) {
35
+ func printSchema (w io.Writer ) error {
36
+ if format != "json" && format != "yaml" {
37
+ return fmt .Errorf ("format must be either 'json' or 'yaml'" )
38
+ }
39
+
28
40
errMsg := `
29
41
Error fetching schema from cluster.
30
- Please make sure kubectl is installed and its context is set correctly.
42
+ Please make sure kubectl is installed, its context is set correctly, and your cluster is up .
31
43
Installation and setup instructions: https://kubernetes.io/docs/tasks/tools/install-kubectl/`
32
44
33
45
command := exec .Command ("kubectl" , []string {"get" , "--raw" , "/openapi/v2" }... )
@@ -36,15 +48,25 @@ Installation and setup instructions: https://kubernetes.io/docs/tasks/tools/inst
36
48
command .Stdout = & stdout
37
49
command .Stderr = & stderr
38
50
err := command .Run ()
39
- if err != nil || stdout .String () == "" {
40
- fmt .Fprintln (w , err , stderr .String ()+ errMsg )
41
- return
51
+ if err != nil {
52
+ return fmt .Errorf ("%w\n %s" , err , stderr .String ()+ errMsg )
53
+ } else if stdout .String () == "" {
54
+ return fmt .Errorf (stderr .String () + errMsg )
42
55
}
43
56
44
57
// format and output
45
58
var jsonSchema map [string ]interface {}
46
59
output := stdout .Bytes ()
47
60
json .Unmarshal (output , & jsonSchema )
48
61
output , _ = json .MarshalIndent (jsonSchema , "" , " " )
62
+
63
+ if format == "yaml" {
64
+ output , err = yaml .JSONToYAML (output )
65
+ if err != nil {
66
+ return err
67
+ }
68
+ }
69
+
49
70
fmt .Fprintln (w , string (output ))
71
+ return nil
50
72
}
0 commit comments