-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathyaml.go
70 lines (66 loc) · 1.63 KB
/
yaml.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package toolbox
import (
"bytes"
"fmt"
"gopkg.in/yaml.v2"
)
//AsYamlText converts data structure int text YAML
func AsYamlText(source interface{}) (string, error) {
if IsStruct(source) || IsMap(source) || IsSlice(source) {
buf := new(bytes.Buffer)
err := yaml.NewEncoder(buf).Encode(source)
return buf.String(), err
}
return "", fmt.Errorf("unsupported type: %T", source)
}
//NormalizeKVPairs converts slice of KV paris into a map, and map[interface{}]interface{} to map[string]interface{}
func NormalizeKVPairs(source interface{}) (interface{}, error) {
if source == nil {
return source, nil
}
isDataStruct := IsMap(source) || IsStruct(source) || IsSlice(source)
var err error
var normalized interface{}
if isDataStruct {
var aMap = make(map[string]interface{})
err = ProcessMap(source, func(k, value interface{}) bool {
var key = AsString(k)
aMap[key] = value
if value == nil {
return true
}
if IsMap(value) || IsSlice(value) || IsStruct(value) {
if normalized, err = NormalizeKVPairs(value); err == nil {
aMap[key] = normalized
}
}
return true
})
if err == nil {
return aMap, nil
}
if IsSlice(aMap) {
return source, err
}
if IsSlice(source) { //yaml style map conversion if applicable
aSlice := AsSlice(source)
if len(aSlice) == 0 {
return source, nil
}
for i, item := range aSlice {
if item == nil {
continue
}
if IsMap(item) || IsSlice(item) {
if normalized, err = NormalizeKVPairs(item); err == nil {
aSlice[i] = normalized
} else {
return source, nil
}
}
}
return aSlice, nil
}
}
return source, err
}