Added strip comments functionality

This commit is contained in:
Mike Farah 2020-04-14 14:48:45 +10:00
parent 33e35d10dd
commit 2db69c91c9
4 changed files with 45 additions and 0 deletions

View File

@ -109,6 +109,29 @@ func TestReadUnwrapCmd(t *testing.T) {
test.AssertResult(t, "'frog' # my favourite\n", result.Output)
}
func TestReadStripCommentsCmd(t *testing.T) {
content := `# this is really cool
b: # my favourite
c: 5 # cats
# blah
`
filename := test.WriteTempYamlFile(content)
defer test.RemoveTempYamlFile(filename)
cmd := getRootCommand()
result := test.RunCmd(cmd, fmt.Sprintf("read %s --stripComments", filename))
if result.Error != nil {
t.Error(result.Error)
}
expectedOutput := `b:
c: 5
`
test.AssertResult(t, expectedOutput, result.Output)
}
func TestReadUnwrapJsonByDefaultCmd(t *testing.T) {
content := `b: 'frog' # my favourite`

View File

@ -9,6 +9,7 @@ var customTag = ""
var printMode = "v"
var printLength = false
var unwrapScalar = true
var stripComments = false
var collectIntoArray = false
var writeInplace = false
var writeScript = ""

View File

@ -29,6 +29,7 @@ yq r -- things.yaml '--key-starting-with-dashes.blah'
cmdRead.PersistentFlags().BoolVarP(&printLength, "length", "l", false, "print length of results")
cmdRead.PersistentFlags().BoolVarP(&collectIntoArray, "collect", "c", false, "collect results into array")
cmdRead.PersistentFlags().BoolVarP(&unwrapScalar, "unwrapScalar", "", true, "unwrap scalar, print the value with no quotes, colors or comments")
cmdRead.PersistentFlags().BoolVarP(&stripComments, "stripComments", "", false, "print yaml without any comments")
cmdRead.PersistentFlags().BoolVarP(&explodeAnchors, "explodeAnchors", "X", false, "explode anchors")
return cmdRead
}

View File

@ -114,6 +114,22 @@ func printNode(node *yaml.Node, writer io.Writer) error {
return encoder.Encode(node)
}
func removeComments(matchingNodes []*yqlib.NodeContext) {
for _, nodeContext := range matchingNodes {
removeCommentOfNode(nodeContext.Node)
}
}
func removeCommentOfNode(node *yaml.Node) {
node.HeadComment = ""
node.LineComment = ""
node.FootComment = ""
for _, child := range node.Content {
removeCommentOfNode(child)
}
}
func setStyle(matchingNodes []*yqlib.NodeContext, style yaml.Style) {
for _, nodeContext := range matchingNodes {
updateStyleOfNode(nodeContext.Node, style)
@ -160,6 +176,10 @@ func printResults(matchingNodes []*yqlib.NodeContext, writer io.Writer) error {
setStyle(matchingNodes, 0)
}
if stripComments {
removeComments(matchingNodes)
}
//always explode anchors when printing json
if explodeAnchors || outputToJSON {
errorExploding := explode(matchingNodes)