-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsetter.go
104 lines (95 loc) · 1.74 KB
/
setter.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
package gojo
import "github.com/iancoleman/orderedmap"
type setter interface {
set([]string, any) error
}
type arraySetter struct {
value any
}
func (s *arraySetter) set(keys []string, v any) error {
arr, ok := v.(*[]any)
if !ok {
return errArray{keys, v}
}
if st, ok := s.value.(setter); ok {
if ast, ok := st.(*arraySetter); ok {
ar := []any{}
if err := ast.set(keys, &ar); err != nil {
return err
}
*arr = append(*arr, ar)
} else {
om := orderedmap.New()
if err := st.set(keys, om); err != nil {
return err
}
*arr = append(*arr, om)
}
} else {
*arr = append(*arr, s.value)
}
return nil
}
type objectSetter struct {
key string
value any
}
func (s *objectSetter) set(keys []string, v any) error {
if !isMap(v) {
return errObject{keys, v}
}
if st, ok := s.value.(setter); ok {
val, ok := getKey(v, s.key)
switch v := val.(type) {
case orderedmap.OrderedMap:
val = &v
case []any:
val = &v
}
if !ok {
if _, ok := st.(*arraySetter); ok {
val = &[]any{}
} else {
val = orderedmap.New()
}
}
if err := st.set(append(keys, s.key), val); err != nil {
return err
}
setKey(v, s.key, val)
} else {
setKey(v, s.key, s.value)
}
return nil
}
func isMap(t any) bool {
switch t.(type) {
case *orderedmap.OrderedMap:
return true
case map[string]any:
return true
default:
return false
}
}
func getKey(t any, key string) (any, bool) {
switch t := t.(type) {
case *orderedmap.OrderedMap:
return t.Get(key)
case map[string]any:
v, ok := t[key]
return v, ok
default:
panic(t)
}
}
func setKey(t any, key string, value any) {
switch t := t.(type) {
case *orderedmap.OrderedMap:
t.Set(key, value)
case map[string]any:
t[key] = value
default:
panic(t)
}
}