Skip to content

Commit

Permalink
Fix #1 for case of comment on same line
Browse files Browse the repository at this point in the history
  • Loading branch information
hlubek committed Feb 5, 2024
1 parent 16e23e8 commit ff03b65
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 3 deletions.
2 changes: 1 addition & 1 deletion end_to_end_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ spec:
image: test.example.com:0.2.0
env:
- name: BUILD_ID
value: "42"
value: '42'
`},
},
},
Expand Down
7 changes: 6 additions & 1 deletion yaml/patcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,16 @@ func (p *Patcher) SetField(path string, value any, createKeys bool) error {
return fmt.Errorf("expected scalar node, got %s (at %d:%d)", kindToStr(valueNode.Kind), valueNode.Line, valueNode.Column)
}

err = valueNode.Encode(value)
newNode := new(goyaml.Node)
newNode.Kind = goyaml.ScalarNode
err = newNode.Encode(value)
if err != nil {
return fmt.Errorf("encoding value: %w", err)
}

valueNode.Value = newNode.Value
valueNode.Tag = newNode.Tag

return nil
}

Expand Down
81 changes: 80 additions & 1 deletion yaml/patcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,22 @@ spec:
image:
# some special comment
tag: 0.2.0
`,
},
{
name: "valid yaml with nested key and comment as annotation on same line",
inputYAML: `
foo: bar
spec:
image:
tag: 0.1.0 # {"$imagepolicy": "foo:bar:tag"}
`,
fieldPath: "spec.image.tag",
value: "0.2.0",
expectedYAML: `foo: bar
spec:
image:
tag: 0.2.0 # {"$imagepolicy": "foo:bar:tag"}
`,
},
{
Expand Down Expand Up @@ -135,7 +151,70 @@ spec:
- name: FOO
value: '1'
- name: BAR
value: "3"
value: '3'
`,
},
// Test various conversion of an existing value
{
name: "setting multi-line strings",
inputYAML: `
foo: bar
`,
fieldPath: "foo",
value: "A longer string\nwith a newline",
expectedYAML: `foo: |-
A longer string
with a newline
`,
},
{
name: "setting unquoted string to quoted",
inputYAML: `
foo: bar
`,
fieldPath: "foo",
value: "!better quote this",
expectedYAML: `foo: '!better quote this'
`,
},
{
name: "setting string in single quote is escaped correctly",
inputYAML: `
foo: 'double quote this'
`,
fieldPath: "foo",
value: "single's quote",
expectedYAML: `foo: 'single''s quote'
`,
},
{
name: "setting string to bool",
inputYAML: `
foo: bar
`,
fieldPath: "foo",
value: true,
expectedYAML: `foo: true
`,
},
{
name: "setting string to int",
inputYAML: `
foo: bar
`,
fieldPath: "foo",
value: 42,
expectedYAML: `foo: 42
`,
},
{
name: "setting string to null",
inputYAML: `
foo: bar
`,
fieldPath: "foo",
value: nil,
expectedYAML: `foo: null
`,
},
}
Expand Down

0 comments on commit ff03b65

Please sign in to comment.