From e6d48190aeff9629b851b2c1f3ea2a8122a26aa8 Mon Sep 17 00:00:00 2001 From: Niels Widger Date: Sat, 8 Feb 2020 10:05:29 -0500 Subject: [PATCH] Add support for colorized JSON output Add support for colorized JSON output via the github.com/nwidger/jsoncolor package. Colorized output can be disabled via a new --monochrome flag. --- cmd/root.go | 19 +++++++++++++++++-- go.mod | 2 ++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index d664905..88e2a12 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -8,13 +8,22 @@ import ( "os" homedir "github.com/mitchellh/go-homedir" + "github.com/nwidger/jsoncolor" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/cube2222/jql/jql/app" ) -var cfgFile string +var ( + cfgFile string + monochrome bool +) + +type encoder interface { + Encode(v interface{}) error + SetIndent(prefix, indent string) +} // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ @@ -26,7 +35,12 @@ var rootCmd = &cobra.Command{ input := json.NewDecoder(bufio.NewReaderSize(os.Stdin, 4096*16)) w := bufio.NewWriterSize(os.Stdout, 4096*16) defer w.Flush() - output := json.NewEncoder(w) + var output encoder + if monochrome { + output = json.NewEncoder(w) + } else { + output = jsoncolor.NewEncoder(w) + } output.SetIndent("", " ") app := app.NewApp(args[0], input, output) @@ -54,6 +68,7 @@ func init() { // will be global for your application. rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.jql.yaml)") + rootCmd.PersistentFlags().BoolVar(&monochrome, "monochrome", false, "monochrome (don't colorize output)") } // initConfig reads in config file and ENV variables if set. diff --git a/go.mod b/go.mod index a399173..0481efc 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,9 @@ module github.com/cube2222/jql go 1.13 require ( + github.com/fatih/color v1.9.0 // indirect github.com/mitchellh/go-homedir v1.1.0 + github.com/nwidger/jsoncolor v0.2.1 github.com/spf13/cobra v0.0.5 github.com/spf13/viper v1.6.1 github.com/stretchr/testify v1.4.0