github.com/argoproj/argo-cd/v3@v3.2.1/cmd/argocd/commands/common.go (about) 1 package commands 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "reflect" 7 8 "sigs.k8s.io/yaml" 9 ) 10 11 const ( 12 cliName = "argocd" 13 14 // DefaultSSOLocalPort is the localhost port to listen on for the temporary web server performing 15 // the OAuth2 login flow. 16 DefaultSSOLocalPort = 8085 17 ) 18 19 // PrintResource prints a single resource in YAML or JSON format to stdout according to the output format 20 func PrintResource(resource any, output string) error { 21 switch output { 22 case "json": 23 jsonBytes, err := json.MarshalIndent(resource, "", " ") 24 if err != nil { 25 return fmt.Errorf("unable to marshal resource to json: %w", err) 26 } 27 fmt.Println(string(jsonBytes)) 28 case "yaml": 29 yamlBytes, err := yaml.Marshal(resource) 30 if err != nil { 31 return fmt.Errorf("unable to marshal resource to yaml: %w", err) 32 } 33 fmt.Print(string(yamlBytes)) 34 default: 35 return fmt.Errorf("unknown output format: %s", output) 36 } 37 return nil 38 } 39 40 // PrintResourceList marshals & prints a list of resources to stdout according to the output format 41 func PrintResourceList(resources any, output string, single bool) error { 42 kt := reflect.ValueOf(resources) 43 // Sometimes, we want to marshal the first resource of a slice or array as single item 44 if kt.Kind() == reflect.Slice || kt.Kind() == reflect.Array { 45 if single && kt.Len() == 1 { 46 return PrintResource(kt.Index(0).Interface(), output) 47 } 48 49 // If we have a zero len list, prevent printing "null" 50 if kt.Len() == 0 { 51 return PrintResource([]string{}, output) 52 } 53 } 54 55 switch output { 56 case "json": 57 jsonBytes, err := json.MarshalIndent(resources, "", " ") 58 if err != nil { 59 return fmt.Errorf("unable to marshal resources to json: %w", err) 60 } 61 fmt.Println(string(jsonBytes)) 62 case "yaml": 63 yamlBytes, err := yaml.Marshal(resources) 64 if err != nil { 65 return fmt.Errorf("unable to marshal resources to yaml: %w", err) 66 } 67 fmt.Print(string(yamlBytes)) 68 default: 69 return fmt.Errorf("unknown output format: %s", output) 70 } 71 return nil 72 }