-
Notifications
You must be signed in to change notification settings - Fork 29
/
struct_helper.go
609 lines (527 loc) · 15.8 KB
/
struct_helper.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
package toolbox
import (
"fmt"
"github.com/go-errors/errors"
"reflect"
"strings"
)
const (
fieldNameKey = "fieldName"
anonymousKey = "anonymous"
fieldIndexKey = "fieldIndex"
defaultKey = "default"
)
var columnMapping = []string{"column", "dateLayout", "dateFormat", "autoincrement", "primaryKey", "sequence", "valueMap", defaultKey, anonymousKey}
// ScanStructFunc scan supplied struct methods
func ScanStructMethods(structOrItsType interface{}, depth int, handler func(method reflect.Method) error) error {
var scanned = make(map[reflect.Type]bool)
return scanStructMethods(structOrItsType, scanned, depth, handler)
}
func scanStructMethods(structOrItsType interface{}, scanned map[reflect.Type]bool, depth int, handler func(method reflect.Method) error) error {
if depth < 0 {
return nil
}
structValue, err := TryDiscoverValueByKind(reflect.ValueOf(structOrItsType), reflect.Struct)
if err != nil {
structValue := reflect.ValueOf(structOrItsType)
if !(structValue.Kind() == reflect.Interface) {
return err
}
}
structType := structValue.Type()
if _, hasScan := scanned[structType]; hasScan {
return nil
}
scanned[structType] = true
for i := 0; i < structValue.NumField(); i++ {
fieldType := structType.Field(i)
if isExported := fieldType.PkgPath == ""; !isExported {
continue
}
if !fieldType.Anonymous {
continue
}
if !IsStruct(fieldType) {
continue
}
if fieldStructType, err := TryDiscoverTypeByKind(fieldType, reflect.Struct); err == nil {
fieldStruct := reflect.New(fieldStructType).Interface()
if err = scanStructMethods(fieldStruct, scanned, depth-1, handler); err != nil {
return err
}
}
}
structPtr, err := TryDiscoverValueByKind(reflect.ValueOf(structOrItsType), reflect.Ptr)
if err != nil {
return err
}
structTypePtr := structPtr.Type()
for i := 0; i < structTypePtr.NumMethod(); i++ {
method := structTypePtr.Method(i)
if isExported := method.PkgPath == ""; !isExported {
continue
}
if err := handler(method); err != nil {
return err
}
}
return nil
}
// StructField represents a struct field
type StructField struct {
Owner reflect.Value
Value reflect.Value
Type reflect.StructField
}
var onUnexportedHandler = IgnoreUnexportedFields
// UnexportedFieldHandler represents unexported field handler
type UnexportedFieldHandler func(structField *StructField) bool
// Handler ignoring unexported fields
func IgnoreUnexportedFields(structField *StructField) bool {
return false
}
func SetUnexportedFieldHandler(handler UnexportedFieldHandler) error {
if handler == nil {
return errors.New("handler was nil")
}
onUnexportedHandler = handler
return nil
}
// ProcessStruct reads passed in struct fields and values to pass it to provided handler
func ProcessStruct(aStruct interface{}, handler func(fieldType reflect.StructField, field reflect.Value) error) error {
structValue, err := TryDiscoverValueByKind(reflect.ValueOf(aStruct), reflect.Struct)
if err != nil {
return err
}
structType := structValue.Type()
var fields = make(map[string]*StructField)
for i := 0; i < structType.NumField(); i++ {
fieldType := structType.Field(i)
if !fieldType.Anonymous {
continue
}
field := structValue.Field(i)
if !IsStruct(field) {
fields[fieldType.Name] = &StructField{Type: fieldType, Value: field, Owner: structValue}
continue
}
var aStruct interface{}
if fieldType.Type.Kind() == reflect.Ptr {
if field.IsNil() {
if !field.CanSet() {
continue
}
structValue.Field(i).Set(reflect.New(fieldType.Type.Elem()))
}
aStruct = field.Interface()
} else {
if field.CanAddr() {
aStruct = field.Addr().Interface()
} else if field.CanInterface() {
aStruct = field.Interface()
} else {
continue
}
}
if err := ProcessStruct(aStruct, func(fieldType reflect.StructField, field reflect.Value) error {
structField := &StructField{Type: fieldType, Value: field, Owner: field}
if field.CanAddr() {
structField.Owner = field.Addr()
}
fields[fieldType.Name] = structField
return nil
}); err != nil {
return err
}
}
for i := 0; i < structType.NumField(); i++ {
fieldType := structType.Field(i)
if fieldType.Anonymous {
continue
}
field := structValue.Field(i)
structField := &StructField{Owner: structValue, Type: fieldType, Value: field}
if isExported := fieldType.PkgPath == ""; !isExported {
if !onUnexportedHandler(structField) {
continue
}
}
fields[fieldType.Name] = &StructField{Owner: structValue, Type: fieldType, Value: field}
}
for _, field := range fields {
if err := handler(field.Type, field.Value); err != nil {
return err
}
}
return nil
}
// BuildTagMapping builds map keyed by mappedKeyTag tag value, and value is another map of keys where tag name is presents in the tags parameter.
func BuildTagMapping(structTemplatePointer interface{}, mappedKeyTag string, resultExclusionTag string, inheritKeyFromField bool, convertKeyToLowerCase bool, tags []string) map[string](map[string]string) {
reflectStructType := DiscoverTypeByKind(structTemplatePointer, reflect.Struct)
var result = make(map[string]map[string]string)
var anonymousMappings = make(map[string]map[string]string)
for i := 0; i < reflectStructType.NumField(); i++ {
var field reflect.StructField
field = reflectStructType.Field(i)
key := getTagValues(field, mappedKeyTag)
if field.Anonymous && key == "" {
var anonymousType = DereferenceType(field.Type)
if anonymousType.Kind() == reflect.Struct {
anonymousMapping := BuildTagMapping(reflect.New(anonymousType).Interface(), mappedKeyTag, resultExclusionTag, inheritKeyFromField, convertKeyToLowerCase, tags)
for k, v := range anonymousMapping {
anonymousMappings[k] = v
anonymousMappings[k][anonymousKey] = "true"
anonymousMappings[k][fieldIndexKey] = AsString(i)
}
}
continue
}
isTransient := strings.EqualFold(field.Tag.Get(resultExclusionTag), "true")
if isTransient {
continue
}
if key == "" {
if !inheritKeyFromField {
continue
}
key = field.Name
}
if convertKeyToLowerCase {
key = strings.ToLower(key)
}
result[key] = make(map[string]string)
for _, tag := range tags {
tagValue := field.Tag.Get(tag)
if len(tagValue) > 0 {
result[key][tag] = tagValue
}
}
result[key][fieldNameKey] = field.Name
}
for k, v := range anonymousMappings {
if _, has := result[k]; !has {
result[k] = v
}
}
return result
}
func getTagValues(field reflect.StructField, mappedKeyTag string) string {
key := field.Tag.Get(mappedKeyTag)
key = strings.Split(key, ",")[0]
if mappedKeyTag == fieldNameKey {
key = field.Name
}
return key
}
// NewFieldSettingByKey reads field's tags and returns them indexed by passed in key, fieldName is always part of the resulting map unless filed has "transient" tag.
func NewFieldSettingByKey(aStruct interface{}, key string) map[string](map[string]string) {
return BuildTagMapping(aStruct, key, "transient", true, true, columnMapping)
}
func setEmptyMap(source reflect.Value, dataTypes map[string]bool) {
if !source.CanSet() {
return
}
mapType := source.Type()
mapPointer := reflect.New(mapType)
mapValueType := mapType.Elem()
mapKeyType := mapType.Key()
newMap := mapPointer.Elem()
newMap.Set(reflect.MakeMap(mapType))
targetMapKeyPointer := reflect.New(mapKeyType)
targetMapValuePointer := reflect.New(mapValueType)
var elementKey = targetMapKeyPointer.Elem()
var elementValue = targetMapValuePointer.Elem()
if elementValue.Kind() == reflect.Ptr && elementValue.IsNil() {
component := reflect.New(elementValue.Type().Elem())
elementValue.Set(component)
}
if elementKey.Type() != mapKeyType {
if elementKey.Type().AssignableTo(mapKeyType) {
elementKey = elementKey.Convert(mapKeyType)
}
}
if DereferenceType(elementValue.Type()).Kind() == reflect.Struct {
initStruct(elementValue.Interface(), dataTypes)
}
newMap.SetMapIndex(elementKey, elementValue)
var elem = mapPointer.Elem()
source.Set(elem)
}
func createEmptySlice(source reflect.Value, dataTypes map[string]bool) {
sliceType := DiscoverTypeByKind(source.Type(), reflect.Slice)
if !source.CanSet() {
return
}
slicePointer := reflect.New(sliceType)
slice := slicePointer.Elem()
componentType := DiscoverComponentType(sliceType)
var targetComponentPointer = reflect.New(componentType)
var targetComponent = targetComponentPointer.Elem()
if DereferenceType(componentType).Kind() == reflect.Struct {
componentType := targetComponent.Type()
isPointer := componentType.Kind() == reflect.Ptr
if isPointer {
componentType = componentType.Elem()
}
structElement := reflect.New(componentType)
initStruct(structElement.Interface(), dataTypes)
if isPointer {
targetComponentPointer.Elem().Set(structElement)
} else {
targetComponentPointer.Elem().Set(structElement.Elem())
}
initStruct(targetComponentPointer.Elem().Interface(), dataTypes)
}
slice.Set(reflect.Append(slice, targetComponentPointer.Elem()))
source.Set(slicePointer.Elem())
}
// InitStruct initialise any struct pointer to empty struct
func InitStruct(source interface{}) {
var dataTypes = make(map[string]bool)
if source == nil {
return
}
initStruct(source, dataTypes)
}
func initStruct(source interface{}, dataTypes map[string]bool) {
if source == nil {
return
}
if !IsStruct(source) {
return
}
var key = DereferenceType(source).Name()
if _, has := dataTypes[key]; has {
return
}
dataTypes[key] = true
sourceValue, ok := source.(reflect.Value)
if !ok {
sourceValue = reflect.ValueOf(source)
}
if sourceValue.Type().Kind() == reflect.Ptr {
elem := sourceValue.Elem()
if elem.Kind() == reflect.Ptr && elem.IsNil() {
return
}
if !sourceValue.Elem().IsValid() {
return
}
}
_ = ProcessStruct(source, func(fieldType reflect.StructField, fieldValue reflect.Value) error {
if !fieldValue.CanInterface() {
return nil
}
if fieldValue.Kind() == reflect.String && fieldValue.CanSet() {
fieldValue.SetString(" ")
return nil
}
if fieldType.Type.Kind() == reflect.Map {
setEmptyMap(fieldValue, dataTypes)
return nil
}
if fieldType.Type.Kind() == reflect.Slice {
createEmptySlice(fieldValue, dataTypes)
return nil
}
if fieldType.Type.Kind() != reflect.Ptr {
return nil
}
if DereferenceType(fieldType).Kind() == reflect.Struct {
if !fieldValue.CanSet() {
return nil
}
if fieldValue.Type().Kind() == reflect.Ptr {
fieldStruct := reflect.New(fieldValue.Type().Elem())
if reflect.TypeOf(source) != fieldStruct.Type() {
initStruct(fieldStruct.Interface(), dataTypes)
}
fieldValue.Set(fieldStruct)
}
}
return nil
})
}
// StructFieldMeta represents struct field meta
type StructFieldMeta struct {
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"`
Required bool `json:"required,"`
Description string `json:"description,omitempty"`
Anonymous bool `json:"anonymous,omitempty"`
Tag string `json:"tag,omitempty"`
}
// StructMeta represents struct meta details
type StructMeta struct {
Type string
rawType reflect.Type `json:"-"`
Fields []*StructFieldMeta `json:"fields,omitempty"`
Dependencies []*StructMeta `json:"dependencies,omitempty"`
}
func (m *StructMeta) Message() map[string]interface{} {
var result = make(map[string]interface{})
var deps = make(map[string]*StructMeta)
for _, dep := range m.Dependencies {
deps[dep.Type] = dep
}
for _, field := range m.Fields {
if dep, ok := deps[field.Type]; ok {
result[field.Name] = dep.Message()
continue
}
result[field.Name] = ""
}
return result
}
// StructMetaFilter
type StructMetaFilter func(field reflect.StructField) bool
func DefaultStructMetaFilter(ield reflect.StructField) bool {
return true
}
var structMetaFilter StructMetaFilter = DefaultStructMetaFilter
// SetStructMetaFilter sets struct meta filter
func SetStructMetaFilter(filter StructMetaFilter) error {
if filter == nil {
return errors.New("filter was nil")
}
structMetaFilter = filter
return nil
}
// GetStructMeta returns struct meta
func GetStructMeta(source interface{}) *StructMeta {
var result = &StructMeta{}
var trackedTypes = make(map[string]bool)
getStructMeta(source, result, trackedTypes)
return result
}
// InitStruct initialise any struct pointer to empty struct
func getStructMeta(source interface{}, meta *StructMeta, trackedTypes map[string]bool) bool {
if source == nil {
return false
}
var structType = fmt.Sprintf("%T", source)
if _, has := trackedTypes[structType]; has {
return false
}
meta.Type = structType
meta.Fields = make([]*StructFieldMeta, 0)
meta.Dependencies = make([]*StructMeta, 0)
sourceValue := reflect.ValueOf(source)
if sourceValue.Kind() == reflect.Ptr {
elem := sourceValue.Elem()
if elem.Kind() == reflect.Ptr && elem.IsNil() {
return false
}
if !sourceValue.Elem().IsValid() {
source = reflect.New(sourceValue.Type().Elem()).Interface()
}
}
meta.rawType = sourceValue.Type()
trackedTypes[structType] = true
_ = ProcessStruct(source, func(fieldType reflect.StructField, field reflect.Value) error {
if !structMetaFilter(fieldType) {
return nil
}
if isExported := fieldType.PkgPath == ""; !isExported {
structField := &StructField{
Owner: reflect.ValueOf(source),
Type: fieldType,
Value: field,
}
if !onUnexportedHandler(structField) {
return nil
}
field = structField.Value
}
if isJSONSkippable(string(fieldType.Tag)) {
return nil
}
fieldMeta := &StructFieldMeta{}
fieldMeta.Name = fieldType.Name
fieldMeta.Type = fieldType.Type.Name()
fieldMeta.Tag = string(fieldType.Tag)
fieldMeta.Anonymous = fieldType.Anonymous
meta.Fields = append(meta.Fields, fieldMeta)
if value, ok := fieldType.Tag.Lookup("required"); ok {
fieldMeta.Required = AsBoolean(value)
}
if value, ok := fieldType.Tag.Lookup("description"); ok {
fieldMeta.Description = value
}
var value = field.Interface()
if value == nil {
return nil
}
fieldMeta.Type = fmt.Sprintf("%T", value)
if fieldType.PkgPath != "" {
fieldMeta.Type = strings.Replace(fieldMeta.Type, "*", "", 1)
}
if IsStruct(value) {
var fieldStruct = &StructMeta{}
switch field.Kind() {
case reflect.Ptr:
var fieldValue interface{}
if field.IsNil() {
fieldValue = reflect.New(field.Type().Elem()).Interface()
} else {
fieldValue = field.Elem().Interface()
}
if getStructMeta(fieldValue, fieldStruct, trackedTypes) {
meta.Dependencies = append(meta.Dependencies, fieldStruct)
}
case reflect.Struct:
if field.CanInterface() {
if getStructMeta(field.Interface(), fieldStruct, trackedTypes) {
meta.Dependencies = append(meta.Dependencies, fieldStruct)
}
}
}
return nil
}
if IsMap(value) {
var aMap = AsMap(field.Interface())
var mapValue interface{}
for _, mapValue = range aMap {
break
}
if mapValue != nil && IsStruct(mapValue) {
var fieldStruct = &StructMeta{}
if getStructMeta(mapValue, fieldStruct, trackedTypes) {
meta.Dependencies = append(meta.Dependencies, fieldStruct)
}
}
return nil
}
if IsSlice(value) {
var aSlice = AsSlice(field.Interface())
if len(aSlice) > 0 {
if aSlice[0] != nil && IsStruct(aSlice[0]) {
var fieldStruct = &StructMeta{}
if getStructMeta(aSlice[0], fieldStruct, trackedTypes) {
meta.Dependencies = append(meta.Dependencies, fieldStruct)
}
}
}
return nil
}
return nil
})
return true
}
func isJSONSkippable(tag string) bool {
return strings.Contains(tag, "json:\"-")
}
// StructFields by name sorter
type StructFields []*StructField
// Len is part of sort.Interface.
func (s StructFields) Len() int {
return len(s)
}
// Swap is part of sort.Interface.
func (s StructFields) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// Less is part of sort.Interface.
func (s StructFields) Less(i, j int) bool {
return s[i].Type.Name < s[j].Type.Name
}