forked from geofffranks/spruce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge.go
277 lines (233 loc) · 6.98 KB
/
merge.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package main
import (
"fmt"
"reflect"
"regexp"
"sort"
"strings"
)
type ErrorList struct {
errs []error
}
func (el ErrorList) Error() string {
str := make([]string, len(el.errs))
for i, s := range el.errs {
str[i] = fmt.Sprintf(" - %s\n", s)
}
sort.Strings(str)
return fmt.Sprintf("%d error(s) detected:\n%s\n", len(el.errs), strings.Join(str, ""))
}
func (el *ErrorList) Count() int {
return len(el.errs)
}
func (el *ErrorList) Push(e error) {
if e != nil {
el.errs = append(el.errs, e)
}
}
type Merger struct {
Errors ErrorList
depth int
}
func (m *Merger) Error() error {
if m.Errors.Count() > 0 {
return m.Errors
}
return nil
}
func (m *Merger) Merge(a map[interface{}]interface{}, b map[interface{}]interface{}) error {
m.mergeMap(a, b, "$")
return m.Error()
}
func (m *Merger) mergeMap(orig map[interface{}]interface{}, n map[interface{}]interface{}, node string) {
for k, val := range n {
path := fmt.Sprintf("%s.%v", node, k)
if _, exists := orig[k]; exists {
orig[k] = m.mergeObj(orig[k], val, path)
} else {
DEBUG("%s: not found upstream, adding it", path)
orig[k] = val
}
}
}
func (m *Merger) mergeObj(orig interface{}, n interface{}, node string) interface{} {
switch t := n.(type) {
case map[interface{}]interface{}:
switch orig.(type) {
case map[interface{}]interface{}:
DEBUG("%s: performing map merge", node)
m.mergeMap(orig.(map[interface{}]interface{}), n.(map[interface{}]interface{}), node)
return orig
default:
DEBUG("%s: replacing with new data (original was not a map)", node)
return t
}
case []interface{}:
switch orig.(type) {
case []interface{}:
DEBUG("%s: performing array merge", node)
return m.mergeArray(orig.([]interface{}), n.([]interface{}), node)
default:
if orig == nil {
DEBUG("%s: performing array merge (original was nil)", node)
return m.mergeArray([]interface{}{}, n.([]interface{}), node)
} else {
DEBUG("%s: replacing with new data (original was not an array)", node)
return t
}
}
default:
DEBUG("%s: replacing with new data (new data is neither map nor array)", node)
return t
}
}
func (m *Merger) mergeArray(orig []interface{}, n []interface{}, node string) []interface{} {
if shouldAppendToArray(n) {
DEBUG("%s: appending %d new elements to existing array, starting at index %d", node, len(n)-1, len(orig))
return append(orig, n[1:]...)
} else if shouldPrependToArray(n) {
DEBUG("%s: prepending %d new elements to existing array", node, len(n)-1)
return append(n[1:], orig...)
} else if shouldInlineMergeArray(n) {
DEBUG("%s: performing explicit inline array merge", node)
return m.mergeArrayInline(orig, n[1:], node)
} else if shouldReplaceArray(n) {
DEBUG("%s: replacing with new data", node)
return n[1:]
} else if should, key := shouldKeyMergeArray(n); should {
DEBUG("%s: performing key-based array merge, using key '%s'", node, key)
if err := canKeyMergeArray("new", n[1:], node, key); err != nil {
m.Errors.Push(err)
return nil
}
if err := canKeyMergeArray("original", orig, node, key); err != nil {
m.Errors.Push(err)
return nil
}
return m.mergeArrayByKey(orig, n[1:], node, key)
} else {
DEBUG("%s: performing index-based array merge", node)
if err := canKeyMergeArray("original", orig, node, "name"); err == nil {
if err := canKeyMergeArray("new", n, node, "name"); err == nil {
return m.mergeArrayByKey(orig, n, node, "name")
}
}
return m.mergeArrayInline(orig, n, node)
}
}
func (m *Merger) mergeArrayInline(orig []interface{}, n []interface{}, node string) []interface{} {
length := len(orig)
if len(n) > len(orig) {
length = len(n)
}
merged := make([]interface{}, length, length)
var last int
for i := range orig {
if i >= len(n) {
merged[i] = orig[i]
} else {
merged[i] = m.mergeObj(orig[i], n[i], fmt.Sprintf("%s.%d", node, i))
}
last = i
}
if len(orig) > 0 {
last++ // move to next index after finishing the orig slice - but only if we looped
}
// grab the remainder of n (if any) and append the to the result
for i := last; i < len(n); i++ {
DEBUG("%s.%d: appending new data to existing array", node, i)
merged[i] = m.mergeObj(nil, n[i], fmt.Sprintf("%s.%d", node, i))
}
return merged
}
func (m *Merger) mergeArrayByKey(orig []interface{}, n []interface{}, node string, key string) []interface{} {
merged := make([]interface{}, len(orig), len(orig))
newMap := make(map[interface{}]interface{})
for _, o := range n {
obj := o.(map[interface{}]interface{})
newMap[obj[key]] = obj
}
for i, o := range orig {
obj := o.(map[interface{}]interface{})
if _, ok := newMap[obj[key]]; ok {
merged[i] = m.mergeObj(obj, newMap[obj[key]], fmt.Sprintf("%s.%d", node, i))
delete(newMap, obj[key])
} else {
merged[i] = obj
}
}
i := 0
for _, obj := range n {
obj := obj.(map[interface{}]interface{})
if _, ok := newMap[obj[key]]; ok {
DEBUG("%s.%d: appending new data to merged array", node, i)
merged = append(merged, obj)
i++
}
}
return merged
}
func shouldInlineMergeArray(obj []interface{}) bool {
if len(obj) >= 1 && reflect.TypeOf(obj[0]).Kind() == reflect.String {
re := regexp.MustCompile("^\\Q((\\E\\s*inline\\s*\\Q))\\E$")
if re.MatchString(obj[0].(string)) {
return true
}
}
return false
}
func shouldAppendToArray(obj []interface{}) bool {
if len(obj) >= 1 && reflect.TypeOf(obj[0]).Kind() == reflect.String {
re := regexp.MustCompile("^\\Q((\\E\\s*append\\s*\\Q))\\E$")
if re.MatchString(obj[0].(string)) {
return true
}
}
return false
}
func shouldPrependToArray(obj []interface{}) bool {
if len(obj) >= 1 && reflect.TypeOf(obj[0]).Kind() == reflect.String {
re := regexp.MustCompile("^\\Q((\\E\\s*prepend\\s*\\Q))\\E$")
if re.MatchString(obj[0].(string)) {
return true
}
}
return false
}
func shouldKeyMergeArray(obj []interface{}) (bool, string) {
key := "name"
if len(obj) >= 1 && reflect.TypeOf(obj[0]).Kind() == reflect.String {
re := regexp.MustCompile("^\\Q((\\E\\s*merge(?:\\s+on\\s+(.*?))?\\s*\\Q))\\E$")
if re.MatchString(obj[0].(string)) {
keys := re.FindStringSubmatch(obj[0].(string))
if keys[1] != "" {
key = keys[1]
}
return true, key
}
}
return false, ""
}
func canKeyMergeArray(disp string, array []interface{}, node string, key string) error {
// ensure that all elements of `array` are maps,
// and that they contain the key `key`
for i, o := range array {
if reflect.TypeOf(o).Kind() != reflect.Map {
return fmt.Errorf("%s.%d: %s object is a %s, not a map - cannot merge using keys", node, i, disp, reflect.TypeOf(o).Kind().String())
}
obj := o.(map[interface{}]interface{})
if _, ok := obj[key]; !ok {
return fmt.Errorf("%s.%d: %s object does not contain the key '%s' - cannot merge", node, i, disp, key)
}
}
return nil
}
func shouldReplaceArray(obj []interface{}) bool {
if len(obj) >= 1 && reflect.TypeOf(obj[0]).Kind() == reflect.String {
re := regexp.MustCompile(`^\Q((\E\s*replace\s*\Q))\E$`)
if re.MatchString(obj[0].(string)) {
return true
}
}
return false
}