wip: explode anchors

This commit is contained in:
Mike Farah 2020-02-05 14:10:59 +11:00
parent 179049a535
commit dc13fa99f7
3 changed files with 24 additions and 0 deletions

View File

@ -11,6 +11,7 @@ var writeInplace = false
var writeScript = "" var writeScript = ""
var outputToJSON = false var outputToJSON = false
var prettyPrint = false var prettyPrint = false
var explodeAnchors = false
var defaultValue = "" var defaultValue = ""
var indent = 2 var indent = 2
var overwriteFlag = false var overwriteFlag = false

View File

@ -26,6 +26,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(&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().StringVarP(&printMode, "printMode", "p", "v", "print mode (v (values, default), p (paths), pv (path and value pairs)")
cmdRead.PersistentFlags().StringVarP(&defaultValue, "defaultValue", "D", "", "default value printed when there are no results") cmdRead.PersistentFlags().StringVarP(&defaultValue, "defaultValue", "D", "", "default value printed when there are no results")
cmdRead.PersistentFlags().BoolVarP(&explodeAnchors, "explodeAnchors", "X", false, "explode anchors")
return cmdRead return cmdRead
} }

View File

@ -102,11 +102,33 @@ func writeString(writer io.Writer, txt string) error {
return errorWriting return errorWriting
} }
func explode(matchingNodes []*yqlib.NodeContext) error {
for _, nodeContext := range matchingNodes {
var targetNode = yaml.Node{Kind: yaml.MappingNode}
explodedNodes, errorRetrieving := lib.Get(nodeContext.Node, "**")
if errorRetrieving != nil {
return errorRetrieving
}
for _, matchingNode := range explodedNodes {
mergePath := lib.MergePathStackToString(matchingNode.PathStack, appendFlag)
updateCommand := yqlib.UpdateCommand{Command: "update", Path: mergePath, Value: matchingNode.Node, Overwrite: overwriteFlag}
lib.Update(&targetNode, updateCommand, true)
}
nodeContext.Node = &targetNode
}
return nil
}
func printResults(matchingNodes []*yqlib.NodeContext, writer io.Writer) error { func printResults(matchingNodes []*yqlib.NodeContext, writer io.Writer) error {
if prettyPrint { if prettyPrint {
setStyle(matchingNodes, 0) setStyle(matchingNodes, 0)
} }
//always explode anchors when printing json
if explodeAnchors || outputToJSON {
explode(matchingNodes)
}
bufferedWriter := bufio.NewWriter(writer) bufferedWriter := bufio.NewWriter(writer)
defer safelyFlush(bufferedWriter) defer safelyFlush(bufferedWriter)