Preserve line-end comments when replacing image

Previously: replace the YNode (yaml.Node) with a new one which is just
the replacement string.
Now: change the value of the YNode, and set it back in place.
This commit is contained in:
Michael Bridgen 2020-09-29 12:19:12 +01:00
parent b9d345dbc4
commit 963ee35c23
7 changed files with 36 additions and 5 deletions

View File

@ -7,4 +7,4 @@ spec:
spec:
containers:
- name: hello
image: helloworld:1.0.1
image: helloworld:1.0.1 # SETTER_SITE

View File

@ -7,4 +7,4 @@ spec:
spec:
containers:
- name: hello
image: helloworld:1.2.0
image: helloworld:1.2.0 # SETTER_SITE

View File

@ -7,4 +7,4 @@ spec:
spec:
containers:
- name: hello
image: helloworld:1.0.0
image: helloworld:1.0.0 # SETTER_SITE

View File

@ -0,0 +1,11 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: foo
namespace: bar
spec:
template:
spec:
containers:
- name: c
image: used:v1.1.0 # the comment must stay!

View File

@ -0,0 +1,11 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: foo
namespace: bar
spec:
template:
spec:
containers:
- name: c
image: used:v1.0.0 # the comment must stay!

View File

@ -36,7 +36,6 @@ func makeUpdateImagesFilter(originalRepo, replacement string) kio.Filter {
}
canonName := originalRef.Context().String()
replacementNode := yaml.NewScalarRNode(replacement)
replaceContainerImage := func(container *yaml.RNode) error {
if imageField := container.Field("image"); imageField != nil {
@ -45,7 +44,9 @@ func makeUpdateImagesFilter(originalRepo, replacement string) kio.Filter {
return err
}
if ref.Context().String() == canonName {
imageField.Value.SetYNode(replacementNode.YNode())
ynode := imageField.Value.YNode()
ynode.Value = replacement
imageField.Value.SetYNode(ynode)
}
}
return nil

View File

@ -32,4 +32,12 @@ var _ = Describe("Update image everywhere", func() {
Expect(UpdateImageEverywhere("testdata/replace/original", tmp, "used", "used:v1.1.0")).To(Succeed())
test.ExpectMatchingDirectories("testdata/replace/expected", tmp)
})
It("keeps comments intact", func() {
tmp, err := ioutil.TempDir("", "gotest")
Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmp)
Expect(UpdateImageEverywhere("testdata/replace/commented", tmp, "used", "used:v1.1.0")).To(Succeed())
test.ExpectMatchingDirectories("testdata/replace/commented-expected", tmp)
})
})