Patchtransformers - drop copied code, improve deletion handling.

This commit is contained in:
jregan
2020-11-29 16:09:32 -08:00
parent c9ab1270fa
commit 4a55a07c14
12 changed files with 654 additions and 205 deletions

View File

@@ -9,9 +9,7 @@ import (
"strings"
jsonpatch "github.com/evanphx/json-patch"
"github.com/pkg/errors"
"sigs.k8s.io/kustomize/api/filters/patchjson6902"
"sigs.k8s.io/kustomize/api/filters/patchstrategicmerge"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
"sigs.k8s.io/kustomize/api/types"
@@ -45,7 +43,6 @@ func (p *plugin) Config(
return fmt.Errorf(
"patch and path can't be set at the same time\n%s", string(c))
}
if p.Path != "" {
loaded, loadErr := h.Loader().Load(p.Path)
if loadErr != nil {
@@ -92,66 +89,13 @@ func (p *plugin) transformStrategicMerge(m resmap.ResMap, patch *resource.Resour
if err != nil {
return err
}
return p.applySMPatch(target, patch)
return target.ApplySmPatch(patch)
}
resources, err := m.Select(*p.Target)
selected, err := m.Select(*p.Target)
if err != nil {
return err
}
for _, res := range resources {
patchCopy := patch.DeepCopy()
patchCopy.SetName(res.GetName())
patchCopy.SetNamespace(res.GetNamespace())
patchCopy.SetGvk(res.GetGvk())
err := p.applySMPatch(res, patchCopy)
if err != nil {
// Check for an error string from UnmarshalJSON that's indicative
// of an object that's missing basic KRM fields, and thus may have been
// entirely deleted (an acceptable outcome). This error handling should
// be deleted along with use of ResMap and apimachinery functions like
// UnmarshalJSON.
if !strings.Contains(err.Error(), "Object 'Kind' is missing") {
// Some unknown error, let it through.
return err
}
if !res.IsEmpty() {
return errors.Wrapf(
err, "with unexpectedly non-empty object map of size %d",
len(res.Map()))
}
// Fall through to handle deleted object.
}
if res.IsEmpty() {
// This means all fields have been removed from the object.
// This can happen if a patch required deletion of the
// entire resource (not just a part of it). This means
// the overall resmap must shrink by one.
err = m.Remove(res.CurId())
if err != nil {
return err
}
}
}
return nil
}
// applySMPatch applies the provided strategic merge patch to the
// given resource.
func (p *plugin) applySMPatch(resource, patch *resource.Resource) error {
node, err := filtersutil.GetRNode(patch)
if err != nil {
return err
}
n, ns := resource.GetName(), resource.GetNamespace()
err = filtersutil.ApplyToJSON(patchstrategicmerge.Filter{
Patch: node,
}, resource)
if !resource.IsEmpty() {
resource.SetName(n)
resource.SetNamespace(ns)
}
return err
return m.ApplySmPatch(resource.MakeIdSet(selected), patch)
}
// transformJson6902 applies the provided json6902 patch

View File

@@ -4,7 +4,6 @@ go 1.15
require (
github.com/evanphx/json-patch v4.5.0+incompatible
github.com/pkg/errors v0.8.1
sigs.k8s.io/kustomize/api v0.6.5
sigs.k8s.io/kustomize/kyaml v0.9.4
sigs.k8s.io/yaml v1.2.0