Add strategic merge patch filter based on kyaml libraries

This commit is contained in:
Morten Torkildsen
2020-04-03 13:25:50 -07:00
parent 0f3d5c80e4
commit 98c08b2b66
10 changed files with 385 additions and 111 deletions

View File

@@ -0,0 +1,6 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
// Package patchstrategicmerge contains a kio.Filter implementation of the
// kustomize strategic merge patch transformer.
package patchstrategicmerge

View File

@@ -0,0 +1,49 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package patchstrategicmerge
import (
"bytes"
"log"
"os"
"sigs.k8s.io/kustomize/kyaml/kio"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
func ExampleFilter() {
err := kio.Pipeline{
Inputs: []kio.Reader{&kio.ByteReader{Reader: bytes.NewBufferString(`
apiVersion: example.com/v1
kind: Foo
metadata:
name: instance
spec:
replicas: 3
`)}},
Filters: []kio.Filter{Filter{
Patch: yaml.MustParse(`
spec:
template:
containers:
- image: nginx
`),
}},
Outputs: []kio.Writer{kio.ByteWriter{Writer: os.Stdout}},
}.Execute()
if err != nil {
log.Fatal(err)
}
// Output:
// apiVersion: example.com/v1
// kind: Foo
// metadata:
// name: instance
// spec:
// replicas: 3
// template:
// containers:
// - image: nginx
}

View File

@@ -0,0 +1,21 @@
package patchstrategicmerge
import (
"sigs.k8s.io/kustomize/kyaml/kio"
"sigs.k8s.io/kustomize/kyaml/yaml"
"sigs.k8s.io/kustomize/kyaml/yaml/merge2"
)
type Filter struct {
Patch *yaml.RNode
}
var _ kio.Filter = Filter{}
func (pf Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) {
return kio.FilterAll(yaml.FilterFunc(pf.run)).Filter(nodes)
}
func (pf Filter) run(node *yaml.RNode) (*yaml.RNode, error) {
return merge2.Merge(pf.Patch, node)
}

View File

@@ -0,0 +1,82 @@
package patchstrategicmerge
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
filtertest "sigs.k8s.io/kustomize/api/testutils/filtertest"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
func TestFilter(t *testing.T) {
testCases := map[string]struct {
input string
patch *yaml.RNode
expected string
}{
"simple patch": {
input: `
apiVersion: apps/v1
metadata:
name: myDeploy
kind: Deployment
`,
patch: yaml.MustParse(`
metadata:
name: yourDeploy
`),
expected: `
apiVersion: apps/v1
metadata:
name: yourDeploy
kind: Deployment
`,
},
"nested patch": {
input: `
apiVersion: apps/v1
metadata:
name: myDeploy
kind: Deployment
spec:
containers:
- name: nginx
args:
- abc
`,
patch: yaml.MustParse(`
spec:
containers:
- name: nginx
args:
- def
`),
expected: `
apiVersion: apps/v1
metadata:
name: myDeploy
kind: Deployment
spec:
containers:
- name: nginx
args:
- def
`,
},
}
for tn, tc := range testCases {
t.Run(tn, func(t *testing.T) {
f := Filter{
Patch: tc.patch,
}
if !assert.Equal(t,
strings.TrimSpace(tc.expected),
strings.TrimSpace(
filtertest.RunFilter(t, tc.input, f))) {
t.FailNow()
}
})
}
}