Added colors to json output #1208

This commit is contained in:
Mike Farah 2022-05-22 21:19:59 +10:00
parent 7d28e4e0de
commit fbe49c3700
9 changed files with 32 additions and 18 deletions

View File

@ -91,7 +91,7 @@ func configurePrinterWriter(format yqlib.PrinterOutputFormat, out io.Writer) (yq
func configureEncoder(format yqlib.PrinterOutputFormat) yqlib.Encoder { func configureEncoder(format yqlib.PrinterOutputFormat) yqlib.Encoder {
switch format { switch format {
case yqlib.JSONOutputFormat: case yqlib.JSONOutputFormat:
return yqlib.NewJONEncoder(indent) return yqlib.NewJONEncoder(indent, colorsEnabled)
case yqlib.PropsOutputFormat: case yqlib.PropsOutputFormat:
return yqlib.NewPropertiesEncoder() return yqlib.NewPropertiesEncoder()
case yqlib.CSVOutputFormat: case yqlib.CSVOutputFormat:

View File

@ -1,6 +1,7 @@
package yqlib package yqlib
import ( import (
"bytes"
"encoding/json" "encoding/json"
"io" "io"
@ -9,6 +10,7 @@ import (
type jsonEncoder struct { type jsonEncoder struct {
indentString string indentString string
colorise bool
} }
func mapKeysToStrings(node *yaml.Node) { func mapKeysToStrings(node *yaml.Node) {
@ -26,14 +28,14 @@ func mapKeysToStrings(node *yaml.Node) {
} }
} }
func NewJONEncoder(indent int) Encoder { func NewJONEncoder(indent int, colorise bool) Encoder {
var indentString = "" var indentString = ""
for index := 0; index < indent; index++ { for index := 0; index < indent; index++ {
indentString = indentString + " " indentString = indentString + " "
} }
return &jsonEncoder{indentString} return &jsonEncoder{indentString, colorise}
} }
func (je *jsonEncoder) CanHandleAliases() bool { func (je *jsonEncoder) CanHandleAliases() bool {
@ -49,7 +51,14 @@ func (je *jsonEncoder) PrintLeadingContent(writer io.Writer, content string) err
} }
func (je *jsonEncoder) Encode(writer io.Writer, node *yaml.Node) error { func (je *jsonEncoder) Encode(writer io.Writer, node *yaml.Node) error {
var encoder = json.NewEncoder(writer)
destination := writer
tempBuffer := bytes.NewBuffer(nil)
if je.colorise {
destination = tempBuffer
}
var encoder = json.NewEncoder(destination)
encoder.SetEscapeHTML(false) // do not escape html chars e.g. &, <, > encoder.SetEscapeHTML(false) // do not escape html chars e.g. &, <, >
encoder.SetIndent("", je.indentString) encoder.SetIndent("", je.indentString)
@ -60,5 +69,12 @@ func (je *jsonEncoder) Encode(writer io.Writer, node *yaml.Node) error {
if errorDecoding != nil { if errorDecoding != nil {
return errorDecoding return errorDecoding
} }
return encoder.Encode(dataBucket) err := encoder.Encode(dataBucket)
if err != nil {
return err
}
if je.colorise {
return colorizeAndPrint(tempBuffer.Bytes(), writer)
}
return nil
} }

View File

@ -13,7 +13,7 @@ func yamlToJSON(sampleYaml string, indent int) string {
var output bytes.Buffer var output bytes.Buffer
writer := bufio.NewWriter(&output) writer := bufio.NewWriter(&output)
var jsonEncoder = NewJONEncoder(indent) var jsonEncoder = NewJONEncoder(indent, false)
inputs, err := readDocuments(strings.NewReader(sampleYaml), "sample.yml", 0, NewYamlDecoder()) inputs, err := readDocuments(strings.NewReader(sampleYaml), "sample.yml", 0, NewYamlDecoder())
if err != nil { if err != nil {
panic(err) panic(err)

View File

@ -97,7 +97,7 @@ func decodeJSON(t *testing.T, jsonString string) *CandidateNode {
func testJSONScenario(t *testing.T, s formatScenario) { func testJSONScenario(t *testing.T, s formatScenario) {
if s.scenarioType == "encode" || s.scenarioType == "roundtrip" { if s.scenarioType == "encode" || s.scenarioType == "roundtrip" {
test.AssertResultWithContext(t, s.expected, processFormatScenario(s, NewYamlDecoder(), NewJONEncoder(s.indent)), s.description) test.AssertResultWithContext(t, s.expected, processFormatScenario(s, NewYamlDecoder(), NewJONEncoder(s.indent, false)), s.description)
} else { } else {
var actual = resultToString(t, decodeJSON(t, s.input)) var actual = resultToString(t, decodeJSON(t, s.input))
test.AssertResultWithContext(t, s.expected, actual, s.description) test.AssertResultWithContext(t, s.expected, actual, s.description)
@ -171,7 +171,7 @@ func documentJSONEncodeScenario(w *bufio.Writer, s formatScenario) {
} }
writeOrPanic(w, "will output\n") writeOrPanic(w, "will output\n")
writeOrPanic(w, fmt.Sprintf("```json\n%v```\n\n", processFormatScenario(s, NewYamlDecoder(), NewJONEncoder(s.indent)))) writeOrPanic(w, fmt.Sprintf("```json\n%v```\n\n", processFormatScenario(s, NewYamlDecoder(), NewJONEncoder(s.indent, false))))
} }
func TestJSONScenarios(t *testing.T) { func TestJSONScenarios(t *testing.T) {

View File

@ -331,25 +331,23 @@ func parseInt64(numberString string) (string, int64, error) {
return "%v", num, err return "%v", num, err
} }
func parseInt(numberString string) (string, int, error) { func parseInt(numberString string) (int, error) {
var err error var err error
var parsed int64 var parsed int64
format := "%v"
if strings.HasPrefix(numberString, "0x") || if strings.HasPrefix(numberString, "0x") ||
strings.HasPrefix(numberString, "0X") { strings.HasPrefix(numberString, "0X") {
format = "0x%X"
parsed, err = strconv.ParseInt(numberString[2:], 16, 64) parsed, err = strconv.ParseInt(numberString[2:], 16, 64)
} else { } else {
parsed, err = strconv.ParseInt(numberString, 10, 64) parsed, err = strconv.ParseInt(numberString, 10, 64)
} }
if err != nil { if err != nil {
return "", 0, err return 0, err
} else if parsed > math.MaxInt { } else if parsed > math.MaxInt {
return "", 0, fmt.Errorf("%v is too big (larger than %v)", parsed, math.MaxInt) return 0, fmt.Errorf("%v is too big (larger than %v)", parsed, math.MaxInt)
} }
return format, int(parsed), err return int(parsed), err
} }
func createScalarNode(value interface{}, stringValue string) *yaml.Node { func createScalarNode(value interface{}, stringValue string) *yaml.Node {

View File

@ -13,7 +13,7 @@ import (
func configureEncoder(format PrinterOutputFormat, indent int) Encoder { func configureEncoder(format PrinterOutputFormat, indent int) Encoder {
switch format { switch format {
case JSONOutputFormat: case JSONOutputFormat:
return NewJONEncoder(indent) return NewJONEncoder(indent, false)
case PropsOutputFormat: case PropsOutputFormat:
return NewPropertiesEncoder() return NewPropertiesEncoder()
case CSVOutputFormat: case CSVOutputFormat:

View File

@ -31,7 +31,7 @@ func pickSequence(original *yaml.Node, indices *yaml.Node) (*yaml.Node, error) {
filteredContent := make([]*yaml.Node, 0) filteredContent := make([]*yaml.Node, 0)
for index := 0; index < len(indices.Content); index = index + 1 { for index := 0; index < len(indices.Content); index = index + 1 {
_, indexInArray, err := parseInt(indices.Content[index].Value) indexInArray, err := parseInt(indices.Content[index].Value)
if err != nil { if err != nil {
return nil, fmt.Errorf("cannot index array with %v", indices.Content[index].Value) return nil, fmt.Errorf("cannot index array with %v", indices.Content[index].Value)
} }

View File

@ -188,7 +188,7 @@ func traverseArrayWithIndices(candidate *CandidateNode, indices []*yaml.Node, pr
for _, indexNode := range indices { for _, indexNode := range indices {
log.Debug("traverseArrayWithIndices: '%v'", indexNode.Value) log.Debug("traverseArrayWithIndices: '%v'", indexNode.Value)
_, index, err := parseInt(indexNode.Value) index, err := parseInt(indexNode.Value)
if err != nil && prefs.OptionalTraverse { if err != nil && prefs.OptionalTraverse {
continue continue
} }

View File

@ -314,7 +314,7 @@ func TestPrinterMultipleDocsJson(t *testing.T) {
var writer = bufio.NewWriter(&output) var writer = bufio.NewWriter(&output)
// note printDocSeparators is true, it should still not print document separators // note printDocSeparators is true, it should still not print document separators
// when outputing JSON. // when outputing JSON.
printer := NewPrinter(NewJONEncoder(0), NewSinglePrinterWriter(writer)) printer := NewPrinter(NewJONEncoder(0, false), NewSinglePrinterWriter(writer))
inputs, err := readDocuments(strings.NewReader(multiDocSample), "sample.yml", 0, NewYamlDecoder()) inputs, err := readDocuments(strings.NewReader(multiDocSample), "sample.yml", 0, NewYamlDecoder())
if err != nil { if err != nil {