/
utils.go
71 lines (61 loc) · 1.19 KB
/
utils.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
package cmdinternal
import (
"fmt"
"strings"
)
func mapGet[T any](m map[string]any, path ...string) (result T, found bool) {
if len(path) == 0 {
result, found = any(m).(T)
return
}
current := m
last := len(path) - 1
for i, key := range path {
value, ok := current[key]
if !ok {
found = false
return
}
if i == last {
result, found = value.(T)
return
}
current, ok = value.(map[string]any)
if !ok {
found = false
return
}
}
return
}
func mapSet[T any](m map[string]any, value T, path ...string) {
current := m
last := len(path) - 1
for i, key := range path {
if i == last {
current[key] = value
return
}
m, ok := current[key]
if !ok {
m = map[string]any{}
current[key] = m
}
current, ok = m.(map[string]any)
if !ok {
panic(fmt.Sprintf("unexpected value type for for path %q: %T", strings.Join(path, "."), m))
}
}
}
func mapSetIfNotFound[T any](m map[string]any, value T, path ...string) {
_, found := mapGet[T](m, path...)
if !found {
mapSet(m, value, path...)
}
}
func mapDelete(m map[string]any, path ...string) {
m, found := mapGet[map[string]any](m, path[:len(path)-1]...)
if found {
delete(m, path[len(path)-1])
}
}