Skip to content

Commit

Permalink
Fix comments handling in addOrReplaceValue function (#1039)
Browse files Browse the repository at this point in the history
  • Loading branch information
vitorvezani authored Mar 15, 2024
1 parent ac638e0 commit a81bd29
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 10 deletions.
3 changes: 3 additions & 0 deletions pkg/mutation/mutate.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,9 @@ func addOrReplaceValue(node *yaml.Node, splits []string, value *yaml.Node) error
}
for _, node := range nodes {
if node.Kind == yaml.ScalarNode {
if value.LineComment == "" {
value.LineComment = node.LineComment // keep the original comment if override is not provided
}
// Overwrite an existing scalar value with a new value (whatever kind).
*node = *value
} else if node.Kind == yaml.MappingNode && value.Kind == yaml.MappingNode {
Expand Down
34 changes: 24 additions & 10 deletions pkg/mutation/mutate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,31 +107,26 @@ obj:
},
Path: "/obj/foo",
},
mutated: `obj:
mutated: `
obj:
foo:
bar:
- c
- d
baz: quux
`,
}, {
original: `
foo: bar
`,
original: `foo: bar`,
patch: config.Mutation{
Op: "replace",
Value: "baz",
Path: "/foo",
Comment: "# We set this to baz",
},
mutated: `
foo: baz # We set this to baz
`,
mutated: `foo: baz # We set this to baz`,
message: "Expected a comment to appear",
}, {
original: `
foo: bar
`,
original: `foo: bar`,
patch: config.Mutation{
Op: "add",
Value: map[string]interface{}{
Expand Down Expand Up @@ -167,6 +162,25 @@ extra:
baz: quux
`,
message: "Expected a comment to appear next to an object",
}, {
original: `foo: bar # we should keep this comment`,
patch: config.Mutation{
Op: "replace",
Value: "baz",
Path: "/foo",
},
mutated: `foo: baz # we should keep this comment`,
message: "Expected a comment to be kept",
}, {
original: `foo: bar # we should override this comment`,
patch: config.Mutation{
Op: "replace",
Value: "baz",
Path: "/foo",
Comment: "override",
},
mutated: `foo: baz # override`,
message: "Expected a comment to overridden",
},
}

Expand Down

0 comments on commit a81bd29

Please sign in to comment.