Allow substring replacement of numerics

This change adds the ability to use substring substitution to inject
numeric source values into string targets.  This is required for our
networking catalogue, since a numeric k8s API port needs to be inserted into
numeric and (sub)string targets in different phases.

Co-Authored-By: Ian Howell <ian.howell0@gmail.com>
Change-Id: I24beb46a2bda4e118406129a0a922b0c56142c76
This commit is contained in:
Matt McEuen 2020-09-10 19:11:55 -05:00
parent 99d37b3907
commit 9997e7427e
2 changed files with 71 additions and 4 deletions

View File

@ -231,9 +231,17 @@ func applySubstringPattern(target interface{}, replacement interface{},
return replacement, nil
}
repl, ok := replacement.(string)
if !ok {
return nil, ErrPatternSubstring{Msg: "pattern-based substitution can only be applied with string replacement values"}
// if replacement is numeric, convert it to a string for the sake of
// substring substitution.
var replacementString string
switch t := replacement.(type) {
case uint, uint8, uint16, uint32, uint64, int, int8, int16, int32, int64:
replacementString = fmt.Sprint(t)
case string:
replacementString = t
default:
return nil, ErrPatternSubstring{Msg: "pattern-based substitution can only be applied " +
"with string or numeric replacement values"}
}
tgt, ok := target.(string)
@ -248,7 +256,7 @@ func applySubstringPattern(target interface{}, replacement interface{},
substringPattern, tgt),
}
}
return p.ReplaceAllString(tgt, repl), nil
return p.ReplaceAllString(tgt, replacementString), nil
}
func updateMapField(m map[string]interface{}, pathToField []string, replacement interface{}) error {

View File

@ -554,6 +554,65 @@ spec:
cfg: `
apiVersion: airshipit.org/v1alpha1
kind: ReplacementTransformer
metadata:
name: test-for-numeric-conversion
replacements:
- source:
objref:
kind: Pod
name: pod
fieldref: spec.containers[0].image
target:
objref:
kind: Deployment
fieldrefs:
- spec.template.spec.containers[name=myapp-container].image%TAG%`,
in: `
apiVersion: v1
kind: Pod
metadata:
name: pod
spec:
containers:
- name: repl
image: 12345
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: deploy2
spec:
template:
spec:
containers:
- image: busybox:TAG
name: myapp-container
`,
expectedOut: `apiVersion: v1
kind: Pod
metadata:
name: pod
spec:
containers:
- image: 12345
name: repl
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: deploy2
spec:
template:
spec:
containers:
- image: busybox:12345
name: myapp-container
`,
},
{
cfg: `
apiVersion: airshipit.org/v1alpha1
kind: ReplacementTransformer
metadata:
name: notImportantHere
replacements: