Debian Codegraph @

plugin/builtin/patchstrategicmergetransformer/PatchStrategicMergeTransformer.go

raw
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 //go:generate pluginator
5 package main
6
7 import (
8 "fmt"
9
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/yaml"
14 )
15
16 type plugin struct {
17 loadedPatches []*resource.Resource
18 Paths []types.PatchStrategicMerge `json:"paths,omitempty" yaml:"paths,omitempty"`
19 Patches string `json:"patches,omitempty" yaml:"patches,omitempty"`
20 }
21
22 var KustomizePlugin plugin //nolint:gochecknoglobals
23
24 func (p *plugin) Config(
25 h *resmap.PluginHelpers, c []byte) (err error) {
26 err = yaml.Unmarshal(c, p)
27 if err != nil {
28 return err
29 }
30 if len(p.Paths) == 0 && p.Patches == "" {
31 return fmt.Errorf("empty file path and empty patch content")
32 }
33 if len(p.Paths) != 0 {
34 patches, err := loadFromPaths(h, p.Paths)
35 if err != nil {
36 return err
37 }
38 p.loadedPatches = append(p.loadedPatches, patches...)
39 }
40 if p.Patches != "" {
41 patches, err := h.ResmapFactory().RF().SliceFromBytes([]byte(p.Patches))
42 if err != nil {
43 return err
44 }
45 p.loadedPatches = append(p.loadedPatches, patches...)
46 }
47 if len(p.loadedPatches) == 0 {
48 return fmt.Errorf(
49 "patch appears to be empty; files=%v, Patch=%s", p.Paths, p.Patches)
50 }
51 return nil
52 }
53
54 func loadFromPaths(
55 h *resmap.PluginHelpers,
56 paths []types.PatchStrategicMerge) (
57 result []*resource.Resource, err error) {
58 var patches []*resource.Resource
59 for _, path := range paths {
60 // For legacy reasons, attempt to treat the path string as
61 // actual patch content.
62 patches, err = h.ResmapFactory().RF().SliceFromBytes([]byte(path))
63 if err != nil {
64 // Failing that, treat it as a file path.
65 patches, err = h.ResmapFactory().RF().SliceFromPatches(
66 h.Loader(), []types.PatchStrategicMerge{path})
67 if err != nil {
68 return
69 }
70 }
71 result = append(result, patches...)
72 }
73 return
74 }
75
76 func (p *plugin) Transform(m resmap.ResMap) error {
77 for _, patch := range p.loadedPatches {
78 target, err := m.GetById(patch.OrgId())
79 if err != nil {
80 return err
81 }
82 if err = m.ApplySmPatch(
83 resource.MakeIdSet([]*resource.Resource{target}), patch); err != nil {
84 return err
85 }
86 }
87 return nil
88 }