-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmerge.go
97 lines (84 loc) · 1.76 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
package misp
import (
"fmt"
"reflect"
)
func Merge(dest interface{}, src interface{}) error {
vSrc := reflect.ValueOf(src)
vDst := reflect.ValueOf(dest)
if vDst.Kind() == reflect.Ptr {
vDst = vDst.Elem()
}
return merge(vDst, vSrc)
}
func merge(dest reflect.Value, src reflect.Value) error {
switch src.Kind() {
case reflect.Func:
if !dest.CanSet() {
return nil
}
src = src.Call([]reflect.Value{})[0]
if src.Kind() == reflect.Ptr {
src = src.Elem()
}
if err := merge(dest, src); err != nil {
return err
}
case reflect.Struct:
// try to set the struct
if src.Type() == dest.Type() {
if !dest.CanSet() {
return nil
}
dest.Set(src)
return nil
}
for i := 0; i < src.NumMethod(); i++ {
tMethod := src.Type().Method(i)
df := dest.FieldByName(tMethod.Name)
if df.Kind() == 0 {
continue
}
if err := merge(df, src.Method(i)); err != nil {
return err
}
}
for i := 0; i < src.NumField(); i++ {
tField := src.Type().Field(i)
df := dest.FieldByName(tField.Name)
if df.Kind() == 0 {
continue
}
if err := merge(df, src.Field(i)); err != nil {
return err
}
}
case reflect.Map:
x := reflect.MakeMap(dest.Type())
for _, k := range src.MapKeys() {
x.SetMapIndex(k, src.MapIndex(k))
}
dest.Set(x)
case reflect.Slice:
x := reflect.MakeSlice(dest.Type(), src.Len(), src.Len())
for j := 0; j < src.Len(); j++ {
merge(x.Index(j), src.Index(j))
}
dest.Set(x)
case reflect.Chan:
case reflect.Ptr:
if !src.IsNil() && dest.CanSet() {
fmt.Println(src.Type().Name())
fmt.Println(dest.Type().Name())
x := reflect.New(dest.Type().Elem())
merge(x.Elem(), src.Elem())
dest.Set(x)
}
default:
if !dest.CanSet() {
return nil
}
dest.Set(src)
}
return nil
}