Repository navigation
Expand file tree
/
Copy pathmetadata.go
More file actions
96 lines (81 loc) · 2.19 KB
/
Copy pathmetadata.go
File metadata and controls
96 lines (81 loc) · 2.19 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package pluginsdk
import (
"reflect"
"strings"
)
// SensitiveMask replaces sensitive values in metadata and config specs.
const SensitiveMask = "********"
// MapToMetadata converts a struct with metadata tags to a metadata map.
// Fields are included when they carry a `metadata:"<key>"` tag and hold
// a non-zero value; fields tagged `sensitive` are masked. Nested structs
// and slices of structs flatten under dotted keys.
func MapToMetadata(source interface{}) map[string]interface{} {
metadata := make(map[string]interface{})
t := reflect.TypeOf(source)
v := reflect.ValueOf(source)
if t.Kind() == reflect.Ptr {
t = t.Elem()
v = v.Elem()
}
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
metadataTag := field.Tag.Get("metadata")
if metadataTag == "" {
continue
}
value := v.Field(i).Interface()
if isNilValue(value) {
continue
}
_, sensitive := field.Tag.Lookup("sensitive")
if sensitive {
value = SensitiveMask
}
switch {
case field.Type.Kind() == reflect.Struct && !sensitive:
nestedMetadata := MapToMetadata(value)
for k, v := range nestedMetadata {
setNestedValue(metadata, metadataTag+"."+k, v)
}
case field.Type.Kind() == reflect.Slice && field.Type.Elem().Kind() == reflect.Struct && !sensitive:
sliceValue := v.Field(i)
for j := 0; j < sliceValue.Len(); j++ {
nestedMetadata := MapToMetadata(sliceValue.Index(j).Interface())
for k, v := range nestedMetadata {
setNestedValue(metadata, metadataTag+"."+k, v)
}
}
default:
setNestedValue(metadata, metadataTag, value)
}
}
return metadata
}
func isNilValue(v interface{}) bool {
switch v := v.(type) {
case string:
return v == ""
case int:
return v == 0
case bool:
return !v
case []string:
return len(v) == 0
case nil:
return true
default:
return false
}
}
func setNestedValue(metadata map[string]interface{}, path string, value interface{}) {
parts := strings.Split(path, ".")
current := metadata
for i := 0; i < len(parts)-1; i++ {
part := parts[i]
if _, exists := current[part]; !exists {
current[part] = make(map[string]interface{})
}
current = current[part].(map[string]interface{})
}
current[parts[len(parts)-1]] = value
}