File: patchjson6902.go

package info (click to toggle)
golang-k8s-sigs-kustomize-api 0.19.0%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 3,732 kB
  • sloc: makefile: 206; sh: 67
file content (65 lines) | stat: -rw-r--r-- 1,556 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

package patchjson6902

import (
	"strings"

	jsonpatch "github.com/evanphx/json-patch/v5"
	"sigs.k8s.io/kustomize/kyaml/kio"
	"sigs.k8s.io/kustomize/kyaml/yaml"
	k8syaml "sigs.k8s.io/yaml"
)

type Filter struct {
	Patch string

	decodedPatch jsonpatch.Patch
}

var _ kio.Filter = Filter{}

func (pf Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) {
	decodedPatch, err := pf.decodePatch()
	if err != nil {
		return nil, err
	}
	pf.decodedPatch = decodedPatch
	return kio.FilterAll(yaml.FilterFunc(pf.run)).Filter(nodes)
}

func (pf Filter) decodePatch() (jsonpatch.Patch, error) {
	patch := pf.Patch
	// If the patch doesn't look like a JSON6902 patch, we
	// try to parse it to json.
	if !strings.HasPrefix(pf.Patch, "[") {
		p, err := k8syaml.YAMLToJSON([]byte(patch))
		if err != nil {
			return nil, err
		}
		patch = string(p)
	}
	decodedPatch, err := jsonpatch.DecodePatch([]byte(patch))
	if err != nil {
		return nil, err
	}
	return decodedPatch, nil
}

func (pf Filter) run(node *yaml.RNode) (*yaml.RNode, error) {
	// We don't actually use the kyaml library for manipulating the
	// yaml here. We just marshal it to json and rely on the
	// jsonpatch library to take care of applying the patch.
	// This means ordering might not be preserved with this filter.
	b, err := node.MarshalJSON()
	if err != nil {
		return nil, err
	}
	res, err := pf.decodedPatch.Apply(b)
	if err != nil {
		return nil, err
	}
	err = node.UnmarshalJSON(res)
	return node, err
}