-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.go
More file actions
115 lines (109 loc) · 2.25 KB
/
tree.go
File metadata and controls
115 lines (109 loc) · 2.25 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Copyright (c) 2018-2024 KIDTSUNAMI
// Author: alex@kidtsunami.com
//
package config
import (
"strconv"
"strings"
"maps"
"slices"
)
func setTree(walker map[string]any, key string, val any) {
keys := strings.Split(key, ".")
for n := 0; n < len(keys); n++ {
v := keys[n]
if sub, ok := walker[v]; ok {
// recurse into subtree
switch e := sub.(type) {
case map[string]any:
walker = e
case []any:
i, _ := strconv.ParseInt(v, 10, 64)
walker = e[int(i)].(map[string]any)
default:
// append leaf if type is not a container
walker[v] = val
}
} else if n < len(keys)-1 {
// append subtree
sub := make(map[string]any)
walker[v] = sub
walker = sub
} else {
// append leaf
walker[v] = val
}
}
}
func setTreeIfEmpty(walker map[string]any, key string, val any) {
keys := strings.Split(key, ".")
for n := 0; n < len(keys); n++ {
v := keys[n]
if sub, ok := walker[v]; ok {
// recurse into subtree
switch e := sub.(type) {
case map[string]any:
walker = e
case []any:
i, _ := strconv.ParseInt(v, 10, 64)
walker = e[int(i)].(map[string]any)
default:
// append leaf if type is not a container and key segment is last
if n == len(keys)-1 {
if _, ok := walker[v]; !ok {
walker[v] = val
}
}
}
} else if n < len(keys)-1 {
// append subtree
sub := make(map[string]any)
walker[v] = sub
walker = sub
} else {
// append leaf
walker[v] = val
}
}
}
func getTree(walker map[string]any, key string) any {
keys := strings.Split(key, ".")
for n := 0; n < len(keys); n++ {
v := keys[n]
sub, ok := walker[v]
if !ok {
return nil
}
if n == len(keys)-1 {
return sub
}
switch e := sub.(type) {
case map[string]any:
walker = e
case []any:
i, _ := strconv.ParseInt(v, 10, 64)
walker = e[int(i)].(map[string]any)
default:
break
}
}
return nil
}
func walkTree(tree map[string]any, prefix string, fn func(key, val string) error) (err error) {
for _, key := range slices.Sorted(maps.Keys(tree)) {
v := tree[key]
if prefix != "" {
key = prefix + "." + key
}
switch sub := v.(type) {
case map[string]any:
err = walkTree(sub, key, fn)
default:
err = fn(key, toString(v))
}
if err != nil {
break
}
}
return
}