From eb1acac350ab831647820ae3ee4b304c7a121df9 Mon Sep 17 00:00:00 2001 From: Piotr Komborski Date: Wed, 30 Sep 2020 14:33:27 +0100 Subject: [PATCH] Overwrite node if key exists but value doesn't match or append if key does not exist This fixes a bug with exploding anchors not overwriting nodes reported in https://github.com/mikefarah/yq/issues/546 Test case: ``` a: &first_anchor foo: bar first: first b: &second_anchor foo: bazz second: second c: <<: *first_anchor <<: *second_anchor ``` Output: ``` a: foo: bar first: first b: foo: bazz second: second c: foo: bazz first: first second: second ``` foo is properly overwritten by *second_anchor --- cmd/utils.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/cmd/utils.go b/cmd/utils.go index 9b1ca726..754c9332 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -149,10 +149,15 @@ func writeString(writer io.Writer, txt string) error { return errorWriting } -func setIfNotThere(node *yaml.Node, key string, value *yaml.Node) { +func overwriteOrSet(node *yaml.Node, key string, value *yaml.Node) { for index := 0; index < len(node.Content); index = index + 2 { keyNode := node.Content[index] - if keyNode.Value == key { + valueNode := node.Content[index+1] + if keyNode.Value == key && valueNode.Value == value.Value { + return + } + if keyNode.Value == key && valueNode.Value != value.Value { + node.Content[index+1] = value return } } @@ -170,7 +175,7 @@ func applyAlias(node *yaml.Node, alias *yaml.Node) { keyNode := alias.Content[index] log.Debugf("applying alias key %v", keyNode.Value) valueNode := alias.Content[index+1] - setIfNotThere(node, keyNode.Value, valueNode) + overwriteOrSet(node, keyNode.Value, valueNode) } }