...

Source file src/sigs.k8s.io/kustomize/api/filters/patchjson6902/patchjson6902.go

Documentation: sigs.k8s.io/kustomize/api/filters/patchjson6902

     1  // Copyright 2020 The Kubernetes Authors.
     2  // SPDX-License-Identifier: Apache-2.0
     3  
     4  package patchjson6902
     5  
     6  import (
     7  	"strings"
     8  
     9  	jsonpatch "gopkg.in/evanphx/json-patch.v4"
    10  	"sigs.k8s.io/kustomize/kyaml/kio"
    11  	"sigs.k8s.io/kustomize/kyaml/yaml"
    12  	k8syaml "sigs.k8s.io/yaml"
    13  )
    14  
    15  type Filter struct {
    16  	Patch string
    17  
    18  	decodedPatch jsonpatch.Patch
    19  }
    20  
    21  var _ kio.Filter = Filter{}
    22  
    23  func (pf Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) {
    24  	decodedPatch, err := pf.decodePatch()
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  	pf.decodedPatch = decodedPatch
    29  	return kio.FilterAll(yaml.FilterFunc(pf.run)).Filter(nodes)
    30  }
    31  
    32  func (pf Filter) decodePatch() (jsonpatch.Patch, error) {
    33  	patch := pf.Patch
    34  	// If the patch doesn't look like a JSON6902 patch, we
    35  	// try to parse it to json.
    36  	if !strings.HasPrefix(pf.Patch, "[") {
    37  		p, err := k8syaml.YAMLToJSON([]byte(patch))
    38  		if err != nil {
    39  			return nil, err
    40  		}
    41  		patch = string(p)
    42  	}
    43  	decodedPatch, err := jsonpatch.DecodePatch([]byte(patch))
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  	return decodedPatch, nil
    48  }
    49  
    50  func (pf Filter) run(node *yaml.RNode) (*yaml.RNode, error) {
    51  	// We don't actually use the kyaml library for manipulating the
    52  	// yaml here. We just marshal it to json and rely on the
    53  	// jsonpatch library to take care of applying the patch.
    54  	// This means ordering might not be preserved with this filter.
    55  	b, err := node.MarshalJSON()
    56  	if err != nil {
    57  		return nil, err
    58  	}
    59  	res, err := pf.decodedPatch.Apply(b)
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  	err = node.UnmarshalJSON(res)
    64  	return node, err
    65  }
    66  

View as plain text