Debian Codegraph @

kyaml/yaml/match.go

raw symbols SCIP
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package yaml
5
6 import (
7 "fmt"
8 "regexp"
9 "strconv"
10 "strings"
11
12 yaml "go.yaml.in/yaml/v3"
13 "sigs.k8s.io/kustomize/kyaml/errors"
14 )
15
16 // PathMatcher returns all RNodes matching the path wrapped in a SequenceNode.
17 // Lists may have multiple elements matching the pafunc cleanPath(path []string) []string {g element
18 // is added to the return result.
19 // If Path points to a SequenceNode, the SequenceNode is wrapped in another SequenceNode
20 // If Path does not contain any lists, the result is still wrapped in a SequenceNode of len == 1
21 type PathMatcher struct {
22 Kind string `yaml:"kind,omitempty"`
23
24 // Path is a slice of parts leading to the RNode to lookup.
25 // Each path part may be one of:
26 // * FieldMatcher -- e.g. "spec"
27 // * Map Key -- e.g. "app.k8s.io/version"
28 // * List Entry -- e.g. "[name=nginx]" or "[=-jar]" or "0"
29 //
30 // Map Keys and Fields are equivalent.
31 // See FieldMatcher for more on Fields and Map Keys.
32 //
33 // List Entries are specified as map entry to match [fieldName=fieldValue].
34 // See Elem for more on List Entries.
35 //
36 // Examples:
37 // * spec.template.spec.container with matching name: [name=nginx] -- match 'name': 'nginx'
38 // * spec.template.spec.container.argument matching a value: [=-jar] -- match '-jar'
39 Path []string `yaml:"path,omitempty"`
40
41 // Matches is set by PathMatch to publish the matched element values for each node.
42 // After running PathMatcher.Filter, each node from the SequenceNode result may be
43 // looked up in Matches to find the field values that were matched.
44 Matches map[*Node][]string
45
46 // StripComments may be set to remove the comments on the matching Nodes.
47 // This is useful for if the nodes are to be printed in FlowStyle.
48 StripComments bool
49
50 // Create will cause missing path parts to be created as they are walked.
51 //
52 // * The leaf Node (final path) will be created with a Kind matching Create
53 // * Intermediary Nodes will be created as either a MappingNodes or
54 // SequenceNodes as appropriate for each's Path location.
55 // * Nodes identified by an index will only be created if the index indicates
56 // an append operation (i.e. index=len(list))
57 Create yaml.Kind `yaml:"create,omitempty"`
58
59 val *RNode
60 field string
61 matchRegex string
62 }
63
64 func (p *PathMatcher) stripComments(n *Node) {
65 if n == nil {
66 return
67 }
68 if p.StripComments {
69 n.LineComment = ""
70 n.HeadComment = ""
71 n.FootComment = ""
72 for i := range n.Content {
73 p.stripComments(n.Content[i])
74 }
75 }
76 }
77
78 func (p *PathMatcher) Filter(rn *RNode) (*RNode, error) {
79 val, err := p.filter(rn)
80 if err != nil {
81 return nil, err
82 }
83 p.stripComments(val.YNode())
84 return val, err
85 }
86
87 func (p *PathMatcher) filter(rn *RNode) (*RNode, error) {
88 p.Matches = map[*Node][]string{}
89
90 if len(p.Path) == 0 {
91 // return the element wrapped in a SequenceNode
92 p.appendRNode("", rn)
93 return p.val, nil
94 }
95
96 if IsIdxNumber(p.Path[0]) {
97 return p.doIndexSeq(rn)
98 }
99
100 if IsListIndex(p.Path[0]) {
101 // match seq elements
102 return p.doSeq(rn)
103 }
104
105 if IsWildcard(p.Path[0]) {
106 // match every elements (*)
107 return p.doMatchEvery(rn)
108 }
109 // match a field
110 return p.doField(rn)
111 }
112
113 func (p *PathMatcher) doMatchEvery(rn *RNode) (*RNode, error) {
114 if err := rn.VisitElements(p.visitEveryElem); err != nil {
115 return nil, err
116 }
117
118 return p.val, nil
119 }
120
121 func (p *PathMatcher) visitEveryElem(elem *RNode) error {
122 fieldName := p.Path[0]
123 // recurse on the matching element
124 pm := &PathMatcher{Path: p.Path[1:], Create: p.Create}
125 add, err := pm.filter(elem)
126 for k, v := range pm.Matches {
127 p.Matches[k] = v
128 }
129 if err != nil || add == nil {
130 return err
131 }
132 p.append(fieldName, add.Content()...)
133
134 return nil
135 }
136
137 func (p *PathMatcher) doField(rn *RNode) (*RNode, error) {
138 // lookup the field
139 field, err := rn.Pipe(Get(p.Path[0]))
140 if err != nil {
141 return nil, err
142 }
143
144 if !IsCreate(p.Create) && field == nil {
145 return nil, nil
146 }
147
148 if IsCreate(p.Create) && field == nil {
149 var nextPart string
150 if len(p.Path) > 1 {
151 nextPart = p.Path[1]
152 }
153 nextPartKind := getPathPartKind(nextPart, p.Create)
154 field = &RNode{value: &yaml.Node{Kind: nextPartKind}}
155 err := rn.PipeE(SetField(p.Path[0], field))
156 if err != nil {
157 return nil, err
158 }
159 }
160
161 // Check if the field is a scalar and there are remaining path segments
162 if field != nil && field.YNode().Kind == yaml.ScalarNode && len(p.Path) > 1 {
163 return p.handleStructuredDataInScalar(field)
164 }
165
166 // recurse on the field, removing the first element of the path
167 pm := &PathMatcher{Path: p.Path[1:], Create: p.Create}
168 p.val, err = pm.filter(field)
169 p.Matches = pm.Matches
170 return p.val, err
171 }
172
173 // doIndexSeq iterates over a sequence and appends elements matching the index p.Val
174 func (p *PathMatcher) doIndexSeq(rn *RNode) (*RNode, error) {
175 // parse to index number
176 idx, err := strconv.Atoi(p.Path[0])
177 if err != nil {
178 return nil, err
179 }
180
181 elements, err := rn.Elements()
182 if err != nil {
183 return nil, err
184 }
185
186 if len(elements) == idx && IsCreate(p.Create) {
187 var nextPart string
188 if len(p.Path) > 1 {
189 nextPart = p.Path[1]
190 }
191 elem := &yaml.Node{Kind: getPathPartKind(nextPart, p.Create)}
192 err = rn.PipeE(Append(elem))
193 if err != nil {
194 return nil, errors.WrapPrefixf(err, "failed to append element for %q", p.Path[0])
195 }
196 elements = append(elements, NewRNode(elem))
197 }
198
199 if len(elements) < idx+1 {
200 return nil, fmt.Errorf("index %d specified but only %d elements found", idx, len(elements))
201 }
202 // get target element
203 element := elements[idx]
204
205 // recurse on the matching element
206 pm := &PathMatcher{Path: p.Path[1:], Create: p.Create}
207 add, err := pm.filter(element)
208 for k, v := range pm.Matches {
209 p.Matches[k] = v
210 }
211 if err != nil || add == nil {
212 return nil, err
213 }
214 p.append("", add.Content()...)
215 return p.val, nil
216 }
217
218 // doSeq iterates over a sequence and appends elements matching the path regex to p.Val
219 func (p *PathMatcher) doSeq(rn *RNode) (*RNode, error) {
220 // parse the field + match pair
221 var err error
222 p.field, p.matchRegex, err = SplitIndexNameValue(p.Path[0])
223 if err != nil {
224 return nil, err
225 }
226
227 primitiveElement := len(p.field) == 0
228 if primitiveElement {
229 err = rn.VisitElements(p.visitPrimitiveElem)
230 } else {
231 err = rn.VisitElements(p.visitElem)
232 }
233 if err != nil {
234 return nil, err
235 }
236 if !p.val.IsNil() && len(p.val.YNode().Content) == 0 {
237 p.val = nil
238 }
239
240 if !IsCreate(p.Create) || p.val != nil {
241 return p.val, nil
242 }
243
244 var elem *yaml.Node
245 valueNode := NewScalarRNode(p.matchRegex).YNode()
246 if primitiveElement {
247 elem = valueNode
248 } else {
249 elem = &yaml.Node{
250 Kind: yaml.MappingNode,
251 Content: []*yaml.Node{{Kind: yaml.ScalarNode, Value: p.field}, valueNode},
252 }
253 }
254 err = rn.PipeE(Append(elem))
255 if err != nil {
256 return nil, errors.WrapPrefixf(err, "failed to create element for %q", p.Path[0])
257 }
258 // re-do the sequence search; this time we'll find the element we just created
259 return p.doSeq(rn)
260 }
261
262 func (p *PathMatcher) visitPrimitiveElem(elem *RNode) error {
263 r, err := regexp.Compile(p.matchRegex)
264 if err != nil {
265 return fmt.Errorf("%w", err)
266 }
267
268 str, err := elem.String()
269 if err != nil {
270 return fmt.Errorf("%w", err)
271 }
272 str = strings.TrimSpace(str)
273 if !r.MatchString(str) {
274 return nil
275 }
276
277 p.appendRNode("", elem)
278 return nil
279 }
280
281 func (p *PathMatcher) visitElem(elem *RNode) error {
282 r, err := regexp.Compile(p.matchRegex)
283 if err != nil {
284 return fmt.Errorf("%w", err)
285 }
286
287 // check if this elements field matches the regex
288 val := elem.Field(p.field)
289 if val == nil || val.Value == nil {
290 return nil
291 }
292 str, err := val.Value.String()
293 if err != nil {
294 return fmt.Errorf("%w", err)
295 }
296 str = strings.TrimSpace(str)
297 if !r.MatchString(str) {
298 return nil
299 }
300
301 // recurse on the matching element
302 pm := &PathMatcher{Path: p.Path[1:], Create: p.Create}
303 add, err := pm.filter(elem)
304 for k, v := range pm.Matches {
305 p.Matches[k] = v
306 }
307 if err != nil || add == nil {
308 return err
309 }
310 p.append(str, add.Content()...)
311 return nil
312 }
313
314 func (p *PathMatcher) appendRNode(path string, node *RNode) {
315 p.append(path, node.YNode())
316 }
317
318 func (p *PathMatcher) append(path string, nodes ...*Node) {
319 if p.val == nil {
320 p.val = NewRNode(&Node{Kind: SequenceNode})
321 }
322 for i := range nodes {
323 node := nodes[i]
324 p.val.YNode().Content = append(p.val.YNode().Content, node)
325 // record the path if specified
326 if path != "" {
327 p.Matches[node] = append(p.Matches[node], path)
328 }
329 }
330 }
331
332 func cleanPath(path []string) []string {
333 var p []string
334 for _, elem := range path {
335 elem = strings.TrimSpace(elem)
336 if len(elem) == 0 {
337 continue
338 }
339 p = append(p, elem)
340 }
341 return p
342 }
343
344 // handleStructuredDataInScalar processes a scalar field that contains structured data (JSON/YAML)
345 // and allows path navigation within that structured data
346 func (p *PathMatcher) handleStructuredDataInScalar(scalarField *RNode) (*RNode, error) {
347 scalarValue := scalarField.YNode().Value
348 var parsedNode yaml.Node
349 if err := yaml.Unmarshal([]byte(scalarValue), &parsedNode); err != nil {
350 return nil, fmt.Errorf("%w", err)
351 }
352
353 // Create a structured field from the parsed data
354 structuredField := NewRNode(&parsedNode)
355
356 // Process the remaining path on the structured data
357 pm := &PathMatcher{Path: p.Path[1:], Create: p.Create}
358 result, err := pm.filter(structuredField)
359 if err != nil {
360 return nil, err
361 }
362 p.Matches = pm.Matches
363
364 return result, nil
365 }