Debian Codegraph @

plugin/builtin/suffixtransformer/SuffixTransformer.go

raw
1 // Copyright 2021 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 //go:generate pluginator
5 package main
6
7 import (
8 "errors"
9
10 "sigs.k8s.io/kustomize/api/filters/suffix"
11 "sigs.k8s.io/kustomize/api/resmap"
12 "sigs.k8s.io/kustomize/api/types"
13 "sigs.k8s.io/kustomize/kyaml/resid"
14 "sigs.k8s.io/kustomize/kyaml/yaml"
15 )
16
17 // Add the given suffix to the field
18 type plugin struct {
19 Suffix string `json:"suffix,omitempty" yaml:"suffix,omitempty"`
20 FieldSpecs types.FsSlice `json:"fieldSpecs,omitempty" yaml:"fieldSpecs,omitempty"`
21 }
22
23 var KustomizePlugin plugin //nolint:gochecknoglobals
24
25 // TODO: Make this gvk skip list part of the config.
26 var suffixFieldSpecsToSkip = types.FsSlice{
27 {Gvk: resid.Gvk{Kind: "CustomResourceDefinition"}},
28 {Gvk: resid.Gvk{Group: "apiregistration.k8s.io", Kind: "APIService"}},
29 {Gvk: resid.Gvk{Kind: "Namespace"}},
30 }
31
32 func (p *plugin) Config(
33 _ *resmap.PluginHelpers, c []byte) (err error) {
34 p.Suffix = ""
35 p.FieldSpecs = nil
36 err = yaml.Unmarshal(c, p)
37 if err != nil {
38 return
39 }
40 if p.FieldSpecs == nil {
41 return errors.New("fieldSpecs is not expected to be nil")
42 }
43 return
44 }
45
46 func (p *plugin) Transform(m resmap.ResMap) error {
47 // Even if the Suffix is empty we want to proceed with the
48 // transformation. This allows to add contextual information
49 // to the resources (AddNameSuffix).
50 for _, r := range m.Resources() {
51 // TODO: move this test into the filter (i.e. make a better filter)
52 if p.shouldSkip(r.OrgId()) {
53 continue
54 }
55 id := r.OrgId()
56 // current default configuration contains
57 // only one entry: "metadata/name" with no GVK
58 for _, fs := range p.FieldSpecs {
59 // TODO: this is redundant to filter (but needed for now)
60 if !id.IsSelected(&fs.Gvk) {
61 continue
62 }
63 // TODO: move this test into the filter.
64 if fs.Path == "metadata/name" {
65 // "metadata/name" is the only field.
66 // this will add a suffix to the resource
67 // even if it is empty
68
69 r.AddNameSuffix(p.Suffix)
70 if p.Suffix != "" {
71 // TODO: There are multiple transformers that can change a resource's name, and each makes a call to
72 // StorePreviousID(). We should make it so that we only call StorePreviousID once per kustomization layer
73 // to avoid storing intermediate names between transformations, to prevent intermediate name conflicts.
74 r.StorePreviousId()
75 }
76 }
77 if err := r.ApplyFilter(suffix.Filter{
78 Suffix: p.Suffix,
79 FieldSpec: fs,
80 }); err != nil {
81 return err
82 }
83 }
84 }
85 return nil
86 }
87
88 func (p *plugin) shouldSkip(id resid.ResId) bool {
89 for _, path := range suffixFieldSpecsToSkip {
90 if id.IsSelected(&path.Gvk) {
91 return true
92 }
93 }
94 return false
95 }