Skip to content

Commit

Permalink
Proper unmarshaller for k8s configuration (#121)
Browse files Browse the repository at this point in the history
Signed-off-by: Jose Fuentes <[email protected]>
  • Loading branch information
j-fuentes authored Feb 24, 2020
1 parent 41da210 commit a7ec263
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
23 changes: 23 additions & 0 deletions pkg/datagatherer/k8s/generic.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,29 @@ type Config struct {
GroupVersionResource schema.GroupVersionResource
}

// UnmarshalYAML unmarshals the Config resolving GroupVersionResource.
func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {
aux := struct {
KubeConfigPath string `yaml:"kubeconfig"`
ResourceType struct {
Group string `yaml:"group"`
Version string `yaml:"version"`
Resource string `yaml:"resource"`
} `yaml:"resource-type"`
}{}
err := unmarshal(&aux)
if err != nil {
return err
}

c.KubeConfigPath = aux.KubeConfigPath
c.GroupVersionResource.Group = aux.ResourceType.Group
c.GroupVersionResource.Version = aux.ResourceType.Version
c.GroupVersionResource.Resource = aux.ResourceType.Resource

return nil
}

// validate validates the configuration.
func (c *Config) validate() error {
if c.GroupVersionResource.Resource == "" {
Expand Down
32 changes: 32 additions & 0 deletions pkg/datagatherer/k8s/generic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"reflect"
"testing"

"gopkg.in/yaml.v2"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
Expand Down Expand Up @@ -108,3 +109,34 @@ func TestGenericGatherer_Fetch(t *testing.T) {
})
}
}

func TestUnmarshalConfig(t *testing.T) {
textCfg := `
kubeconfig: "/home/someone/.kube/config"
resource-type:
group: "g"
version: "v"
resource: "r"
`

expectedGVR := schema.GroupVersionResource{
Group: "g",
Version: "v",
Resource: "r",
}

cfg := Config{}
err := yaml.Unmarshal([]byte(textCfg), &cfg)
if err != nil {
t.Fatalf("unexpected error: %+v", err)
}

if got, want := cfg.KubeConfigPath, "/home/someone/.kube/config"; got != want {
t.Errorf("KubeConfigPath does not match: got=%q; want=%q", got, want)
}

if got, want := cfg.GroupVersionResource, expectedGVR; !reflect.DeepEqual(got, want) {
t.Errorf("GroupVersionResource does not match: got=%+v want=%+v", got, want)
}

}

0 comments on commit a7ec263

Please sign in to comment.