labelsandannotations.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. "errors"
  16. "fmt"
  17. "sigs.k8s.io/kustomize/pkg/resmap"
  18. "sigs.k8s.io/kustomize/pkg/transformers/config"
  19. )
  20. // mapTransformer applies a string->string map to fieldSpecs.
  21. type mapTransformer struct {
  22. m map[string]string
  23. fieldSpecs []config.FieldSpec
  24. }
  25. var _ Transformer = &mapTransformer{}
  26. // NewLabelsMapTransformer constructs a mapTransformer.
  27. func NewLabelsMapTransformer(
  28. m map[string]string, fs []config.FieldSpec) (Transformer, error) {
  29. return NewMapTransformer(fs, m)
  30. }
  31. // NewAnnotationsMapTransformer construct a mapTransformer.
  32. func NewAnnotationsMapTransformer(
  33. m map[string]string, fs []config.FieldSpec) (Transformer, error) {
  34. return NewMapTransformer(fs, m)
  35. }
  36. // NewMapTransformer construct a mapTransformer.
  37. func NewMapTransformer(
  38. pc []config.FieldSpec, m map[string]string) (Transformer, error) {
  39. if m == nil {
  40. return NewNoOpTransformer(), nil
  41. }
  42. if pc == nil {
  43. return nil, errors.New("fieldSpecs is not expected to be nil")
  44. }
  45. return &mapTransformer{fieldSpecs: pc, m: m}, nil
  46. }
  47. // Transform apply each <key, value> pair in the mapTransformer to the
  48. // fields specified in mapTransformer.
  49. func (o *mapTransformer) Transform(m resmap.ResMap) error {
  50. for id := range m {
  51. objMap := m[id].Map()
  52. for _, path := range o.fieldSpecs {
  53. if !id.Gvk().IsSelected(&path.Gvk) {
  54. continue
  55. }
  56. err := mutateField(objMap, path.PathSlice(), path.CreateIfNotPresent, o.addMap)
  57. if err != nil {
  58. return err
  59. }
  60. }
  61. }
  62. return nil
  63. }
  64. func (o *mapTransformer) addMap(in interface{}) (interface{}, error) {
  65. m, ok := in.(map[string]interface{})
  66. if !ok {
  67. return nil, fmt.Errorf("%#v is expected to be %T", in, m)
  68. }
  69. for k, v := range o.m {
  70. m[k] = v
  71. }
  72. return m, nil
  73. }