Skip to content

Commit

Permalink
Allow setting every array element in replacements
Browse files Browse the repository at this point in the history
  • Loading branch information
koba1t committed Jan 26, 2022
1 parent c65ef48 commit 26b9af0
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
6 changes: 6 additions & 0 deletions kyaml/yaml/fns.go
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,12 @@ func SplitIndexNameValue(p string) (string, string, error) {
return parts[0], parts[1], nil
}

// IsMatchEveryIndex returns true if p is matching every elements.
// e.g. "*"
func IsMatchEveryIndex(p string) bool {
return p == "*"
}

// IncrementFieldIndex increments i to point to the next field name element in
// a slice of Contents.
func IncrementFieldIndex(i int) int {
Expand Down
32 changes: 32 additions & 0 deletions kyaml/yaml/match.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,42 @@ func (p *PathMatcher) filter(rn *RNode) (*RNode, error) {
// match seq elements
return p.doSeq(rn)
}

if IsMatchEveryIndex(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
}

// fmt.Println(p.val.String())
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:]}
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]))
Expand Down
6 changes: 6 additions & 0 deletions kyaml/yaml/match_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ spec:
{[]string{
"spec", "template", "spec", "containers", "[name=s.*]", "ports", "[containerPort=.*2]"},
""},
{[]string{
"spec", "template", "spec", "containers", "*", "image"},
"- nginx:1.7.9\n- sidecar:1.0.0\n"},
{[]string{
"spec", "template", "spec", "containers", "*", "ports", "*"},
"- containerPort: 80\n- containerPort: 8081\n- containerPort: 9090\n"},
}
for i, u := range updates {
result, err := node.Pipe(&PathMatcher{Path: u.path})
Expand Down

0 comments on commit 26b9af0

Please sign in to comment.