Debian Codegraph @

maps/maps.go

raw
1 // Package maps provides reusable functions for manipulating nested
2 // map[string]any maps are common unmarshal products from
3 // various serializers such as json, yaml etc.
4 package maps
5
6 import (
7 "fmt"
8 "reflect"
9 "strings"
10
11 "github.com/mitchellh/copystructure"
12 )
13
14 // Flatten takes a map[string]any and traverses it and flattens
15 // nested children into keys delimited by delim.
16 //
17 // It's important to note that all nested maps should be
18 // map[string]any and not map[any]any.
19 // Use IntfaceKeysToStrings() to convert if necessary.
20 //
21 // eg: `{ "parent": { "child": 123 }}` becomes `{ "parent.child": 123 }`
22 // In addition, it keeps track of and returns a map of the delimited keypaths with
23 // a slice of key parts, for eg: { "parent.child": ["parent", "child"] }. This
24 // parts list is used to remember the key path's original structure to
25 // unflatten later.
26 func Flatten(m map[string]any, keys []string, delim string) (map[string]any, map[string][]string) {
27 var (
28 out = make(map[string]any)
29 keyMap = make(map[string][]string)
30 )
31
32 flatten(m, keys, delim, out, keyMap)
33 return out, keyMap
34 }
35
36 func flatten(m map[string]any, keys []string, delim string, out map[string]any, keyMap map[string][]string) {
37 for key, val := range m {
38 // Copy the incoming key paths into a fresh list
39 // and append the current key in the iteration.
40 kp := make([]string, 0, len(keys)+1)
41 kp = append(kp, keys...)
42 kp = append(kp, key)
43
44 switch cur := val.(type) {
45 case map[string]any:
46 // Empty map.
47 if len(cur) == 0 {
48 newKey := strings.Join(kp, delim)
49 out[newKey] = val
50 keyMap[newKey] = kp
51 continue
52 }
53
54 // It's a nested map. Flatten it recursively.
55 flatten(cur, kp, delim, out, keyMap)
56 default:
57 newKey := strings.Join(kp, delim)
58 out[newKey] = val
59 keyMap[newKey] = kp
60 }
61 }
62 }
63
64 // Unflatten takes a flattened key:value map (non-nested with delimited keys)
65 // and returns a nested map where the keys are split into hierarchies by the given
66 // delimiter. For instance, `parent.child.key: 1` to `{parent: {child: {key: 1}}}`
67 //
68 // It's important to note that all nested maps should be
69 // map[string]any and not map[any]any.
70 // Use IntfaceKeysToStrings() to convert if necessary.
71 func Unflatten(m map[string]any, delim string) map[string]any {
72 out := make(map[string]any)
73
74 // Iterate through the flat conf map.
75 for k, v := range m {
76 var (
77 keys []string
78 next = out
79 )
80
81 if delim != "" {
82 keys = strings.Split(k, delim)
83 } else {
84 keys = []string{k}
85 }
86
87 // Iterate through key parts, for eg:, parent.child.key
88 // will be ["parent", "child", "key"]
89 for _, k := range keys[:len(keys)-1] {
90 sub, ok := next[k]
91 if !ok {
92 // If the key does not exist in the map, create it.
93 sub = make(map[string]any)
94 next[k] = sub
95 }
96 if n, ok := sub.(map[string]any); ok {
97 next = n
98 }
99 }
100
101 // Assign the value.
102 next[keys[len(keys)-1]] = v
103 }
104 return out
105 }
106
107 // Merge recursively merges map a into b (left to right), mutating
108 // and expanding map b. Note that there's no copying involved, so
109 // map b will retain references to map a.
110 //
111 // It's important to note that all nested maps should be
112 // map[string]any and not map[any]any.
113 // Use IntfaceKeysToStrings() to convert if necessary.
114 func Merge(a, b map[string]any) {
115 for key, val := range a {
116 // Does the key exist in the target map?
117 // If no, add it and move on.
118 bVal, ok := b[key]
119 if !ok {
120 b[key] = val
121 continue
122 }
123
124 // If the incoming val is not a map, do a direct merge.
125 if _, ok := val.(map[string]any); !ok {
126 b[key] = val
127 continue
128 }
129
130 // The source key and target keys are both maps. Merge them.
131 switch v := bVal.(type) {
132 case map[string]any:
133 Merge(val.(map[string]any), v)
134 default:
135 b[key] = val
136 }
137 }
138 }
139
140 // MergeStrict recursively merges map a into b (left to right), mutating
141 // and expanding map b. Note that there's no copying involved, so
142 // map b will retain references to map a.
143 // If an equal key in either of the maps has a different value type, it will return the first error.
144 //
145 // It's important to note that all nested maps should be
146 // map[string]any and not map[any]any.
147 // Use IntfaceKeysToStrings() to convert if necessary.
148 func MergeStrict(a, b map[string]any) error {
149 return mergeStrict(a, b, "")
150 }
151
152 func mergeStrict(a, b map[string]any, fullKey string) error {
153 for key, val := range a {
154 // Does the key exist in the target map?
155 // If no, add it and move on.
156 bVal, ok := b[key]
157 if !ok {
158 b[key] = val
159 continue
160 }
161
162 newFullKey := key
163 if fullKey != "" {
164 newFullKey = fmt.Sprintf("%v.%v", fullKey, key)
165 }
166
167 // If the incoming val is not a map, do a direct merge between the same types.
168 if _, ok := val.(map[string]any); !ok {
169 if reflect.TypeOf(b[key]) == reflect.TypeOf(val) {
170 b[key] = val
171 } else {
172 return fmt.Errorf("incorrect types at key %v, type %T != %T", fullKey, b[key], val)
173 }
174 continue
175 }
176
177 // The source key and target keys are both maps. Merge them.
178 switch v := bVal.(type) {
179 case map[string]any:
180 if err := mergeStrict(val.(map[string]any), v, newFullKey); err != nil {
181 return err
182 }
183 default:
184 b[key] = val
185 }
186 }
187 return nil
188 }
189
190 // Delete removes the entry present at a given path, from the map. The path
191 // is the key map slice, for eg:, parent.child.key -> [parent child key].
192 // Any empty, nested map on the path, is recursively deleted.
193 //
194 // It's important to note that all nested maps should be
195 // map[string]any and not map[any]any.
196 // Use IntfaceKeysToStrings() to convert if necessary.
197 func Delete(mp map[string]any, path []string) {
198 next, ok := mp[path[0]]
199 if ok {
200 if len(path) == 1 {
201 delete(mp, path[0])
202 return
203 }
204 switch nval := next.(type) {
205 case map[string]any:
206 Delete(nval, path[1:])
207 // Delete map if it has no keys.
208 if len(nval) == 0 {
209 delete(mp, path[0])
210 }
211 }
212 }
213 }
214
215 // Search recursively searches a map for a given path. The path is
216 // the key map slice, for eg:, parent.child.key -> [parent child key].
217 //
218 // It's important to note that all nested maps should be
219 // map[string]any and not map[any]any.
220 // Use IntfaceKeysToStrings() to convert if necessary.
221 func Search(mp map[string]any, path []string) any {
222 next, ok := mp[path[0]]
223 if ok {
224 if len(path) == 1 {
225 return next
226 }
227 switch m := next.(type) {
228 case map[string]any:
229 return Search(m, path[1:])
230 default:
231 return nil
232 } //
233 // It's important to note that all nested maps should be
234 // map[string]any and not map[any]any.
235 // Use IntfaceKeysToStrings() to convert if necessary.
236 }
237 return nil
238 }
239
240 // Copy returns a deep copy of a conf map.
241 //
242 // It's important to note that all nested maps should be
243 // map[string]any and not map[any]any.
244 // Use IntfaceKeysToStrings() to convert if necessary.
245 func Copy(mp map[string]any) map[string]any {
246 out, _ := copystructure.Copy(&mp)
247 if res, ok := out.(*map[string]any); ok {
248 return *res
249 }
250 return map[string]any{}
251 }
252
253 // IntfaceKeysToStrings recursively converts map[any]any to
254 // map[string]any. Some parses such as YAML unmarshal return this.
255 func IntfaceKeysToStrings(mp map[string]any) {
256 for key, val := range mp {
257 switch cur := val.(type) {
258 case map[any]any:
259 x := make(map[string]any)
260 for k, v := range cur {
261 x[fmt.Sprintf("%v", k)] = v
262 }
263 mp[key] = x
264 IntfaceKeysToStrings(x)
265 case []any:
266 for i, v := range cur {
267 switch sub := v.(type) {
268 case map[any]any:
269 x := make(map[string]any)
270 for k, v := range sub {
271 x[fmt.Sprintf("%v", k)] = v
272 }
273 cur[i] = x
274 IntfaceKeysToStrings(x)
275 case map[string]any:
276 IntfaceKeysToStrings(sub)
277 }
278 }
279 case map[string]any:
280 IntfaceKeysToStrings(cur)
281 }
282 }
283 }
284
285 // StringSliceToLookupMap takes a slice of strings and returns a lookup map
286 // with the slice values as keys with true values.
287 func StringSliceToLookupMap(s []string) map[string]bool {
288 return sliceToLookupMap(s)
289 }
290
291 // Int64SliceToLookupMap takes a slice of int64s and returns a lookup map
292 // with the slice values as keys with true values.
293 func Int64SliceToLookupMap(s []int64) map[int64]bool {
294 return sliceToLookupMap(s)
295 }
296
297 func sliceToLookupMap[T string | int64](s []T) map[T]bool {
298 mp := make(map[T]bool, len(s))
299 for _, v := range s {
300 mp[v] = true
301 }
302 return mp
303 }