/
copier.go
238 lines (214 loc) · 6.11 KB
/
copier.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
package copier
import (
"database/sql"
"errors"
"fmt"
"reflect"
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
)
var _ignore = fmt.Sprint("")
// Copy copy things
func Copy(toValue interface{}, fromValue interface{}) (err error) {
var (
isSlice bool
amount = 1
from = indirect(reflect.ValueOf(fromValue))
to = indirect(reflect.ValueOf(toValue))
)
if !to.CanAddr() {
return errors.New("copy to value is unaddressable")
}
// Return is from value is invalid
if !from.IsValid() {
return
}
// Just set it if possible to assign
if from.Type().AssignableTo(to.Type()) {
to.Set(from)
return
}
fromType := indirectType(from.Type())
toType := indirectType(to.Type())
if fromType.Kind() != reflect.Struct || toType.Kind() != reflect.Struct {
return
}
if to.Kind() == reflect.Slice {
isSlice = true
if from.Kind() == reflect.Slice {
amount = from.Len()
}
}
for i := 0; i < amount; i++ {
var dest, source reflect.Value
if isSlice {
// source
if from.Kind() == reflect.Slice {
source = indirect(from.Index(i))
} else {
source = indirect(from)
}
// dest
dest = indirect(reflect.New(toType).Elem())
} else {
source = indirect(from)
dest = indirect(to)
}
// check source
if source.IsValid() {
fromTypeFields := deepFields(fromType)
//fmt.Printf("%#v", fromTypeFields)
// Copy from field to field or method
for _, field := range fromTypeFields {
name := field.Name
if fromField := source.FieldByName(name); fromField.IsValid() {
// has field
if toField := dest.FieldByName(name); toField.IsValid() {
if toField.CanSet() {
if !set(toField, fromField) {
if err := Copy(toField.Addr().Interface(), fromField.Interface()); err != nil {
return err
}
}
}
} else {
// try to set to method
var toMethod reflect.Value
if dest.CanAddr() {
toMethod = dest.Addr().MethodByName(name)
} else {
toMethod = dest.MethodByName(name)
}
if toMethod.IsValid() && toMethod.Type().NumIn() == 1 && fromField.Type().AssignableTo(toMethod.Type().In(0)) {
toMethod.Call([]reflect.Value{fromField})
}
}
}
}
// Copy from method to field
for _, field := range deepFields(toType) {
name := field.Name
var fromMethod reflect.Value
if source.CanAddr() {
fromMethod = source.Addr().MethodByName(name)
} else {
fromMethod = source.MethodByName(name)
}
if fromMethod.IsValid() && fromMethod.Type().NumIn() == 0 && fromMethod.Type().NumOut() == 1 {
if toField := dest.FieldByName(name); toField.IsValid() && toField.CanSet() {
values := fromMethod.Call([]reflect.Value{})
if len(values) >= 1 {
set(toField, values[0])
}
}
}
}
}
if isSlice {
if dest.Addr().Type().AssignableTo(to.Type().Elem()) {
to.Set(reflect.Append(to, dest.Addr()))
} else if dest.Type().AssignableTo(to.Type().Elem()) {
to.Set(reflect.Append(to, dest))
}
}
}
return
}
func deepFields(reflectType reflect.Type) []reflect.StructField {
var fields []reflect.StructField
if reflectType = indirectType(reflectType); reflectType.Kind() == reflect.Struct {
for i := 0; i < reflectType.NumField(); i++ {
v := reflectType.Field(i)
if v.Anonymous {
fields = append(fields, deepFields(v.Type)...)
} else {
fields = append(fields, v)
}
}
}
return fields
}
func indirect(reflectValue reflect.Value) reflect.Value {
for reflectValue.Kind() == reflect.Ptr {
reflectValue = reflectValue.Elem()
}
return reflectValue
}
func indirectType(reflectType reflect.Type) reflect.Type {
for reflectType.Kind() == reflect.Ptr || reflectType.Kind() == reflect.Slice {
reflectType = reflectType.Elem()
}
return reflectType
}
var (
timePtrType = reflect.TypeOf(&time.Time{})
)
func set(to, from reflect.Value) bool {
//fmt.Printf("to=%s, from=%s\n", to.Type().String(), from.Type().Name())
var toPtr reflect.Value
if from.IsValid() {
fromTypeName := from.Type().Name()
if to.Kind() == reflect.Ptr {
toPtr = to
//set `to` to nil if from is nil
if from.Kind() == reflect.Ptr && from.IsNil() {
to.Set(reflect.Zero(to.Type()))
return true
} else if fromTypeName == "int64" && to.Type() == timePtrType && from.Int() <= 0 {
// int64(0) => *time.Timer(nil)
return true
} else if to.IsNil() {
to.Set(reflect.New(to.Type().Elem()))
}
to = to.Elem()
}
toTypeName := to.Type().Name()
if fromTypeName == "uint64" && toTypeName == "string" {
to.SetString(fmt.Sprintf("%d", from.Interface()))
} else if from.Type().ConvertibleTo(to.Type()) {
to.Set(from.Convert(to.Type()))
} else if scanner, ok := to.Addr().Interface().(sql.Scanner); ok {
err := scanner.Scan(from.Interface())
if err != nil {
return false
}
} else if from.Kind() == reflect.Ptr {
return set(to, from.Elem())
} else if fromTypeName == "int64" && toTypeName == "Time" {
//int64 to time.Time, default is second
t := time.Unix(from.Int(), 0)
to.Set(reflect.ValueOf(t))
} else if toTypeName == "int64" && fromTypeName == "Time" {
//time.Time to int64
to.SetInt(from.Interface().(time.Time).Unix())
} else if fromTypeName == "string" && toTypeName == "Time" {
//string to time.Time
//RFC3339
timeStr := from.String()
if timeStr == "" && toPtr.Kind() == reflect.Ptr { //空为nil
toPtr.Set(reflect.Zero(toPtr.Type()))
return true
}
t, err := time.Parse(time.RFC3339, timeStr)
if err == nil {
to.Set(reflect.ValueOf(t))
}
} else if fromTypeName == "Time" && toTypeName == "string" {
//time.Time to string
to.SetString(from.Interface().(time.Time).Format(time.RFC3339))
} else if fromTypeName == "string" && toTypeName == "ObjectID" {
oid, err := primitive.ObjectIDFromHex(from.String())
if err != nil {
return false
}
to.Set(reflect.ValueOf(oid))
} else if fromTypeName == "ObjectID" && toTypeName == "string" {
oid := from.Interface().(primitive.ObjectID)
to.Set(reflect.ValueOf(oid.Hex()))
} else {
//fmt.Printf("to=%s, from=%s\n", to.Type().Name(), from.Type().Name())
return false
}
}
return true
}