Pretty print

This commit is contained in:
Mike Farah 2020-01-31 16:35:01 +11:00
parent c6a52012ab
commit ec25511f1b
4 changed files with 41 additions and 0 deletions

View File

@ -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")

View File

@ -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

View File

@ -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)
}

View File

@ -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")