Skip to content

Commit 5f4be3b

Browse files
stefanhallerChris McDonnell
andcommitted
Add yaml_utils.RemoveKey
Co-authored-by: Chris McDonnell <c.a.mcdonn@gmail.com>
1 parent 02611da commit 5f4be3b

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

pkg/utils/yaml_utils/yaml_utils.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"errors"
66
"fmt"
7+
"slices"
78

89
"gopkg.in/yaml.v3"
910
)
@@ -18,6 +19,19 @@ func lookupKey(node *yaml.Node, key string) (*yaml.Node, *yaml.Node) {
1819
return nil, nil
1920
}
2021

22+
// Returns the key and value if they were present
23+
func RemoveKey(node *yaml.Node, key string) (*yaml.Node, *yaml.Node) {
24+
for i := 0; i < len(node.Content)-1; i += 2 {
25+
if node.Content[i].Value == key {
26+
key, value := node.Content[i], node.Content[i+1]
27+
node.Content = slices.Delete(node.Content, i, i+2)
28+
return key, value
29+
}
30+
}
31+
32+
return nil, nil
33+
}
34+
2135
// Walks a yaml document from the root node to the specified path, and then applies the transformation to that node.
2236
// If the requested path is not defined in the document, no changes are made to the document.
2337
func TransformNode(rootNode *yaml.Node, path []string, transform func(node *yaml.Node) error) error {

pkg/utils/yaml_utils/yaml_utils_test.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,55 @@ foo:
282282
}
283283
}
284284

285+
func TestRemoveKey(t *testing.T) {
286+
tests := []struct {
287+
name string
288+
in string
289+
key string
290+
expectedOut string
291+
expectedRemovedKey string
292+
expectedRemovedValue string
293+
}{
294+
{
295+
name: "Key not present",
296+
in: "foo: 1",
297+
key: "bar",
298+
},
299+
{
300+
name: "Key present",
301+
in: "foo: 1\nbar: 2\nbaz: 3\n",
302+
key: "bar",
303+
expectedOut: "foo: 1\nbaz: 3\n",
304+
expectedRemovedKey: "bar",
305+
expectedRemovedValue: "2",
306+
},
307+
}
308+
309+
for _, test := range tests {
310+
t.Run(test.name, func(t *testing.T) {
311+
node := unmarshalForTest(t, test.in)
312+
removedKey, removedValue := RemoveKey(node.Content[0], test.key)
313+
if test.expectedOut == "" {
314+
unmodifiedOriginal := unmarshalForTest(t, test.in)
315+
assert.Equal(t, unmodifiedOriginal, node)
316+
} else {
317+
result := marshalForTest(t, &node)
318+
assert.Equal(t, test.expectedOut, result)
319+
}
320+
if test.expectedRemovedKey == "" {
321+
assert.Nil(t, removedKey)
322+
} else {
323+
assert.Equal(t, test.expectedRemovedKey, removedKey.Value)
324+
}
325+
if test.expectedRemovedValue == "" {
326+
assert.Nil(t, removedValue)
327+
} else {
328+
assert.Equal(t, test.expectedRemovedValue, removedValue.Value)
329+
}
330+
})
331+
}
332+
}
333+
285334
func unmarshalForTest(t *testing.T, input string) yaml.Node {
286335
t.Helper()
287336
var node yaml.Node

0 commit comments

Comments
 (0)