Debian Codegraph @

api/internal/builtins/PatchTransformer.go

raw ◀ ▶
1 Debian patch touch this file
1 // Code generated by pluginator on PatchTransformer; DO NOT EDIT.
2 package builtins
3
4 import (
5 "fmt"
6 "strings"
7
8 jsonpatch "github.com/evanphx/json-patch/v5"
9 "sigs.k8s.io/kustomize/api/filters/patchjson6902"
•10 "sigs.k8s.io/kustomize/api/resmap"
11 "sigs.k8s.io/kustomize/api/resource"
12 "sigs.k8s.io/kustomize/api/types"
13 "sigs.k8s.io/kustomize/kyaml/errors"
14 "sigs.k8s.io/kustomize/kyaml/kio/kioutil"
15 "sigs.k8s.io/yaml"
16 )
17
18 type PatchTransformerPlugin struct {
19 smPatches []*resource.Resource // strategic-merge patches
20 jsonPatches jsonpatch.Patch // json6902 patch
21 // patchText is pure patch text created by Path or Patch
22 patchText string
23 // patchSource is patch source message
24 patchSource string
25 Path string `json:"path,omitempty" yaml:"path,omitempty"`
26 Patch string `json:"patch,omitempty" yaml:"patch,omitempty"`
27 Target *types.Selector `json:"target,omitempty" yaml:"target,omitempty"`
28 Options *types.PatchArgs `json:"options,omitempty" yaml:"options,omitempty"`
29 }
30
31 func (p *PatchTransformerPlugin) Config(h *resmap.PluginHelpers, c []byte) error {
32 if err := yaml.Unmarshal(c, p); err != nil {
33 return err
34 }
35
36 p.Patch = strings.TrimSpace(p.Patch)
37 switch {
38 case p.Patch == "" && p.Path == "":
39 return fmt.Errorf("must specify one of patch and path in\n%s", string(c))
40 case p.Patch != "" && p.Path != "":
41 return fmt.Errorf("patch and path can't be set at the same time\n%s", string(c))
42 case p.Patch != "":
43 p.patchText = p.Patch
44 p.patchSource = fmt.Sprintf("[patch: %q]", p.patchText)
45 case p.Path != "":
46 loaded, err := h.Loader().Load(p.Path)
47 if err != nil {
48 return fmt.Errorf("failed to get the patch file from path(%s): %w", p.Path, err)
49 }
50 p.patchText = string(loaded)
51 p.patchSource = fmt.Sprintf("[path: %q]", p.Path)
52 }
53
54 patchesSM, errSM := h.ResmapFactory().RF().SliceFromBytes([]byte(p.patchText))
55 patchesJson, errJson := jsonPatchFromBytes([]byte(p.patchText))
56
57 if ((errSM == nil && errJson == nil) ||
58 (patchesSM != nil && patchesJson != nil)) &&
59 (len(patchesSM) > 0 && len(patchesJson) > 0) {
60 return fmt.Errorf(
61 "illegally qualifies as both an SM and JSON patch: %s",
62 p.patchSource)
63 }
64 if errSM != nil && errJson != nil {
65 return fmt.Errorf(
66 "unable to parse SM or JSON patch from %s", p.patchSource)
67 }
68 if errSM == nil {
69 p.smPatches = patchesSM
70 for _, loadedPatch := range p.smPatches {
71 if p.Options == nil {
72 continue
73 }
74
75 if p.Options.AllowNameChange {
76 loadedPatch.AllowNameChange()
77 }
78 if p.Options.AllowKindChange {
79 loadedPatch.AllowKindChange()
80 }
81 }
82 } else {
83 p.jsonPatches = patchesJson
84 }
85 return nil
86 }
87
88 func (p *PatchTransformerPlugin) Transform(m resmap.ResMap) error {
89 if p.smPatches != nil {
90 return p.transformStrategicMerge(m)
91 }
92 if p.jsonPatches != nil {
93 return p.transformJson6902(m)
94 }
95 return nil
96 }
97
98 // transformStrategicMerge applies each loaded strategic merge patch
99 // to the resource in the ResMap that matches the identifier of the patch.
100 // If only one patch is specified, the Target can be used instead.
101 func (p *PatchTransformerPlugin) transformStrategicMerge(m resmap.ResMap) error {
102 if p.Target != nil {
103 if len(p.smPatches) > 1 {
104 // detail: https://github.com/kubernetes-sigs/kustomize/issues/5049#issuecomment-1440604403
105 return fmt.Errorf("Multiple Strategic-Merge Patches in one `patches` entry is not allowed to set `patches.target` field: %s", p.patchSource)
106 }
107
108 // single patch
109 patch := p.smPatches[0]
110 selected, err := m.Select(*p.Target)
111 if err != nil {
112 return fmt.Errorf("unable to find patch target %q in `resources`: %w", p.Target, err)
113 }
114 return errors.Wrap(m.ApplySmPatch(resource.MakeIdSet(selected), patch))
115 }
116
117 for _, patch := range p.smPatches {
118 target, err := m.GetById(patch.OrgId())
119 if err != nil {
120 return fmt.Errorf("no resource matches strategic merge patch %q: %w", patch.OrgId(), err)
121 }
122 if err := target.ApplySmPatch(patch); err != nil {
123 return errors.Wrap(err)
124 }
125 }
126 return nil
127 }
128
129 // transformJson6902 applies json6902 Patch to all the resources in the ResMap that match Target.
130 func (p *PatchTransformerPlugin) transformJson6902(m resmap.ResMap) error {
131 if p.Target == nil {
132 return fmt.Errorf("must specify a target for JSON patch %s", p.patchSource)
133 }
134 resources, err := m.Select(*p.Target)
135 if err != nil {
136 return err
137 }
138 for _, res := range resources {
139 res.StorePreviousId()
140 internalAnnotations := kioutil.GetInternalAnnotations(&res.RNode)
141 err = res.ApplyFilter(patchjson6902.Filter{
142 Patch: p.patchText,
143 })
144 if err != nil {
145 return err
146 }
147
148 annotations := res.GetAnnotations()
149 for key, value := range internalAnnotations {
150 annotations[key] = value
151 }
152 err = res.SetAnnotations(annotations)
153 }
154 return nil
155 }
156
157 // jsonPatchFromBytes loads a Json 6902 patch from a bytes input
158 func jsonPatchFromBytes(in []byte) (jsonpatch.Patch, error) {
159 ops := string(in)
160 if ops == "" {
161 return nil, fmt.Errorf("empty json patch operations")
162 }
163
164 if ops[0] != '[' {
165 // TODO(5049):
166 // In the case of multiple yaml documents, return error instead of ignoring all but first.
167 // Details: https://github.com/kubernetes-sigs/kustomize/pull/5194#discussion_r1256686728
168 jsonOps, err := yaml.YAMLToJSON(in)
169 if err != nil {
170 return nil, err
171 }
172 ops = string(jsonOps)
173 }
174 return jsonpatch.DecodePatch([]byte(ops))
175 }
176
177 func NewPatchTransformerPlugin() resmap.TransformerPlugin {
178 return &PatchTransformerPlugin{}
179 }