Skip to content

Commit a7ec263

Browse files
authored
Proper unmarshaller for k8s configuration (#121)
Signed-off-by: Jose Fuentes <[email protected]>
1 parent 41da210 commit a7ec263

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

pkg/datagatherer/k8s/generic.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,29 @@ type Config struct {
1919
GroupVersionResource schema.GroupVersionResource
2020
}
2121

22+
// UnmarshalYAML unmarshals the Config resolving GroupVersionResource.
23+
func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {
24+
aux := struct {
25+
KubeConfigPath string `yaml:"kubeconfig"`
26+
ResourceType struct {
27+
Group string `yaml:"group"`
28+
Version string `yaml:"version"`
29+
Resource string `yaml:"resource"`
30+
} `yaml:"resource-type"`
31+
}{}
32+
err := unmarshal(&aux)
33+
if err != nil {
34+
return err
35+
}
36+
37+
c.KubeConfigPath = aux.KubeConfigPath
38+
c.GroupVersionResource.Group = aux.ResourceType.Group
39+
c.GroupVersionResource.Version = aux.ResourceType.Version
40+
c.GroupVersionResource.Resource = aux.ResourceType.Resource
41+
42+
return nil
43+
}
44+
2245
// validate validates the configuration.
2346
func (c *Config) validate() error {
2447
if c.GroupVersionResource.Resource == "" {

pkg/datagatherer/k8s/generic_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"reflect"
55
"testing"
66

7+
"gopkg.in/yaml.v2"
78
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
89
"k8s.io/apimachinery/pkg/runtime"
910
"k8s.io/apimachinery/pkg/runtime/schema"
@@ -108,3 +109,34 @@ func TestGenericGatherer_Fetch(t *testing.T) {
108109
})
109110
}
110111
}
112+
113+
func TestUnmarshalConfig(t *testing.T) {
114+
textCfg := `
115+
kubeconfig: "/home/someone/.kube/config"
116+
resource-type:
117+
group: "g"
118+
version: "v"
119+
resource: "r"
120+
`
121+
122+
expectedGVR := schema.GroupVersionResource{
123+
Group: "g",
124+
Version: "v",
125+
Resource: "r",
126+
}
127+
128+
cfg := Config{}
129+
err := yaml.Unmarshal([]byte(textCfg), &cfg)
130+
if err != nil {
131+
t.Fatalf("unexpected error: %+v", err)
132+
}
133+
134+
if got, want := cfg.KubeConfigPath, "/home/someone/.kube/config"; got != want {
135+
t.Errorf("KubeConfigPath does not match: got=%q; want=%q", got, want)
136+
}
137+
138+
if got, want := cfg.GroupVersionResource, expectedGVR; !reflect.DeepEqual(got, want) {
139+
t.Errorf("GroupVersionResource does not match: got=%+v want=%+v", got, want)
140+
}
141+
142+
}

0 commit comments

Comments
 (0)