Skip to content

Commit

Permalink
Colorized compact output.
Browse files Browse the repository at this point in the history
Signed-off-by: Springcomp <[email protected]>
  • Loading branch information
springcomp committed Mar 20, 2023
1 parent f752c98 commit af2c94a
Showing 1 changed file with 33 additions and 9 deletions.
42 changes: 33 additions & 9 deletions jp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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
}
}

0 comments on commit af2c94a

Please sign in to comment.