Add test for mutatefield

This commit is contained in:
Jeffrey Regan
2018-11-27 12:17:48 -08:00
parent ef51cceff5
commit 8ba2ea9ca7
2 changed files with 171 additions and 0 deletions

View File

@@ -0,0 +1,74 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package transformers
import (
"fmt"
)
type mutateFunc func(interface{}) (interface{}, error)
func mutateField(
m map[string]interface{},
pathToField []string,
createIfNotPresent bool,
fns ...mutateFunc) error {
if len(pathToField) == 0 {
return nil
}
_, found := m[pathToField[0]]
if !found {
if !createIfNotPresent {
return nil
}
m[pathToField[0]] = map[string]interface{}{}
}
if len(pathToField) == 1 {
var err error
for _, fn := range fns {
m[pathToField[0]], err = fn(m[pathToField[0]])
if err != nil {
return err
}
}
return nil
}
v := m[pathToField[0]]
newPathToField := pathToField[1:]
switch typedV := v.(type) {
case map[string]interface{}:
return mutateField(typedV, newPathToField, createIfNotPresent, fns...)
case []interface{}:
for i := range typedV {
item := typedV[i]
typedItem, ok := item.(map[string]interface{})
if !ok {
return fmt.Errorf("%#v is expected to be %T", item, typedItem)
}
err := mutateField(typedItem, newPathToField, createIfNotPresent, fns...)
if err != nil {
return err
}
}
return nil
default:
return fmt.Errorf("%#v is not expected to be a primitive type", typedV)
}
}