combine transformers

This commit is contained in:
zoncoen
2018-11-15 18:32:07 +09:00
parent c1e7f1b957
commit d481dbad62
8 changed files with 44 additions and 268 deletions

View File

@@ -149,14 +149,17 @@ func (n ResId) Namespace() string {
return n.namespace return n.namespace
} }
// CopyWithNewPrefix make a new copy from current ResId and append a new prefix // CopyWithNewPrefixSuffix make a new copy from current ResId and append a new prefix and suffix
func (n ResId) CopyWithNewPrefix(p string) ResId { func (n ResId) CopyWithNewPrefixSuffix(p, s string) ResId {
return ResId{gvKind: n.gvKind, name: n.name, prefix: n.concatPrefix(p), suffix: n.suffix, namespace: n.namespace} prefix := n.prefix
} if p != "" {
prefix = n.concatPrefix(p)
// CopyWithNewSuffix make a new copy from current ResId and append a new suffix }
func (n ResId) CopyWithNewSuffix(p string) ResId { suffix := n.suffix
return ResId{gvKind: n.gvKind, name: n.name, prefix: n.prefix, suffix: n.concatSuffix(p), namespace: n.namespace} if s != "" {
suffix = n.concatSuffix(s)
}
return ResId{gvKind: n.gvKind, name: n.name, prefix: prefix, suffix: suffix, namespace: n.namespace}
} }
// CopyWithNewNamespace make a new copy from current ResId and set a new namespace // CopyWithNewNamespace make a new copy from current ResId and set a new namespace

View File

@@ -282,8 +282,11 @@ func (kt *KustTarget) newTransformer(patches []*resource.Resource) (transformers
r = append(r, t) r = append(r, t)
r = append(r, transformers.NewNamespaceTransformer( r = append(r, transformers.NewNamespaceTransformer(
string(kt.kustomization.Namespace), kt.tConfig.NameSpace)) string(kt.kustomization.Namespace), kt.tConfig.NameSpace))
t, err = transformers.NewNamePrefixTransformer( t, err = transformers.NewNamePrefixSuffixTransformer(
string(kt.kustomization.NamePrefix), kt.tConfig.NamePrefix) string(kt.kustomization.NamePrefix),
"", // TODO(zoncoen): pass the name suffix
kt.tConfig.NamePrefix,
)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -26,7 +26,6 @@ import (
func GetDefaultFieldSpecs() []byte { func GetDefaultFieldSpecs() []byte {
configData := [][]byte{ configData := [][]byte{
[]byte(namePrefixFieldSpecs), []byte(namePrefixFieldSpecs),
[]byte(nameSuffixFieldSpecs),
[]byte(commonLabelFieldSpecs), []byte(commonLabelFieldSpecs),
[]byte(commonAnnotationFieldSpecs), []byte(commonAnnotationFieldSpecs),
[]byte(namespaceFieldSpecs), []byte(namespaceFieldSpecs),
@@ -41,7 +40,6 @@ func GetDefaultFieldSpecs() []byte {
func GetDefaultFieldSpecsAsMap() map[string]string { func GetDefaultFieldSpecsAsMap() map[string]string {
result := make(map[string]string) result := make(map[string]string)
result["nameprefix"] = namePrefixFieldSpecs result["nameprefix"] = namePrefixFieldSpecs
result["namesuffix"] = nameSuffixFieldSpecs
result["commonlabels"] = commonLabelFieldSpecs result["commonlabels"] = commonLabelFieldSpecs
result["commonannotations"] = commonAnnotationFieldSpecs result["commonannotations"] = commonAnnotationFieldSpecs
result["namespace"] = namespaceFieldSpecs result["namespace"] = namespaceFieldSpecs

View File

@@ -1,24 +0,0 @@
/*
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 defaultconfig
const (
nameSuffixFieldSpecs = `
nameSuffix:
- path: metadata/name
`
)

View File

@@ -1,98 +0,0 @@
/*
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 transformers
import (
"reflect"
"testing"
"sigs.k8s.io/kustomize/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/pkg/resid"
"sigs.k8s.io/kustomize/pkg/resmap"
"sigs.k8s.io/kustomize/pkg/resource"
)
func TestPrefixNameRun(t *testing.T) {
rf := resource.NewFactory(
kunstruct.NewKunstructuredFactoryImpl())
m := resmap.ResMap{
resid.NewResId(cmap, "cm1"): rf.FromMap(
map[string]interface{}{
"apiVersion": "v1",
"kind": "ConfigMap",
"metadata": map[string]interface{}{
"name": "cm1",
},
}),
resid.NewResId(cmap, "cm2"): rf.FromMap(
map[string]interface{}{
"apiVersion": "v1",
"kind": "ConfigMap",
"metadata": map[string]interface{}{
"name": "cm2",
},
}),
resid.NewResId(crd, "crd"): rf.FromMap(
map[string]interface{}{
"apiVersion": "apiextensions.k8s.io/v1beta1",
"kind": "CustomResourceDefinition",
"metadata": map[string]interface{}{
"name": "crd",
},
}),
}
expected := resmap.ResMap{
resid.NewResIdWithPrefix(cmap, "cm1", "someprefix-"): rf.FromMap(
map[string]interface{}{
"apiVersion": "v1",
"kind": "ConfigMap",
"metadata": map[string]interface{}{
"name": "someprefix-cm1",
},
}),
resid.NewResIdWithPrefix(cmap, "cm2", "someprefix-"): rf.FromMap(
map[string]interface{}{
"apiVersion": "v1",
"kind": "ConfigMap",
"metadata": map[string]interface{}{
"name": "someprefix-cm2",
},
}),
resid.NewResId(crd, "crd"): rf.FromMap(
map[string]interface{}{
"apiVersion": "apiextensions.k8s.io/v1beta1",
"kind": "CustomResourceDefinition",
"metadata": map[string]interface{}{
"name": "crd",
},
}),
}
npt, err := NewNamePrefixTransformer(
"someprefix-", defaultTransformerConfig.NamePrefix)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
err = npt.Transform(m)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !reflect.DeepEqual(m, expected) {
err = expected.ErrorIfNotEqual(m)
t.Fatalf("actual doesn't match expected: %v", err)
}
}

View File

@@ -26,40 +26,41 @@ import (
"sigs.k8s.io/kustomize/pkg/transformers/config" "sigs.k8s.io/kustomize/pkg/transformers/config"
) )
// namePrefixTransformer contains the prefix and the FieldSpecs // namePrefixSuffixTransformer contains the prefix, suffix, and the FieldSpecs
// for each field needing a name prefix. // for each field needing a name prefix and suffix.
type namePrefixTransformer struct { type namePrefixSuffixTransformer struct {
prefix string prefix string
suffix string
fieldSpecsToUse []config.FieldSpec fieldSpecsToUse []config.FieldSpec
fieldSpecsToSkip []config.FieldSpec fieldSpecsToSkip []config.FieldSpec
} }
var _ Transformer = &namePrefixTransformer{} var _ Transformer = &namePrefixSuffixTransformer{}
var prefixFieldSpecsToSkip = []config.FieldSpec{ var prefixSuffixFieldSpecsToSkip = []config.FieldSpec{
{ {
Gvk: gvk.Gvk{Kind: "CustomResourceDefinition"}, Gvk: gvk.Gvk{Kind: "CustomResourceDefinition"},
}, },
} }
// deprecateNamePrefixFieldSpec will be moved into prefixFieldSpecsToSkip in next release // deprecateNamePrefixSuffixFieldSpec will be moved into prefixSuffixFieldSpecsToSkip in next release
var deprecateNamePrefixFieldSpec = config.FieldSpec{ var deprecateNamePrefixSuffixFieldSpec = config.FieldSpec{
Gvk: gvk.Gvk{Kind: "Namespace"}, Gvk: gvk.Gvk{Kind: "Namespace"},
} }
// NewNamePrefixTransformer construct a namePrefixTransformer. // NewNamePrefixSuffixTransformer construct a namePrefixSuffixTransformer.
func NewNamePrefixTransformer(np string, pc []config.FieldSpec) (Transformer, error) { func NewNamePrefixSuffixTransformer(np, ns string, pc []config.FieldSpec) (Transformer, error) {
if len(np) == 0 { if len(np) == 0 && len(ns) == 0 {
return NewNoOpTransformer(), nil return NewNoOpTransformer(), nil
} }
if pc == nil { if pc == nil {
return nil, errors.New("fieldSpecs is not expected to be nil") return nil, errors.New("fieldSpecs is not expected to be nil")
} }
return &namePrefixTransformer{fieldSpecsToUse: pc, prefix: np, fieldSpecsToSkip: prefixFieldSpecsToSkip}, nil return &namePrefixSuffixTransformer{fieldSpecsToUse: pc, prefix: np, suffix: ns, fieldSpecsToSkip: prefixSuffixFieldSpecsToSkip}, nil
} }
// Transform prepends the name prefix. // Transform prepends the name prefix and appends the name suffix.
func (o *namePrefixTransformer) Transform(m resmap.ResMap) error { func (o *namePrefixSuffixTransformer) Transform(m resmap.ResMap) error {
// Fill map "mf" with entries subject to name modification, and // Fill map "mf" with entries subject to name modification, and
// delete these entries from "m", so that for now m retains only // delete these entries from "m", so that for now m retains only
// the entries whose names will not be modified. // the entries whose names will not be modified.
@@ -79,29 +80,29 @@ func (o *namePrefixTransformer) Transform(m resmap.ResMap) error {
} }
for id := range mf { for id := range mf {
if id.Gvk().IsSelected(&deprecateNamePrefixFieldSpec.Gvk) { if id.Gvk().IsSelected(&deprecateNamePrefixSuffixFieldSpec.Gvk) {
log.Println("Adding nameprefix to Namespace resource will be deprecated in next release.") log.Println("Adding nameprefix and namesuffix to Namespace resource will be deprecated in next release.")
} }
objMap := mf[id].Map() objMap := mf[id].Map()
for _, path := range o.fieldSpecsToUse { for _, path := range o.fieldSpecsToUse {
if !id.Gvk().IsSelected(&path.Gvk) { if !id.Gvk().IsSelected(&path.Gvk) {
continue continue
} }
err := mutateField(objMap, path.PathSlice(), path.CreateIfNotPresent, o.addPrefix) err := mutateField(objMap, path.PathSlice(), path.CreateIfNotPresent, o.addPrefixSuffix)
if err != nil { if err != nil {
return err return err
} }
newId := id.CopyWithNewPrefix(o.prefix) newId := id.CopyWithNewPrefixSuffix(o.prefix, o.suffix)
m[newId] = mf[id] m[newId] = mf[id]
} }
} }
return nil return nil
} }
func (o *namePrefixTransformer) addPrefix(in interface{}) (interface{}, error) { func (o *namePrefixSuffixTransformer) addPrefixSuffix(in interface{}) (interface{}, error) {
s, ok := in.(string) s, ok := in.(string)
if !ok { if !ok {
return nil, fmt.Errorf("%#v is expected to be %T", in, s) return nil, fmt.Errorf("%#v is expected to be %T", in, s)
} }
return o.prefix + s, nil return fmt.Sprintf("%s%s%s", o.prefix, s, o.suffix), nil
} }

View File

@@ -26,7 +26,7 @@ import (
"sigs.k8s.io/kustomize/pkg/resource" "sigs.k8s.io/kustomize/pkg/resource"
) )
func TestSuffixNameRun(t *testing.T) { func TestPrefixSuffixNameRun(t *testing.T) {
rf := resource.NewFactory( rf := resource.NewFactory(
kunstruct.NewKunstructuredFactoryImpl()) kunstruct.NewKunstructuredFactoryImpl())
m := resmap.ResMap{ m := resmap.ResMap{
@@ -56,20 +56,20 @@ func TestSuffixNameRun(t *testing.T) {
}), }),
} }
expected := resmap.ResMap{ expected := resmap.ResMap{
resid.NewResIdWithSuffix(cmap, "cm1", "-somesuffix"): rf.FromMap( resid.NewResIdWithPrefixSuffix(cmap, "cm1", "someprefix-", "-somesuffix"): rf.FromMap(
map[string]interface{}{ map[string]interface{}{
"apiVersion": "v1", "apiVersion": "v1",
"kind": "ConfigMap", "kind": "ConfigMap",
"metadata": map[string]interface{}{ "metadata": map[string]interface{}{
"name": "cm1-somesuffix", "name": "someprefix-cm1-somesuffix",
}, },
}), }),
resid.NewResIdWithSuffix(cmap, "cm2", "-somesuffix"): rf.FromMap( resid.NewResIdWithPrefixSuffix(cmap, "cm2", "someprefix-", "-somesuffix"): rf.FromMap(
map[string]interface{}{ map[string]interface{}{
"apiVersion": "v1", "apiVersion": "v1",
"kind": "ConfigMap", "kind": "ConfigMap",
"metadata": map[string]interface{}{ "metadata": map[string]interface{}{
"name": "cm2-somesuffix", "name": "someprefix-cm2-somesuffix",
}, },
}), }),
resid.NewResId(crd, "crd"): rf.FromMap( resid.NewResId(crd, "crd"): rf.FromMap(
@@ -82,12 +82,12 @@ func TestSuffixNameRun(t *testing.T) {
}), }),
} }
npt, err := NewNameSuffixTransformer( npst, err := NewNamePrefixSuffixTransformer(
"-somesuffix", defaultTransformerConfig.NameSuffix) "someprefix-", "-somesuffix", defaultTransformerConfig.NamePrefix)
if err != nil { if err != nil {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
err = npt.Transform(m) err = npst.Transform(m)
if err != nil { if err != nil {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }

View File

@@ -1,107 +0,0 @@
/*
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 transformers
import (
"errors"
"fmt"
"log"
"sigs.k8s.io/kustomize/pkg/gvk"
"sigs.k8s.io/kustomize/pkg/resmap"
"sigs.k8s.io/kustomize/pkg/transformers/config"
)
// nameSuffixTransformer contains the suffix and the FieldSpecs
// for each field needing a name suffix.
type nameSuffixTransformer struct {
suffix string
fieldSpecsToUse []config.FieldSpec
fieldSpecsToSkip []config.FieldSpec
}
var _ Transformer = &nameSuffixTransformer{}
var suffixFieldSpecsToSkip = []config.FieldSpec{
{
Gvk: gvk.Gvk{Kind: "CustomResourceDefinition"},
},
}
// deprecateNameSuffixFieldSpec will be moved into suffixFieldSpecsToSkip in next release
var deprecateNameSuffixFieldSpec = config.FieldSpec{
Gvk: gvk.Gvk{Kind: "Namespace"},
}
// NewNameSuffixTransformer construct a nameSuffixTransformer.
func NewNameSuffixTransformer(ns string, pc []config.FieldSpec) (Transformer, error) {
if len(ns) == 0 {
return NewNoOpTransformer(), nil
}
if pc == nil {
return nil, errors.New("fieldSpecs is not expected to be nil")
}
return &nameSuffixTransformer{fieldSpecsToUse: pc, suffix: ns, fieldSpecsToSkip: suffixFieldSpecsToSkip}, nil
}
// Transform appends the name suffix.
func (o *nameSuffixTransformer) Transform(m resmap.ResMap) error {
// Fill map "mf" with entries subject to name modification, and
// delete these entries from "m", so that for now m retains only
// the entries whose names will not be modified.
mf := resmap.ResMap{}
for id := range m {
found := false
for _, path := range o.fieldSpecsToSkip {
if id.Gvk().IsSelected(&path.Gvk) {
found = true
break
}
}
if !found {
mf[id] = m[id]
delete(m, id)
}
}
for id := range mf {
if id.Gvk().IsSelected(&deprecateNameSuffixFieldSpec.Gvk) {
log.Println("Adding name suffix to Namespace resource will be deprecated in next release.")
}
objMap := mf[id].Map()
for _, path := range o.fieldSpecsToUse {
if !id.Gvk().IsSelected(&path.Gvk) {
continue
}
err := mutateField(objMap, path.PathSlice(), path.CreateIfNotPresent, o.addSuffix)
if err != nil {
return err
}
newId := id.CopyWithNewSuffix(o.suffix)
m[newId] = mf[id]
}
}
return nil
}
func (o *nameSuffixTransformer) addSuffix(in interface{}) (interface{}, error) {
s, ok := in.(string)
if !ok {
return nil, fmt.Errorf("%#v is expectd to be %T", in, s)
}
return s + o.suffix, nil
}