Skip to content

Commit 8b0b153

Browse files
committed
Add yaml_utils.RemoveKey
1 parent af37a88 commit 8b0b153

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
)
@@ -65,6 +66,19 @@ func lookupKey(node *yaml.Node, key string) (*yaml.Node, *yaml.Node) {
6566
return nil, nil
6667
}
6768

69+
// Returns the key and value if they were present
70+
func RemoveKey(node *yaml.Node, key string) (*yaml.Node, *yaml.Node) {
71+
for i := 0; i < len(node.Content)-1; i += 2 {
72+
if node.Content[i].Value == key {
73+
key, value := node.Content[i], node.Content[i+1]
74+
node.Content = slices.Delete(node.Content, i, i+2)
75+
return key, value
76+
}
77+
}
78+
79+
return nil, nil
80+
}
81+
6882
// Walks a yaml document from the root node to the specified path, and then applies the transformation to that node.
6983
// If the requested path is not defined in the document, no changes are made to the document.
7084
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)