From ec25511f1baf3a676791d09cc36b17094f015e88 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Fri, 31 Jan 2020 16:35:01 +1100 Subject: [PATCH] Pretty print --- cmd/commands_test.go | 21 +++++++++++++++++++++ cmd/constant.go | 1 + cmd/read.go | 5 +++++ cmd/utils.go | 14 ++++++++++++++ 4 files changed, 41 insertions(+) diff --git a/cmd/commands_test.go b/cmd/commands_test.go index 19217ab2..73d8dbd1 100644 --- a/cmd/commands_test.go +++ b/cmd/commands_test.go @@ -342,6 +342,27 @@ func TestReadCmd_ArrayYaml(t *testing.T) { test.AssertResult(t, "false", result.Output) } +func TestReadPrettyPrintCmd(t *testing.T) { + cmd := getRootCommand() + result := test.RunCmd(cmd, "read -P ../examples/sample.json") + if result.Error != nil { + t.Error(result.Error) + } + expectedOutput := `a: Easy! as one two three +b: + c: 2 + d: + - 3 + - 4 + e: + - name: fred + value: 3 + - name: sam + value: 4 +` + test.AssertResult(t, expectedOutput, result.Output) +} + func TestReadCmd_ArrayYaml_NoPath(t *testing.T) { cmd := getRootCommand() result := test.RunCmd(cmd, "read ../examples/array.yaml") diff --git a/cmd/constant.go b/cmd/constant.go index 8302a624..476987d7 100644 --- a/cmd/constant.go +++ b/cmd/constant.go @@ -10,6 +10,7 @@ var printMode = "v" var writeInplace = false var writeScript = "" var outputToJSON = false +var prettyPrint = false var overwriteFlag = false var autoCreateFlag = true var allowEmptyFlag = false diff --git a/cmd/read.go b/cmd/read.go index d9d3bd23..568203ef 100644 --- a/cmd/read.go +++ b/cmd/read.go @@ -25,6 +25,7 @@ yq r -- things.yaml '--key-starting-with-dashes.blah' } cmdRead.PersistentFlags().StringVarP(&docIndex, "doc", "d", "0", "process document index number (0 based, * for all documents)") cmdRead.PersistentFlags().StringVarP(&printMode, "printMode", "p", "v", "print mode (v (values, default), p (paths), pv (path and value pairs)") + cmdRead.PersistentFlags().BoolVarP(&prettyPrint, "prettyPrint", "P", false, "pretty print") return cmdRead } @@ -48,5 +49,9 @@ func readProperty(cmd *cobra.Command, args []string) error { return errorReadingStream } + if prettyPrint { + setStyle(matchingNodes, 0) + } + return printResults(matchingNodes, cmd) } diff --git a/cmd/utils.go b/cmd/utils.go index 590f49e1..1b51992d 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -87,6 +87,20 @@ func printValue(node *yaml.Node, cmd *cobra.Command) error { return nil } +func setStyle(matchingNodes []*yqlib.NodeContext, style yaml.Style) { + for _, nodeContext := range matchingNodes { + updateStyleOfNode(nodeContext.Node, style) + } +} + +func updateStyleOfNode(node *yaml.Node, style yaml.Style) { + node.Style = style + + for _, child := range node.Content { + updateStyleOfNode(child, style) + } +} + func printResults(matchingNodes []*yqlib.NodeContext, cmd *cobra.Command) error { if len(matchingNodes) == 0 { log.Debug("no matching results, nothing to print")