-
Notifications
You must be signed in to change notification settings - Fork 4
/
unstructured_util.go
52 lines (44 loc) · 1.64 KB
/
unstructured_util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package kubernetes
import (
"fmt"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
// this file contains utility functions for working with Unstructured types
// GetLabel returns the label identified by "key"
func GetLabel(un *unstructured.Unstructured, key string) (string, error) {
labels, err := nestedNullableStringMap(un.Object, "metadata", "labels")
if err != nil {
return "", fmt.Errorf("failed to get labels from target object %s %s/%s: %w", un.GroupVersionKind().String(), un.GetNamespace(), un.GetName(), err)
}
if labels != nil {
return labels[key], nil
}
return "", nil
}
// SetLabel sets the label identified by "key" on an unstructured object
func SetLabel(target *unstructured.Unstructured, key, val string) error {
labels, err := nestedNullableStringMap(target.Object, "metadata", "labels")
if err != nil {
return fmt.Errorf("failed to get labels from target object %s %s/%s: %w", target.GroupVersionKind().String(), target.GetNamespace(), target.GetName(), err)
}
if labels == nil {
labels = make(map[string]string)
}
labels[key] = val
target.SetLabels(labels)
return nil
}
// nestedNullableStringMap returns a copy of map[string]string value of a nested field.
// Returns an error if not one of map[string]interface{} or nil, or contains non-string values in the map.
func nestedNullableStringMap(obj map[string]interface{}, fields ...string) (map[string]string, error) {
var m map[string]string
val, found, err := unstructured.NestedFieldNoCopy(obj, fields...)
if err != nil {
return nil, err
}
if found && val != nil {
val, _, err := unstructured.NestedStringMap(obj, fields...)
return val, err
}
return m, err
}