From 9fd1f5513b150f0745d26f7ac71ef8e94e82cdfd Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Sun, 29 Sep 2024 14:48:54 +0000 Subject: [PATCH] Add `--no-pretty` global flag for parsable CLI output --- cmd/root.go | 1 + internal/output/marshal.go | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/cmd/root.go b/cmd/root.go index 74eacc2..c67f9ef 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -67,6 +67,7 @@ func init() { rootCmd.PersistentFlags().String("client-id", "", "Client ID. Sent to the Token Issuer during the Client Credentials flow") //nolint:lll rootCmd.PersistentFlags().String("client-secret", "", "Client Secret. Sent to the Token Issuer during the Client Credentials flow") //nolint:lll rootCmd.PersistentFlags().StringArray("api-scopes", []string{}, "API Scopes (repeat option for multiple values). Used in the Client Credentials flow") //nolint:lll + rootCmd.PersistentFlags().Bool("no-pretty", false, "Disable pretty output features (useful for scripting)") //nolint:lll rootCmd.MarkFlagsRequiredTogether( "api-token-issuer", diff --git a/internal/output/marshal.go b/internal/output/marshal.go index 828d0ad..d1746a1 100644 --- a/internal/output/marshal.go +++ b/internal/output/marshal.go @@ -23,6 +23,7 @@ import ( "os" "github.com/gocarina/gocsv" + "github.com/spf13/viper" "gopkg.in/yaml.v3" "github.com/mattn/go-isatty" @@ -184,6 +185,10 @@ func outputNonTerminal(data any) error { // Display will decorate the output if possible. Otherwise, will print out the standard JSON. func Display(data any) error { + if viper.GetBool("no-pretty") { + return outputParsable(data) + } + if isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd()) { if os.Getenv("NO_COLOR") != "" { return displayNoColorTerminal(data) @@ -194,3 +199,12 @@ func Display(data any) error { return outputNonTerminal(data) } + +func outputParsable(data any) error { + result, err := json.Marshal(data) + if err != nil { + return fmt.Errorf("unable to marshal json with error %w", err) + } + fmt.Println(string(result)) + return nil +}