Allow setting every array element in replacements

This commit is contained in:
koba1t
2022-01-27 06:17:23 +09:00
parent c65ef489ca
commit 26b9af0379
3 changed files with 44 additions and 0 deletions

View File

@@ -796,6 +796,12 @@ func SplitIndexNameValue(p string) (string, string, error) {
return parts[0], parts[1], nil 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 // IncrementFieldIndex increments i to point to the next field name element in
// a slice of Contents. // a slice of Contents.
func IncrementFieldIndex(i int) int { func IncrementFieldIndex(i int) int {

View File

@@ -83,10 +83,42 @@ func (p *PathMatcher) filter(rn *RNode) (*RNode, error) {
// match seq elements // match seq elements
return p.doSeq(rn) return p.doSeq(rn)
} }
if IsMatchEveryIndex(p.Path[0]) {
// match every elements (*)
return p.doMatchEvery(rn)
}
// match a field // match a field
return p.doField(rn) 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) { func (p *PathMatcher) doField(rn *RNode) (*RNode, error) {
// lookup the field // lookup the field
field, err := rn.Pipe(Get(p.Path[0])) field, err := rn.Pipe(Get(p.Path[0]))

View File

@@ -77,6 +77,12 @@ spec:
{[]string{ {[]string{
"spec", "template", "spec", "containers", "[name=s.*]", "ports", "[containerPort=.*2]"}, "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 { for i, u := range updates {
result, err := node.Pipe(&PathMatcher{Path: u.path}) result, err := node.Pipe(&PathMatcher{Path: u.path})