/
flatten.go
113 lines (99 loc) · 2.63 KB
/
flatten.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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
Copyright 2021 The KodeRover Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package converter
import (
"fmt"
"reflect"
"strings"
"helm.sh/helm/v3/pkg/strvals"
"sigs.k8s.io/yaml"
)
const (
delimiter = "."
// maxDepth = 0
)
func YamlToFlatMap(data []byte) (map[string]interface{}, error) {
nested := make(map[string]interface{})
if len(data) == 0 {
return nested, nil
}
if err := yaml.Unmarshal(data, &nested); err != nil {
return nil, err
}
return Flatten(nested)
}
// Flatten flattens the nested map
// examples:
// {a: {b: c}} => {a.b: c}
// {a: [{b: c}, [b: d]} => {a[0].b: c, a[1].b: d}
// {a: [b, c]} => {a[0]: b, a[1]: c}
func Flatten(nested map[string]interface{}) (map[string]interface{}, error) {
return flatten("", 0, nested)
}
func flatten(prefix string, depth int, nested interface{}) (flat map[string]interface{}, err error) {
flat = make(map[string]interface{})
switch nested := nested.(type) {
case map[string]interface{}:
//if maxDepth != 0 && depth >= maxDepth {
// flat[prefix] = nested
// return
//}
if reflect.DeepEqual(nested, map[string]interface{}{}) {
flat[prefix] = nested
return
}
for k, v := range nested {
newKey := k
if prefix != "" {
newKey = prefix + delimiter + newKey
}
fm1, fe := flatten(newKey, depth+1, v)
if fe != nil {
err = fe
return
}
mergeMap(flat, fm1)
}
case []interface{}:
if reflect.DeepEqual(nested, []interface{}{}) {
flat[prefix] = nested
return
}
for i, v := range nested {
newKey := fmt.Sprintf("%s[%d]", prefix, i)
fm1, fe := flatten(newKey, depth+1, v)
if fe != nil {
err = fe
return
}
mergeMap(flat, fm1)
}
default:
flat[prefix] = nested
}
return
}
func mergeMap(to map[string]interface{}, from map[string]interface{}) {
for kt, vt := range from {
to[kt] = vt
}
}
func Expand(flat map[string]interface{}) (nested map[string]interface{}, err error) {
nested = make(map[string]interface{})
joinedStrSlice := make([]string, 0)
for k, v := range flat {
joinedStrSlice = append(joinedStrSlice, fmt.Sprintf("%s=%v", k, v))
}
err = strvals.ParseInto(strings.Join(joinedStrSlice, ","), nested)
return nested, err
}