Fix patch YAML without new line on end of file

This commit is contained in:
Alexey Khit
2023-09-04 11:52:13 +03:00
parent 08dabc7331
commit 05360ac284
2 changed files with 55 additions and 0 deletions
+15
View File
@@ -109,6 +109,13 @@ func AddOrReplace(src []byte, key string, value any, nodeParent *yaml.Node) ([]b
i0 := LineOffset(src, nodeKey.Line)
i1 := LineOffset(src, LastChild(nodeValue).Line+1)
if i1 < 0 { // no new line on the end of file
if value != nil {
return append(src[:i0], put...), nil
}
return src[:i0], nil
}
dst := make([]byte, 0, len(src)+len(put))
dst = append(dst, src[:i0]...)
if value != nil {
@@ -121,6 +128,14 @@ func AddOrReplace(src []byte, key string, value any, nodeParent *yaml.Node) ([]b
i := LineOffset(src, LastChild(nodeParent).Line+1)
if i < 0 { // no new line on the end of file
src = append(src, '\n')
if value != nil {
src = append(src, put...)
}
return src, nil
}
dst := make([]byte, 0, len(src)+len(put))
dst = append(dst, src[:i]...)
if value != nil {
+40
View File
@@ -104,3 +104,43 @@ func TestPatch2(t *testing.T) {
camera2: url3
`, string(b))
}
func TestNoNewLineEnd1(t *testing.T) {
b := []byte(`streams:
camera1: url4
camera2:
- url2
- url3`)
b, err := Patch(b, "camera2", "url5", "streams")
require.Nil(t, err)
require.Equal(t, `streams:
camera1: url4
camera2: url5
`, string(b))
}
func TestNoNewLineEnd2(t *testing.T) {
b := []byte(`streams:
camera1: url1
homekit:
camera1:
pin: 123-45-678`)
// 1. Add new key
pairings := []string{"client1", "client2"}
b, err := Patch(b, "pairings", pairings, "homekit", "camera1")
require.Nil(t, err)
require.Equal(t, `streams:
camera1: url1
homekit:
camera1:
pin: 123-45-678
pairings:
- client1
- client2
`, string(b))
}