-
Notifications
You must be signed in to change notification settings - Fork 0
/
flatten.go
54 lines (50 loc) · 956 Bytes
/
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
package yamltools
import (
"gopkg.in/yaml.v3"
)
// EnsureFlatList will flatten nested lists of yaml nodes
// expects to be passed a yaml.SequenceNode
func EnsureFlatList(n *yaml.Node) *yaml.Node {
if n.Kind == yaml.SequenceNode {
length := getFlatLength(n)
if length < 0 {
return n
}
dst := make([]*yaml.Node, 0, length)
flattenSlice(n, &dst)
n.Content = dst
}
return n
}
func getFlatLength(n *yaml.Node) int {
count := 0
isNested := false
for _, v := range n.Content {
if v.Kind == yaml.AliasNode {
v = v.Alias
}
if v.Kind == yaml.SequenceNode {
isNested = true
count += getFlatLength(v)
} else {
count++
}
}
if isNested {
return count
} else {
return -1
}
}
func flattenSlice(n *yaml.Node, dst *[]*yaml.Node) {
for _, v := range n.Content {
if v.Kind == yaml.AliasNode {
v = v.Alias
}
if v.Kind == yaml.SequenceNode {
flattenSlice(v, dst)
} else {
*dst = append(*dst, v)
}
}
}