Uniform unmarshal function

This commit is contained in:
Donny Xia
2020-07-14 17:01:11 -07:00
parent ec9ae3d7b0
commit 897698fb29
4 changed files with 44 additions and 13 deletions

View File

@@ -4,7 +4,6 @@
package target
import (
"bytes"
"encoding/json"
"fmt"
"strings"
@@ -60,7 +59,7 @@ func (kt *KustTarget) Load() error {
return err
}
var k types.Kustomization
err = unmarshal(content, &k)
err = k.Unmarshal(content)
if err != nil {
return err
}
@@ -104,16 +103,6 @@ func loadKustFile(ldr ifc.Loader) ([]byte, error) {
}
}
func unmarshal(y []byte, o interface{}) error {
j, err := yaml.YAMLToJSON(y)
if err != nil {
return err
}
dec := json.NewDecoder(bytes.NewReader(j))
dec.DisallowUnknownFields()
return dec.Decode(o)
}
// MakeCustomizedResMap creates a fully customized ResMap
// per the instructions contained in its kustomiztion instance.
func (kt *KustTarget) MakeCustomizedResMap() (resmap.ResMap, error) {

View File

@@ -3,6 +3,13 @@
package types
import (
"bytes"
"encoding/json"
"sigs.k8s.io/yaml"
)
const (
KustomizationVersion = "kustomize.config.k8s.io/v1beta1"
KustomizationKind = "Kustomization"
@@ -165,3 +172,20 @@ func (k *Kustomization) EnforceFields() []string {
}
return errs
}
// Unmarshal replace k with the content in YAML input y
func (k *Kustomization) Unmarshal(y []byte) error {
j, err := yaml.YAMLToJSON(y)
if err != nil {
return err
}
dec := json.NewDecoder(bytes.NewReader(j))
dec.DisallowUnknownFields()
var nk Kustomization
err = dec.Decode(&nk)
if err != nil {
return err
}
*k = nk
return nil
}

View File

@@ -153,7 +153,7 @@ func (mf *kustomizationFile) Read() (*types.Kustomization, error) {
return nil, err
}
var k types.Kustomization
err = yaml.Unmarshal(data, &k)
err = k.Unmarshal(data)
if err != nil {
return nil, err
}

View File

@@ -340,3 +340,21 @@ kind: Kustomization
string(expected), string(bytes))
}
}
func TestUnknownFieldInKustomization(t *testing.T) {
kContent := []byte(`
foo:
bar
`)
fSys := filesys.MakeFsInMemory()
testutils_test.WriteTestKustomizationWith(fSys, kContent)
mf, err := NewKustomizationFile(fSys)
if err != nil {
t.Fatalf("Unexpected Error: %v", err)
}
_, err = mf.Read()
if err == nil || err.Error() != "json: unknown field \"foo\"" {
t.Fatalf("Expect an unknown field error but got: %v", err)
}
}