add conflict check

This commit is contained in:
Donny Xia
2021-03-24 10:41:37 -07:00
parent 5ed2067be9
commit ccb95ab269
3 changed files with 44 additions and 4 deletions

View File

@@ -6,6 +6,7 @@ package types
import (
"bytes"
"encoding/json"
"fmt"
"sigs.k8s.io/yaml"
)
@@ -189,15 +190,28 @@ func (k *Kustomization) FixKustomizationPostUnmarshalling() {
// FixKustomizationPreMarshalling fixes things
// that should occur after the kustomization file
// has been processed.
func (k *Kustomization) FixKustomizationPreMarshalling() {
func (k *Kustomization) FixKustomizationPreMarshalling() error {
// PatchesJson6902 should be under the Patches field.
k.Patches = append(k.Patches, k.PatchesJson6902...)
k.PatchesJson6902 = nil
if l := labelFromCommonLabels(k.CommonLabels); l != nil {
k.Labels = append(k.Labels, *l)
// this fix is not in FixKustomizationPostUnmarshalling because
// it will break some commands like `create` and `add`. those
// commands depend on 'commonLabels' field
if cl := labelFromCommonLabels(k.CommonLabels); cl != nil {
// check conflicts between commonLabels and labels
for _, l := range k.Labels {
for k := range l.Pairs {
if _, exist := cl.Pairs[k]; exist {
return fmt.Errorf("label name '%s' exists in both commonLabels and labels", k)
}
}
}
k.Labels = append(k.Labels, *cl)
k.CommonLabels = nil
}
return nil
}
func (k *Kustomization) EnforceFields() []string {

View File

@@ -39,6 +39,9 @@ func RunFix(fSys filesys.FileSystem) error {
return err
}
m.FixKustomizationPreMarshalling()
err = m.FixKustomizationPreMarshalling()
if err != nil {
return err
}
return mf.Write(m)
}

View File

@@ -175,3 +175,26 @@ kind: Kustomization
t.Errorf("Mismatch (-expected, +actual):\n%s", diff)
}
}
func TestFixOutdatedCommonLabelsDuplicate(t *testing.T) {
kustomizationContentWithOutdatedCommonLabels := []byte(`
commonLabels:
foo: bar
labels:
- pairs:
foo: baz
a: b
`)
fSys := filesys.MakeFsInMemory()
testutils_test.WriteTestKustomizationWith(fSys, kustomizationContentWithOutdatedCommonLabels)
cmd := NewCmdFix(fSys)
err := cmd.RunE(cmd, nil)
if err == nil {
t.Fatalf("expect error")
}
expectedErr := "label name 'foo' exists in both commonLabels and labels"
if err.Error() != expectedErr {
t.Fatalf("error message '%s' doesn't match expected", err.Error())
}
}