diff --git a/jp.go b/jp.go index e467481..aefc91a 100644 --- a/jp.go +++ b/jp.go @@ -78,6 +78,21 @@ func runMain(c *cli.Context) int { } expression = c.Args()[0] } + // NoColor defines if the output is colorized or not. It's dynamically set to + // false or true based on the stdout's file descriptor referring to a terminal + // or not. It's also set to true if the NO_COLOR environment variable is + // set (regardless of its value). This is a global option and affects all + // colors. + switch c.String("color") { + case "always": + color.NoColor = false + case "auto": + // this is the default in the library + case "never": + color.NoColor = true + default: + return errMsg("Invalid color specification. Must use always/auto/never") + } if c.Bool("ast") { parser := jmespath.NewParser() parsed, err := parser.Parse(expression) @@ -123,16 +138,17 @@ func runMain(c *cli.Context) int { os.Stdout.WriteString(converted) } else { var toJSON []byte - if c.Bool("compact") { - toJSON, err = json.Marshal(result) - } else { - if color.NoColor { - // avoid doing the extra processing in jsoncolor - toJSON, err = json.MarshalIndent(result, "", " ") - } else { - toJSON, err = jsoncolor.MarshalIndent(result, "", " ") - } + var writers = [2][2]func(v interface{}) ([]byte, error){ + { + func(v interface{}) ([]byte, error) { return jsoncolor.MarshalIndent(v, "", " ") }, + jsoncolor.Marshal, + }, + { + func(v interface{}) ([]byte, error) { return json.MarshalIndent(v, "", " ") }, + json.Marshal, + }, } + toJSON, err = writers[bool2int(color.NoColor)][bool2int(c.Bool("compact"))](result) if err != nil { errMsg("Error marshalling result to JSON: %s\n", err) return 3 @@ -142,3 +158,11 @@ func runMain(c *cli.Context) int { os.Stdout.WriteString("\n") return 0 } + +func bool2int(b bool) int { + if b { + return 1 + } else { + return 0 + } +}