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