avoid double unmarshalling

This commit is contained in:
Yann Hamon 2020-12-15 18:35:33 +01:00
parent 4afe9b1977
commit 29a8f4c09e
7 changed files with 72 additions and 17 deletions

View file

@ -111,8 +111,8 @@ func FromFiles(ctx context.Context, ignoreFilePatterns []string, paths ...string
}
}
close(resources)
close(errors)
close(resources)
}()
return resources, errors

View file

@ -42,3 +42,26 @@ func (res *Resource) Signature() (*Signature, error) {
res.sig = &Signature{Kind: resource.Kind, Version: resource.APIVersion, Namespace: resource.Metadata.Namespace, Name: name}
return res.sig, err
}
func (res *Resource) SignatureFromMap(m map[string]interface{}) (*Signature, error) {
if res.sig != nil {
return res.sig, nil
}
APIVersion, _ := m["apiVersion"].(string)
Kind, _ := m["kind"].(string)
var name, ns string
Metadata, ok := m["metadata"].(map[string]interface{})
if ok {
name, _ = Metadata["name"].(string)
ns, _ = Metadata["namespace"].(string)
if _, ok := Metadata["generateName"].(string); ok {
name = Metadata["generateName"].(string) + "{{ generateName }}"
}
}
// We cache the result to not unmarshall every time we want to access the signature
res.sig = &Signature{Kind: Kind, Version: APIVersion, Namespace: ns, Name: name}
return res.sig, nil
}

View file

@ -1,9 +1,12 @@
package resource_test
import (
"fmt"
"log"
"testing"
"github.com/yannh/kubeconform/pkg/resource"
"sigs.k8s.io/yaml"
)
func TestSignatureFromBytes(t *testing.T) {
@ -47,3 +50,29 @@ spec:
}
}
}
func TestSignatureFromMap(t *testing.T) {
testCases := []struct {
b string
}{
{
"apiVersion: v1\nkind: ReplicationController\nmetadata:\n name: \"bob\"\nspec:\n replicas: 2\n",
},
}
for _, testCase := range testCases {
res := resource.Resource{
Path: "foo",
Bytes: []byte(testCase.b),
}
var r map[string]interface{}
if err := yaml.Unmarshal(res.Bytes, &r); err != nil {
log.Fatal(err)
}
res.SignatureFromMap(r)
sig, _ := res.Signature()
fmt.Printf("%+v", sig)
}
}