mutatefield.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package transformers
  14. import (
  15. "fmt"
  16. "log"
  17. "strings"
  18. )
  19. type mutateFunc func(interface{}) (interface{}, error)
  20. func mutateField(
  21. m map[string]interface{},
  22. pathToField []string,
  23. createIfNotPresent bool,
  24. fns ...mutateFunc) error {
  25. if len(pathToField) == 0 {
  26. return nil
  27. }
  28. _, found := m[pathToField[0]]
  29. if !found {
  30. if !createIfNotPresent {
  31. return nil
  32. }
  33. m[pathToField[0]] = map[string]interface{}{}
  34. }
  35. if len(pathToField) == 1 {
  36. var err error
  37. for _, fn := range fns {
  38. m[pathToField[0]], err = fn(m[pathToField[0]])
  39. if err != nil {
  40. return err
  41. }
  42. }
  43. return nil
  44. }
  45. v := m[pathToField[0]]
  46. newPathToField := pathToField[1:]
  47. switch typedV := v.(type) {
  48. case nil:
  49. log.Printf(
  50. "nil value at `%s` ignored in mutation attempt",
  51. strings.Join(pathToField, "."))
  52. return nil
  53. case map[string]interface{}:
  54. return mutateField(typedV, newPathToField, createIfNotPresent, fns...)
  55. case []interface{}:
  56. for i := range typedV {
  57. item := typedV[i]
  58. typedItem, ok := item.(map[string]interface{})
  59. if !ok {
  60. return fmt.Errorf("%#v is expected to be %T", item, typedItem)
  61. }
  62. err := mutateField(typedItem, newPathToField, createIfNotPresent, fns...)
  63. if err != nil {
  64. return err
  65. }
  66. }
  67. return nil
  68. default:
  69. return fmt.Errorf("%#v is not expected to be a primitive type", typedV)
  70. }
  71. }