@@ -61,7 +61,7 @@ func updateYamlNode(node *yaml.Node, path []string, value string) (bool, error)
61
61
}
62
62
63
63
key := path [0 ]
64
- if _ , valueNode := lookupKey (node , key ); valueNode != nil {
64
+ if _ , valueNode := LookupKey (node , key ); valueNode != nil {
65
65
return updateYamlNode (valueNode , path [1 :], value )
66
66
}
67
67
@@ -90,7 +90,7 @@ func updateYamlNode(node *yaml.Node, path []string, value string) (bool, error)
90
90
return updateYamlNode (newNode , path [1 :], value )
91
91
}
92
92
93
- func lookupKey (node * yaml.Node , key string ) (* yaml.Node , * yaml.Node ) {
93
+ func LookupKey (node * yaml.Node , key string ) (* yaml.Node , * yaml.Node ) {
94
94
for i := 0 ; i < len (node .Content )- 1 ; i += 2 {
95
95
if node .Content [i ].Value == key {
96
96
return node .Content [i ], node .Content [i + 1 ]
@@ -100,6 +100,19 @@ func lookupKey(node *yaml.Node, key string) (*yaml.Node, *yaml.Node) {
100
100
return nil , nil
101
101
}
102
102
103
+ // Returns the key and value if they were present
104
+ func RemoveKey (node * yaml.Node , key string ) (* yaml.Node , * yaml.Node ) {
105
+ for i := 0 ; i < len (node .Content )- 1 ; i += 2 {
106
+ if node .Content [i ].Value == key {
107
+ key , value := node .Content [i ], node .Content [i + 1 ]
108
+ node .Content = append (node .Content [:i ], node .Content [i + 2 :]... )
109
+ return key , value
110
+ }
111
+ }
112
+
113
+ return nil , nil
114
+ }
115
+
103
116
// Walks a yaml document from the root node to the specified path, and then applies the transformation to that node.
104
117
// If the requested path is not defined in the document, no changes are made to the document.
105
118
func TransformNode (rootNode * yaml.Node , path []string , transform func (node * yaml.Node ) error ) error {
@@ -123,7 +136,7 @@ func transformNode(node *yaml.Node, path []string, transform func(node *yaml.Nod
123
136
return transform (node )
124
137
}
125
138
126
- keyNode , valueNode := lookupKey (node , path [0 ])
139
+ keyNode , valueNode := LookupKey (node , path [0 ])
127
140
if keyNode == nil {
128
141
return nil
129
142
}
@@ -154,15 +167,15 @@ func renameYamlKey(node *yaml.Node, path []string, newKey string) error {
154
167
return errors .New ("yaml node in path is not a dictionary" )
155
168
}
156
169
157
- keyNode , valueNode := lookupKey (node , path [0 ])
170
+ keyNode , valueNode := LookupKey (node , path [0 ])
158
171
if keyNode == nil {
159
172
return nil
160
173
}
161
174
162
175
// end of path reached: rename key
163
176
if len (path ) == 1 {
164
177
// Check that new key doesn't exist yet
165
- if newKeyNode , _ := lookupKey (node , newKey ); newKeyNode != nil {
178
+ if newKeyNode , _ := LookupKey (node , newKey ); newKeyNode != nil {
166
179
return fmt .Errorf ("new key `%s' already exists" , newKey )
167
180
}
168
181
0 commit comments