mirror of
https://github.com/kubernetes-sigs/kustomize.git
synced 2026-05-21 06:21:43 +00:00
86 lines
2.2 KiB
Go
86 lines
2.2 KiB
Go
/*
|
|
Copyright 2018 The Kubernetes Authors.
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
you may not use this file except in compliance with the License.
|
|
You may obtain a copy of the License at
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
See the License for the specific language governing permissions and
|
|
limitations under the License.
|
|
*/
|
|
|
|
package transformer
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
jsonpatch "github.com/evanphx/json-patch"
|
|
"github.com/pkg/errors"
|
|
"sigs.k8s.io/kustomize/v3/pkg/resid"
|
|
"sigs.k8s.io/kustomize/v3/pkg/resmap"
|
|
"sigs.k8s.io/kustomize/v3/pkg/transformers"
|
|
"sigs.k8s.io/yaml"
|
|
)
|
|
|
|
// patchJson6902JSONTransformer applies patches.
|
|
type patchJson6902JSONTransformer struct {
|
|
target resid.ResId
|
|
patch jsonpatch.Patch
|
|
rawOp []byte
|
|
}
|
|
|
|
var _ transformers.Transformer = &patchJson6902JSONTransformer{}
|
|
|
|
// newPatchJson6902JSONTransformer constructs a PatchJson6902 transformer.
|
|
func newPatchJson6902JSONTransformer(
|
|
id resid.ResId, rawOp []byte) (transformers.Transformer, error) {
|
|
op := rawOp
|
|
var err error
|
|
|
|
if len(op) == 0 {
|
|
return nil, fmt.Errorf("json patch file is empty %v", id)
|
|
}
|
|
|
|
if !isJsonFormat(op) {
|
|
// if it isn't JSON, try to parse it as YAML
|
|
op, err = yaml.YAMLToJSON(rawOp)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
decodedPatch, err := jsonpatch.DecodePatch(op)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(decodedPatch) == 0 {
|
|
return transformers.NewNoOpTransformer(), nil
|
|
}
|
|
return &patchJson6902JSONTransformer{target: id, patch: decodedPatch, rawOp: rawOp}, nil
|
|
}
|
|
|
|
// Transform apply the json patches on top of the base resources.
|
|
func (t *patchJson6902JSONTransformer) Transform(m resmap.ResMap) error {
|
|
obj, err := m.GetById(t.target)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
rawObj, err := obj.MarshalJSON()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
modifiedObj, err := t.patch.Apply(rawObj)
|
|
if err != nil {
|
|
return errors.Wrapf(err, "failed to apply json patch '%s'", string(t.rawOp))
|
|
}
|
|
err = obj.UnmarshalJSON(modifiedObj)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|