Debian Codegraph @

api/filters/replacement/replacement.go

raw
1 // Copyright 2021 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package replacement
5
6 import (
7 "encoding/json"
8 "fmt"
9 "strings"
10
11 "sigs.k8s.io/kustomize/api/internal/utils"
12 "sigs.k8s.io/kustomize/api/resource"
13 "sigs.k8s.io/kustomize/api/types"
14 "sigs.k8s.io/kustomize/kyaml/errors"
15 kyaml_utils "sigs.k8s.io/kustomize/kyaml/utils"
16 "sigs.k8s.io/kustomize/kyaml/yaml"
17 )
18
19 type Filter struct {
20 Replacements []types.Replacement `json:"replacements,omitempty" yaml:"replacements,omitempty"`
21 }
22
23 // Filter replaces values of targets with values from sources
24 func (f Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) {
25 for i, r := range f.Replacements {
26 if (r.SourceValue == nil && r.Source == nil) || r.Targets == nil {
27 return nil, fmt.Errorf("replacements must specify a source and at least one target")
28 }
29 value, err := getReplacement(nodes, &f.Replacements[i])
30 if err != nil {
31 return nil, err
32 }
33 nodes, err = applyReplacement(nodes, value, r.Targets)
34 if err != nil {
35 return nil, err
36 }
37 }
38 return nodes, nil
39 }
40
41 func getReplacement(nodes []*yaml.RNode, r *types.Replacement) (*yaml.RNode, error) {
42 if r.SourceValue != nil && r.Source != nil {
43 return nil, fmt.Errorf("value and resource selectors are mutually exclusive")
44 }
45 if r.SourceValue != nil {
46 return yaml.NewScalarRNode(*r.SourceValue), nil
47 }
48
49 source, err := selectSourceNode(nodes, r.Source)
50 if err != nil {
51 return nil, err
52 }
53
54 if r.Source.FieldPath == "" {
55 r.Source.FieldPath = types.DefaultReplacementFieldPath
56 }
57 fieldPath := kyaml_utils.SmarterPathSplitter(r.Source.FieldPath, ".")
58
59 rn, err := source.Pipe(yaml.Lookup(fieldPath...))
60 if err != nil {
61 return nil, fmt.Errorf("error looking up replacement source: %w", err)
62 }
63 if rn.IsNilOrEmpty() {
64 return nil, fmt.Errorf("fieldPath `%s` is missing for replacement source %s", r.Source.FieldPath, r.Source.ResId)
65 }
66
67 return getRefinedValue(r.Source.Options, rn)
68 }
69
70 // selectSourceNode finds the node that matches the selector, returning
71 // an error if multiple or none are found
72 func selectSourceNode(nodes []*yaml.RNode, selector *types.SourceSelector) (*yaml.RNode, error) {
73 var matches []*yaml.RNode
74 for _, n := range nodes {
75 ids, err := utils.MakeResIds(n)
76 if err != nil {
77 return nil, fmt.Errorf("error getting node IDs: %w", err)
78 }
79 for _, id := range ids {
80 if id.IsSelectedBy(selector.ResId) {
81 if len(matches) > 0 {
82 return nil, fmt.Errorf(
83 "multiple matches for selector %s", selector)
84 }
85 matches = append(matches, n)
86 break
87 }
88 }
89 }
90 if len(matches) == 0 {
91 return nil, fmt.Errorf("nothing selected by %s", selector)
92 }
93 return matches[0], nil
94 }
95
96 func getRefinedValue(options *types.FieldOptions, rn *yaml.RNode) (*yaml.RNode, error) {
97 if options == nil || options.Delimiter == "" {
98 return rn, nil
99 }
100 if rn.YNode().Kind != yaml.ScalarNode {
101 return nil, fmt.Errorf("delimiter option can only be used with scalar nodes")
102 }
103 value := strings.Split(yaml.GetValue(rn), options.Delimiter)
104 if options.Index >= len(value) || options.Index < 0 {
105 return nil, fmt.Errorf("options.index %d is out of bounds for value %s", options.Index, yaml.GetValue(rn))
106 }
107 n := rn.Copy()
108 n.YNode().Value = value[options.Index]
109 return n, nil
110 }
111
112 func applyReplacement(nodes []*yaml.RNode, value *yaml.RNode, targetSelectors []*types.TargetSelector) ([]*yaml.RNode, error) {
113 for _, selector := range targetSelectors {
114 if selector.Select == nil {
115 return nil, errors.Errorf("target must specify resources to select")
116 }
117 if len(selector.FieldPaths) == 0 {
118 selector.FieldPaths = []string{types.DefaultReplacementFieldPath}
119 }
120 tsr, err := types.NewTargetSelectorRegex(selector)
121 if err != nil {
122 return nil, fmt.Errorf("error creating target selector: %w", err)
123 }
124 for _, possibleTarget := range nodes {
125 ids, err := utils.MakeResIds(possibleTarget)
126 if err != nil {
127 return nil, err
128 }
129
130 // filter targets by label and annotation selectors
131 selectByAnnoAndLabel, err := selectByAnnoAndLabel(possibleTarget, selector)
132 if err != nil {
133 return nil, err
134 }
135 if !selectByAnnoAndLabel {
136 continue
137 }
138
139 if tsr.RejectsAny(ids) {
140 continue
141 }
142
143 // filter targets by matching resource IDs
144 for _, id := range ids {
145 if tsr.Selects(id) {
146 err := copyValueToTarget(possibleTarget, value, selector)
147 if err != nil {
148 return nil, err
149 }
150 break
151 }
152 }
153 }
154 }
155 return nodes, nil
156 }
157
158 func selectByAnnoAndLabel(n *yaml.RNode, t *types.TargetSelector) (bool, error) {
159 if matchesSelect, err := matchesAnnoAndLabelSelector(n, t.Select); !matchesSelect || err != nil {
160 return false, err
161 }
162 for _, reject := range t.Reject {
163 if reject.AnnotationSelector == "" && reject.LabelSelector == "" {
164 continue
165 }
166 if m, err := matchesAnnoAndLabelSelector(n, reject); m || err != nil {
167 return false, err
168 }
169 }
170 return true, nil
171 }
172
173 func matchesAnnoAndLabelSelector(n *yaml.RNode, selector *types.Selector) (bool, error) {
174 r := resource.Resource{RNode: *n}
175 annoMatch, err := r.MatchesAnnotationSelector(selector.AnnotationSelector)
176 if err != nil {
177 return false, err
178 }
179 labelMatch, err := r.MatchesLabelSelector(selector.LabelSelector)
180 if err != nil {
181 return false, err
182 }
183 return annoMatch && labelMatch, nil
184 }
185
186 func copyValueToTarget(target *yaml.RNode, value *yaml.RNode, selector *types.TargetSelector) error {
187 for _, fp := range selector.FieldPaths {
188 createKind := yaml.Kind(0) // do not create
189 if selector.Options != nil && selector.Options.Create {
190 createKind = value.YNode().Kind
191 }
192
193 // Check if this fieldPath contains structured data access
194 if err := setValueInStructuredData(target, value, fp, createKind); err == nil {
195 // Successfully handled as structured data
196 continue
197 }
198
199 // Fall back to normal path handling
200 targetFieldList, err := target.Pipe(&yaml.PathMatcher{
201 Path: kyaml_utils.SmarterPathSplitter(fp, "."),
202 Create: createKind})
203 if err != nil {
204 return errors.WrapPrefixf(err, "%s", fieldRetrievalError(fp, createKind != 0))
205 }
206 targetFields, err := targetFieldList.Elements()
207 if err != nil {
208 return errors.WrapPrefixf(err, "%s", fieldRetrievalError(fp, createKind != 0))
209 }
210 if len(targetFields) == 0 {
211 return errors.Errorf("%s", fieldRetrievalError(fp, createKind != 0))
212 }
213
214 for _, t := range targetFields {
215 if err := setFieldValue(selector.Options, t, value); err != nil {
216 return fmt.Errorf("%w", err)
217 }
218 }
219 }
220 return nil
221 }
222
223 func fieldRetrievalError(fieldPath string, isCreate bool) string {
224 if isCreate {
225 return fmt.Sprintf("unable to find or create field %q in replacement target", fieldPath)
226 }
227 return fmt.Sprintf("unable to find field %q in replacement target", fieldPath)
228 }
229
230 func setFieldValue(options *types.FieldOptions, targetField *yaml.RNode, value *yaml.RNode) error {
231 value = value.Copy()
232 if options != nil && options.Delimiter != "" {
233 if targetField.YNode().Kind != yaml.ScalarNode {
234 return fmt.Errorf("delimiter option can only be used with scalar nodes")
235 }
236 tv := strings.Split(targetField.YNode().Value, options.Delimiter)
237 v := yaml.GetValue(value)
238 // TODO: Add a way to remove an element
239 switch {
240 case options.Index < 0: // prefix
241 tv = append([]string{v}, tv...)
242 case options.Index >= len(tv): // suffix
243 tv = append(tv, v)
244 default: // replace an element
245 tv[options.Index] = v
246 }
247 value.YNode().Value = strings.Join(tv, options.Delimiter)
248 }
249
250 if targetField.YNode().Kind == yaml.ScalarNode {
251 // For scalar, only copy the value (leave any type intact to auto-convert int->string or string->int)
252 targetField.YNode().Value = value.YNode().Value
253 } else {
254 targetField.SetYNode(value.YNode())
255 }
256
257 return nil
258 }
259
260 // setValueInStructuredData handles setting values within structured data (JSON/YAML) in scalar fields
261 func setValueInStructuredData(target *yaml.RNode, value *yaml.RNode, fieldPath string, createKind yaml.Kind) error {
262 pathParts := kyaml_utils.SmarterPathSplitter(fieldPath, ".")
263 if len(pathParts) < 2 {
264 return fmt.Errorf("not a structured data path")
265 }
266
267 // Find the potential scalar field that might contain structured data
268 var scalarFieldPath []string
269 var structuredDataPath []string
270 var foundScalar = false
271
272 // Try to find where the scalar field ends and structured data begins
273 for i := 1; i <= len(pathParts); i++ {
274 potentialScalarPath := pathParts[:i]
275 scalarField, err := target.Pipe(yaml.Lookup(potentialScalarPath...))
276 if err != nil {
277 continue
278 }
279 if scalarField != nil && scalarField.YNode().Kind == yaml.ScalarNode && i < len(pathParts) {
280 // Try to parse the scalar value as structured data
281 scalarValue := scalarField.YNode().Value
282 var parsedNode yaml.Node
283 if err := yaml.Unmarshal([]byte(scalarValue), &parsedNode); err == nil {
284 // Successfully parsed - this is structured data
285 scalarFieldPath = potentialScalarPath
286 structuredDataPath = pathParts[i:]
287 foundScalar = true
288 break
289 }
290 }
291 }
292
293 if !foundScalar {
294 return fmt.Errorf("no structured data found in path")
295 }
296
297 // Get the scalar field containing structured data
298 scalarField, err := target.Pipe(yaml.Lookup(scalarFieldPath...))
299 if err != nil {
300 return fmt.Errorf("%w", err)
301 }
302
303 // Parse the structured data
304 scalarValue := scalarField.YNode().Value
305 var parsedNode yaml.Node
306 if err := yaml.Unmarshal([]byte(scalarValue), &parsedNode); err != nil {
307 return fmt.Errorf("%w", err)
308 }
309
310 structuredData := yaml.NewRNode(&parsedNode)
311
312 // Navigate to the target location within the structured data
313 targetInStructured, err := structuredData.Pipe(&yaml.PathMatcher{
314 Path: structuredDataPath,
315 Create: createKind,
316 })
317 if err != nil {
318 return fmt.Errorf("%w", err)
319 }
320
321 targetFields, err := targetInStructured.Elements()
322 if err != nil {
323 return fmt.Errorf("%w", err)
324 }
325
326 if len(targetFields) == 0 {
327 return fmt.Errorf("unable to find field in structured data")
328 }
329
330 // Set the value in the structured data
331 for _, t := range targetFields {
332 if t.YNode().Kind == yaml.ScalarNode {
333 t.YNode().Value = value.YNode().Value
334 } else {
335 t.SetYNode(value.YNode())
336 }
337 }
338
339 // Serialize the modified structured data back to the scalar field
340 // Try to detect if original was JSON or YAML and preserve formatting
341 serializedData, err := serializeStructuredData(structuredData, scalarValue)
342 if err != nil {
343 return fmt.Errorf("%w", err)
344 }
345
346 // Update the original scalar field
347 scalarField.YNode().Value = serializedData
348
349 return nil
350 }
351
352 // serializeStructuredData handles the serialization of structured data back to string format
353 // preserving the original format (JSON vs YAML) and style (pretty vs compact)
354 func serializeStructuredData(structuredData *yaml.RNode, originalValue string) (string, error) {
355 firstChar := rune(strings.TrimSpace(originalValue)[0])
356 if firstChar == '{' || firstChar == '[' {
357 return serializeAsJSON(structuredData, originalValue)
358 }
359
360 // Fallback to YAML format
361 return serializeAsYAML(structuredData)
362 }
363
364 // serializeAsJSON converts structured data back to JSON format
365 func serializeAsJSON(structuredData *yaml.RNode, originalValue string) (string, error) {
366 modifiedData, err := structuredData.String()
367 if err != nil {
368 return "", fmt.Errorf("failed to serialize structured data: %w", err)
369 }
370
371 // Parse the YAML output as JSON
372 var jsonData interface{}
373 if err := yaml.Unmarshal([]byte(modifiedData), &jsonData); err != nil {
374 return "", fmt.Errorf("failed to unmarshal YAML data: %w", err)
375 }
376
377 // Check if original was pretty-printed by looking for newlines and indentation
378 if strings.Contains(originalValue, "\n") && strings.Contains(originalValue, " ") {
379 // Pretty-print the JSON to match original formatting
380 if prettyJSON, err := json.MarshalIndent(jsonData, "", " "); err == nil {
381 return string(prettyJSON), nil
382 }
383 }
384
385 // Compact JSON
386 if compactJSON, err := json.Marshal(jsonData); err == nil {
387 return string(compactJSON), nil
388 }
389
390 return "", fmt.Errorf("failed to marshal JSON data")
391 }
392
393 // serializeAsYAML converts structured data back to YAML format
394 func serializeAsYAML(structuredData *yaml.RNode) (string, error) {
395 modifiedData, err := structuredData.String()
396 if err != nil {
397 return "", fmt.Errorf("failed to serialize YAML data: %w", err)
398 }
399
400 return strings.TrimSpace(modifiedData), nil
401 }