-
Notifications
You must be signed in to change notification settings - Fork 5
/
reflect.go
627 lines (579 loc) · 14.9 KB
/
reflect.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
package reflect
import (
"errors"
"fmt"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"unicode"
)
var (
// ErrInvalidStruct specifies invalid struct error
ErrInvalidStruct = errors.New("invalid struct specified")
// ErrInvalidParam specifies invalid url query params
ErrInvalidParam = errors.New("invalid url query param provided")
)
var (
bracketSplitter = regexp.MustCompile(`\[|\]`)
)
func fieldName(name string) string {
newstr := make([]rune, 0)
upper := false
for idx, chr := range name {
if idx == 0 {
upper = true
} else if chr == '_' {
upper = true
continue
}
if upper {
newstr = append(newstr, unicode.ToUpper(chr))
} else {
newstr = append(newstr, chr)
}
upper = false
}
return string(newstr)
}
// IsEmpty returns true if value empty
func IsEmpty(v reflect.Value) bool {
switch getKind(v) {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int:
return v.Int() == 0
case reflect.Uint:
return v.Uint() == 0
case reflect.Float32:
return v.Float() == 0
case reflect.Interface, reflect.Ptr:
if v.IsNil() {
return true
}
return IsEmpty(v.Elem())
case reflect.Func:
return v.IsNil()
case reflect.Invalid:
return true
case reflect.Struct:
var ok bool
for i := 0; i < v.NumField(); i++ {
ok = IsEmpty(v.FieldByIndex([]int{i}))
if !ok {
return false
}
}
default:
fmt.Printf("%#+v\n", v)
return false
}
return true
}
// IsZero returns true if struct is zero (not have any defined values)
func IsZero(src interface{}) bool {
v := reflect.ValueOf(src)
return IsEmpty(v)
}
// Zero creates new zero interface
func Zero(src interface{}) (interface{}, error) {
sv := reflect.ValueOf(src)
if sv.Kind() == reflect.Ptr {
sv = sv.Elem()
}
if sv.Kind() == reflect.Invalid {
return nil, ErrInvalidStruct
}
dst := reflect.New(sv.Type())
return dst.Interface(), nil
}
// StructFields returns slice of struct fields
func StructFields(src interface{}) ([]reflect.StructField, error) {
var fields []reflect.StructField
sv := reflect.ValueOf(src)
if sv.Kind() == reflect.Ptr {
sv = sv.Elem()
}
if sv.Kind() != reflect.Struct {
return nil, ErrInvalidStruct
}
typ := sv.Type()
for idx := 0; idx < typ.NumField(); idx++ {
fld := typ.Field(idx)
val := sv.Field(idx)
if !val.CanSet() || len(fld.PkgPath) != 0 {
continue
}
if val.Kind() == reflect.Struct {
infields, err := StructFields(val.Interface())
if err != nil {
return nil, err
}
fields = append(fields, infields...)
} else {
fields = append(fields, fld)
}
}
return fields, nil
}
// CopyDefaults for a from b
// a and b should be pointers to the same kind of struct
func CopyDefaults(a, b interface{}) {
pt := reflect.TypeOf(a)
t := pt.Elem()
va := reflect.ValueOf(a).Elem()
vb := reflect.ValueOf(b).Elem()
for i := 0; i < t.NumField(); i++ {
aField := va.Field(i)
if aField.CanSet() {
bField := vb.Field(i)
aField.Set(bField)
}
}
}
// CopyFrom sets the public members of a from b
// a and b should be pointers to structs
// a can be a different type from b
// Only the Fields which have the same name and assignable type on a
// and b will be set.
func CopyFrom(a, b interface{}) {
ta := reflect.TypeOf(a).Elem()
tb := reflect.TypeOf(b).Elem()
va := reflect.ValueOf(a).Elem()
vb := reflect.ValueOf(b).Elem()
for i := 0; i < tb.NumField(); i++ {
bField := vb.Field(i)
tbField := tb.Field(i)
name := tbField.Name
aField := va.FieldByName(name)
taField, found := ta.FieldByName(name)
if found && aField.IsValid() && bField.IsValid() && aField.CanSet() && tbField.Type.AssignableTo(taField.Type) {
aField.Set(bField)
}
}
}
// URLMap returns map of url query params
func URLMap(query string) (map[string]interface{}, error) {
var (
mp interface{} = make(map[string]interface{})
)
params := strings.Split(query, "&")
for _, part := range params {
tm, err := queryToMap(part)
if err != nil {
return nil, err
}
mp = merge(mp, tm)
}
return mp.(map[string]interface{}), nil
}
// FlattenMap expand key.subkey to nested map
func FlattenMap(a map[string]interface{}) map[string]interface{} {
// preprocess map
nb := make(map[string]interface{}, len(a))
for k, v := range a {
ps := strings.Split(k, ".")
if len(ps) == 1 {
nb[k] = v
continue
}
em := make(map[string]interface{})
em[ps[len(ps)-1]] = v
for i := len(ps) - 2; i > 0; i-- {
nm := make(map[string]interface{})
nm[ps[i]] = em
em = nm
}
if vm, ok := nb[ps[0]]; ok {
// nested map
nm := vm.(map[string]interface{})
for vk, vv := range em {
nm[vk] = vv
}
nb[ps[0]] = nm
} else {
nb[ps[0]] = em
}
}
return nb
}
// MergeMap merges maps
//nolint:gocyclo
func MergeMap(a interface{}, b map[string]interface{}) error {
var err error
ta := reflect.TypeOf(a)
if ta.Kind() == reflect.Ptr {
ta = ta.Elem()
}
va := reflect.ValueOf(a)
if va.Kind() == reflect.Ptr {
va = va.Elem()
}
for mk, mv := range b {
vmv := reflect.ValueOf(mv)
name := fieldName(mk)
fva := va.FieldByName(name)
fta, found := ta.FieldByName(name)
if !found || !fva.IsValid() || !fva.CanSet() || fta.PkgPath != "" {
continue
}
// fast path via direct assign
if vmv.Type().AssignableTo(fta.Type) && !IsEmpty(vmv) {
fva.Set(vmv)
continue
}
switch getKind(fva) {
case reflect.Bool:
err = mergeBool(fva, vmv)
case reflect.String:
err = mergeString(fva, vmv)
case reflect.Int:
err = mergeInt(fva, vmv)
case reflect.Uint:
err = mergeUint(fva, vmv)
case reflect.Float32:
err = mergeFloat(fva, vmv)
case reflect.Array:
//fmt.Printf("Array %#+v %#+v\n", fva, vmv)
case reflect.Slice:
err = mergeSlice(fva, vmv)
case reflect.Ptr:
if fva.IsNil() {
fva.Set(reflect.New(fva.Type().Elem()))
if fva.Elem().Type().Kind() == reflect.Struct {
for i := 0; i < fva.Elem().NumField(); i++ {
field := fva.Elem().Field(i)
if field.Type().Kind() == reflect.Ptr && field.IsNil() && fva.Elem().Type().Field(i).Anonymous {
field.Set(reflect.New(field.Type().Elem()))
}
}
}
}
if nmp, ok := vmv.Interface().(map[string]interface{}); ok {
err = MergeMap(fva.Interface(), nmp)
} else {
err = fmt.Errorf("cant fill")
}
case reflect.Struct:
if nmp, ok := vmv.Interface().(map[string]interface{}); ok {
err = MergeMap(fva.Interface(), nmp)
} else {
err = fmt.Errorf("cant fill")
}
case reflect.Map:
//fmt.Printf("Map %#+v %#+v\n", fva, vmv)
}
if err != nil {
return err
}
}
return nil
}
//nolint:gocyclo
func mergeSlice(va, vb reflect.Value) error {
switch getKind(vb) {
/*
case reflect.Int:
if vb.Int() == 1 {
va.SetBool(true)
}
case reflect.Uint:
if vb.Uint() == 1 {
va.SetBool(true)
}
case reflect.Float64:
if vb.Float() == 1 {
va.SetBool(true)
}
*/
case reflect.String:
var err error
fn := func(c rune) bool { return c == ',' || c == ';' || c == ' ' }
slice := strings.FieldsFunc(vb.String(), fn)
va.Set(reflect.MakeSlice(va.Type(), len(slice), len(slice)))
for idx, sl := range slice {
vl := reflect.ValueOf(sl)
switch va.Type().Elem().Kind() {
case reflect.Bool:
err = mergeBool(va.Index(idx), vl)
case reflect.String:
err = mergeString(va.Index(idx), vl)
case reflect.Ptr:
if va.Index(idx).IsNil() {
va.Index(idx).Set(reflect.New(va.Index(idx).Type().Elem()))
}
switch va.Type().Elem().String() {
case "*wrapperspb.BoolValue":
if eva := reflect.Indirect(va.Index(idx)).FieldByName("Value"); eva.IsValid() {
err = mergeBool(eva, vl)
}
case "*wrapperspb.BytesValue":
if eva := va.Index(idx).FieldByName("Value"); eva.IsValid() {
err = mergeUint(eva, vl)
}
case "*wrapperspb.DoubleValue", "*wrapperspb.FloatValue":
if eva := reflect.Indirect(va.Index(idx)).FieldByName("Value"); eva.IsValid() {
err = mergeFloat(eva, vl)
}
case "*wrapperspb.Int32Value", "*wrapperspb.Int64Value":
if eva := reflect.Indirect(va.Index(idx)).FieldByName("Value"); eva.IsValid() {
err = mergeInt(eva, vl)
}
case "*wrapperspb.StringValue":
if eva := reflect.Indirect(va.Index(idx)).FieldByName("Value"); eva.IsValid() {
err = mergeString(eva, vl)
}
case "*wrapperspb.UInt32Value", "*wrapperspb.UInt64Value":
if eva := reflect.Indirect(va.Index(idx)).FieldByName("Value"); eva.IsValid() {
err = mergeUint(eva, vl)
}
}
}
if err != nil {
return err
}
}
default:
return fmt.Errorf("cant merge %v %s with %v %s", va, va.Kind(), vb, vb.Kind())
}
return nil
}
func mergeBool(va, vb reflect.Value) error {
switch getKind(vb) {
case reflect.Int:
if vb.Int() == 1 {
va.SetBool(true)
}
case reflect.Uint:
if vb.Uint() == 1 {
va.SetBool(true)
}
case reflect.Float32:
if vb.Float() == 1 {
va.SetBool(true)
}
case reflect.String:
b, err := strconv.ParseBool(vb.String())
if err != nil {
return err
}
va.SetBool(b)
default:
return fmt.Errorf("cant merge %v %s with %v %s", va, va.Kind(), vb, vb.Kind())
}
return nil
}
func mergeString(va, vb reflect.Value) error {
switch getKind(vb) {
case reflect.Int:
va.SetString(fmt.Sprintf("%d", vb.Int()))
case reflect.Uint:
va.SetString(fmt.Sprintf("%d", vb.Uint()))
case reflect.Float32:
va.SetString(fmt.Sprintf("%f", vb.Float()))
case reflect.String:
va.Set(vb)
default:
return fmt.Errorf("cant merge %v %s with %v %s", va, va.Kind(), vb, vb.Kind())
}
return nil
}
func mergeInt(va, vb reflect.Value) error {
switch getKind(vb) {
case reflect.Int:
va.Set(vb)
case reflect.Uint:
va.SetInt(int64(vb.Uint()))
case reflect.Float32:
va.SetInt(int64(vb.Float()))
case reflect.String:
f, err := strconv.ParseInt(vb.String(), 10, va.Type().Bits())
if err != nil {
return err
}
va.SetInt(f)
default:
return fmt.Errorf("cant merge %v %s with %v %s", va, va.Kind(), vb, vb.Kind())
}
return nil
}
func mergeUint(va, vb reflect.Value) error {
switch getKind(vb) {
case reflect.Int:
va.SetUint(uint64(vb.Int()))
case reflect.Uint:
va.Set(vb)
case reflect.Float32:
va.SetUint(uint64(vb.Float()))
case reflect.String:
f, err := strconv.ParseUint(vb.String(), 10, va.Type().Bits())
if err != nil {
return err
}
va.SetUint(f)
default:
return fmt.Errorf("cant merge %v %s with %v %s", va, va.Kind(), vb, vb.Kind())
}
return nil
}
func mergeFloat(va, vb reflect.Value) error {
switch getKind(vb) {
case reflect.Int:
va.SetFloat(float64(vb.Int()))
case reflect.Uint:
va.SetFloat(float64(vb.Uint()))
case reflect.Float32:
va.Set(vb)
case reflect.String:
f, err := strconv.ParseFloat(vb.String(), va.Type().Bits())
if err != nil {
return err
}
va.SetFloat(f)
default:
return fmt.Errorf("cant merge %v %s with %v %s", va, va.Kind(), vb, vb.Kind())
}
return nil
}
func getKind(val reflect.Value) reflect.Kind {
kind := val.Kind()
switch {
case kind >= reflect.Int && kind <= reflect.Int64:
return reflect.Int
case kind >= reflect.Uint && kind <= reflect.Uint64:
return reflect.Uint
case kind >= reflect.Float32 && kind <= reflect.Float64:
return reflect.Float32
}
return kind
}
func btSplitter(str string) []string {
r := bracketSplitter.Split(str, -1)
for idx, s := range r {
if len(s) == 0 {
if len(r) > idx+1 {
copy(r[idx:], r[idx+1:])
r = r[:len(r)-1]
}
}
}
return r
}
// queryToMap turns something like a[b][c]=4 into
// map[string]interface{}{
// "a": map[string]interface{}{
// "b": map[string]interface{}{
// "c": 4,
// },
// },
// }
func queryToMap(param string) (map[string]interface{}, error) {
rawKey, rawValue, err := splitKeyAndValue(param)
if err != nil {
return nil, err
}
rawValue, err = url.QueryUnescape(rawValue)
if err != nil {
return nil, err
}
rawKey, err = url.QueryUnescape(rawKey)
if err != nil {
return nil, err
}
pieces := btSplitter(rawKey)
key := pieces[0]
// If len==1 then rawKey has no [] chars and we can just
// decode this as key=value into {key: value}
if len(pieces) == 1 {
return map[string]interface{}{
key: rawValue,
}, nil
}
// If len > 1 then we have something like a[b][c]=2
// so we need to turn this into {"a": {"b": {"c": 2}}}
// To do this we break our key into two pieces:
// a and b[c]
// and then we set {"a": queryToMap("b[c]", value)}
ret := make(map[string]interface{})
ret[key], err = queryToMap(buildNewKey(rawKey) + "=" + rawValue)
if err != nil {
return nil, err
}
// When URL params have a set of empty brackets (eg a[]=1)
// it is assumed to be an array. This will get us the
// correct value for the array item and return it as an
// []interface{} so that it can be merged properly.
if pieces[1] == "" {
temp := ret[key].(map[string]interface{})
ret[key] = []interface{}{temp[""]}
}
return ret, nil
}
// buildNewKey will take something like:
// origKey = "bar[one][two]"
// pieces = [bar one two ]
// and return "one[two]"
func buildNewKey(origKey string) string {
pieces := btSplitter(origKey)
ret := origKey[len(pieces[0])+1:]
ret = ret[:len(pieces[1])] + ret[len(pieces[1])+1:]
return ret
}
// splitKeyAndValue splits a URL param at the last equal
// sign and returns the two strings. If no equal sign is
// found, the ErrInvalidParam error is returned.
func splitKeyAndValue(param string) (string, string, error) {
li := strings.LastIndex(param, "=")
if li == -1 {
return "", "", ErrInvalidParam
}
return param[:li], param[li+1:], nil
}
// merge merges a with b if they are either both slices
// or map[string]interface{} types. Otherwise it returns b.
func merge(a interface{}, b interface{}) interface{} {
if av, aok := a.(map[string]interface{}); aok {
if bv, bok := b.(map[string]interface{}); bok {
return mergeMapIface(av, bv)
}
}
if av, aok := a.([]interface{}); aok {
if bv, bok := b.([]interface{}); bok {
return mergeSliceIface(av, bv)
}
}
va := reflect.ValueOf(a)
vb := reflect.ValueOf(b)
if (va.Type().Kind() == reflect.Slice) && (va.Type().Elem().Kind() == vb.Type().Kind() || vb.Type().ConvertibleTo(va.Type().Elem())) {
va = reflect.Append(va, vb.Convert(va.Type().Elem()))
return va.Interface()
}
return b
}
// mergeMap merges a with b, attempting to merge any nested
// values in nested maps but eventually overwriting anything
// in a that can't be merged with whatever is in b.
func mergeMapIface(a map[string]interface{}, b map[string]interface{}) map[string]interface{} {
for bK, bV := range b {
if aV, ok := a[bK]; ok {
if (reflect.ValueOf(aV).Type().Kind() == reflect.ValueOf(bV).Type().Kind()) ||
((reflect.ValueOf(aV).Type().Kind() == reflect.Slice) && reflect.ValueOf(aV).Type().Elem().Kind() == reflect.ValueOf(bV).Type().Kind()) {
nV := []interface{}{aV, bV}
a[bK] = nV
} else {
a[bK] = merge(a[bK], bV)
}
} else {
a[bK] = bV
}
}
return a
}
// mergeSlice merges a with b and returns the result.
func mergeSliceIface(a []interface{}, b []interface{}) []interface{} {
a = append(a, b...)
return a
}