-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeepmerge.go
183 lines (155 loc) · 5.52 KB
/
deepmerge.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
package deepmerge
import (
"errors"
"fmt"
"reflect"
)
// DeepMerge instantiates initial counters / keys for traversal
type DeepMerge struct {
map1 interface{}
map2 interface{}
// Stores the keys that we have processed as we iterate the maps
seenKeys map[interface{}]bool
// Keeps track of nested parent keys
parentKey reflect.Value
}
// Merge merges 2 maps by applying a fptr (function pointer) to the values
// Example:
// d := &DeepMerge{ map1 : some_map1, map2: some_map2}
// d.Merge(&my_func)
// where my_func := func(a,b int) int { return a + b }
func (d DeepMerge) Merge(fptr interface{}) (interface{}, error) {
if d.map1 == nil && d.map2 != nil {
return d.map2, nil
}
if d.map1 != nil && d.map2 == nil {
return d.map1, nil
}
m1_t := reflect.ValueOf(d.map1).Type()
m2_t := reflect.ValueOf(d.map2).Type()
if m1_t != m2_t {
return nil, errors.New("Maps have to be of the same type")
}
d.seenKeys = make(map[interface{}]bool)
return d.merge(d.map1, d.map2, fptr), nil
}
func (d DeepMerge) merge(m1, m2, fptr interface{}) interface{} {
// Lets keep track of the keys from the maps were iterating
var allKeys []reflect.Value
m1_t := reflect.ValueOf(m1)
m2_t := reflect.ValueOf(m2)
// This will store our final merged map
ret_map := reflect.MakeMap(m1_t.Type())
cp_m1 := reflect.New(m1_t.Type()).Elem()
cp_m2 := reflect.New(m2_t.Type()).Elem()
// Copy over the map values to the placeholder maps
// that will perform the fptr function operations
translateRecursive(cp_m1, m1_t)
translateRecursive(cp_m2, m2_t)
// Lets find out what type of function we have
// so that we can call it
fn := reflect.ValueOf(fptr).Elem()
allKeys = append(allKeys, cp_m1.MapKeys()...)
allKeys = append(allKeys, cp_m2.MapKeys()...)
// For each key we'll run the function block
for _, k := range allKeys {
// If we've already processed the key we'll skip
if _, ok := d.seenKeys[k.Interface()]; ok {
continue
}
// If we're traversing a parent_key, then we'll need to add that key
if (d.parentKey.IsValid()) && (d.parentKey.Len() != 0) {
keyplus := fmt.Sprintf("%v_%v", k.Interface(), d.parentKey.Interface())
d.seenKeys[keyplus] = true
} else {
d.seenKeys[k.Interface()] = true
}
// Get the value of the key from each map
v := cp_m1.MapIndex(k)
o_v := cp_m2.MapIndex(k)
// If we have a map, lets iterative through
// recursively
if v.Kind() == reflect.Map && o_v.Kind() == reflect.Map {
d.parentKey = k
yy := d.merge(v.Interface(), o_v.Interface(), fptr)
ret_map.SetMapIndex(k, reflect.ValueOf(yy))
} else {
// If any of the keys traversed is invalid
// we'll ignore it and update the map to
// the values of the other key
if !v.IsValid() && o_v.IsValid() {
ret_map.SetMapIndex(k, o_v)
continue
}
if !o_v.IsValid() && v.IsValid() {
ret_map.SetMapIndex(k, v)
continue
}
// Everything looks good to call the function pointer
in := []reflect.Value{v, o_v}
zz := fn.Call(in)
// We'll only take the first return value
ret_map.SetMapIndex(k, zz[0])
}
}
return ret_map.Interface()
}
func translateRecursive(copy, original reflect.Value) {
switch original.Kind() {
// The first cases handle nested structures and translate them recursively
// If it is a pointer we need to unwrap and call once again
case reflect.Ptr:
// To get the actual value of the original we have to call Elem()
// At the same time this unwraps the pointer so we don't end up in
// an infinite recursion
originalValue := original.Elem()
// Check if the pointer is nil
if !originalValue.IsValid() {
return
}
// Allocate a new object and set the pointer to it
copy.Set(reflect.New(originalValue.Type()))
// Unwrap the newly created pointer
translateRecursive(copy.Elem(), originalValue)
// If it is an interface (which is very similar to a pointer), do basically the
// same as for the pointer. Though a pointer is not the same as an interface so
// note that we have to call Elem() after creating a new object because otherwise
// we would end up with an actual pointer
case reflect.Interface:
// Get rid of the wrapping interface
originalValue := original.Elem()
// Create a new object. Now new gives us a pointer, but we want the value it
// points to, so we have to call Elem() to unwrap it
copyValue := reflect.New(originalValue.Type()).Elem()
translateRecursive(copyValue, originalValue)
copy.Set(copyValue)
// If it is a struct we translate each field
case reflect.Struct:
for i := 0; i < original.NumField(); i += 1 {
if copy.Field(i).CanSet() {
translateRecursive(copy.Field(i), original.Field(i))
} else {
fmt.Printf("WARNING: Cannot Set unexported fields. Type:%T ,Value:%v will be set to it's zero value.\n", original.Type().Field(i).Name, original.Field(i))
}
}
// If it is a slice we create a new slice and translate each element
case reflect.Slice:
copy.Set(reflect.MakeSlice(original.Type(), original.Len(), original.Cap()))
for i := 0; i < original.Len(); i += 1 {
translateRecursive(copy.Index(i), original.Index(i))
}
// If it is a map we create a new map and translate each value
case reflect.Map:
copy.Set(reflect.MakeMap(original.Type()))
for _, key := range original.MapKeys() {
originalValue := original.MapIndex(key)
// New gives us a pointer, but again we want the value
copyValue := reflect.New(originalValue.Type()).Elem()
translateRecursive(copyValue, originalValue)
copy.SetMapIndex(key, copyValue)
}
// And everything else will simply be taken from the original
default:
copy.Set(original)
}
}