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
This commit is contained in:
Piotr Komborski 2020-09-30 14:33:27 +01:00
parent 87550b7fe5
commit eb1acac350
No known key found for this signature in database
GPG Key ID: 66A31A11D9693D9D

View File

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