forked from viant/toolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstruct_helper.go
369 lines (324 loc) · 9.99 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
package toolbox
import (
"fmt"
"reflect"
"strings"
)
const (
fieldNameKey = "fieldName"
anonymousKey = "anonymous"
fieldIndexKey = "fieldIndex"
defaultKey = "default"
)
var columnMapping = []string{"column", "dateLayout", "dateFormat", "autoincrement", "primaryKey", "sequence", "valueMap", defaultKey, anonymousKey}
//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 := DiscoverValueByKind(reflect.ValueOf(aStruct), reflect.Struct)
structType := structValue.Type()
var isPrivate = func(candidate string) bool {
if candidate == "" {
return true
}
return strings.ToLower(candidate[0:1]) == candidate[0:1]
}
type fieldStruct struct {
Value reflect.Value
Type reflect.StructField
}
var fields = make(map[string]*fieldStruct)
for i := 0; i < structType.NumField(); i++ {
fieldType := structType.Field(i)
if !fieldType.Anonymous {
continue
}
field := structValue.Field(i)
if !IsStruct(field) {
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() {
continue
}
aStruct = field.Addr().Interface()
}
if err := ProcessStruct(aStruct, func(fieldType reflect.StructField, field reflect.Value) error {
fields[fieldType.Name] = &fieldStruct{Type: fieldType, Value: field}
return nil
}); err != nil {
return err
}
}
for i := 0; i < structType.NumField(); i++ {
fieldType := structType.Field(i)
fieldName := fieldType.Name
if isPrivate(fieldName) || fieldType.Anonymous {
continue
}
field := structValue.Field(i)
fields[fieldType.Name] = &fieldStruct{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)
if field.Anonymous {
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
}
key := field.Tag.Get(mappedKeyTag)
if mappedKeyTag == fieldNameKey {
key = field.Name
}
if len(key) == 0 {
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
}
//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 {
structElement := reflect.New(targetComponent.Type().Elem())
initStruct(structElement.Interface(), dataTypes)
targetComponentPointer.Elem().Set(structElement)
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)
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 && !sourceValue.Elem().IsValid() {
return
}
ProcessStruct(source, func(fieldType reflect.StructField, fieldValue reflect.Value) error {
if !fieldValue.CanInterface() {
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"`
}
//StructMeta represents struct meta details
type StructMeta struct {
Type string
Fields []*StructFieldMeta `json:"fields,omitempty"`
Dependencies []*StructMeta `json:"dependencies,omitempty"`
}
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
trackedTypes[structType] = true
meta.Fields = make([]*StructFieldMeta, 0)
meta.Dependencies = make([]*StructMeta, 0)
ProcessStruct(source, func(fieldType reflect.StructField, field reflect.Value) error {
fieldMeta := &StructFieldMeta{}
if strings.Contains(string(fieldType.Tag), "json:\"-") {
return nil
}
meta.Fields = append(meta.Fields, fieldMeta)
fieldMeta.Name = fieldType.Name
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 IsStruct(value) {
var fieldStruct = &StructMeta{}
if field.Kind() == reflect.Ptr && !field.IsNil() {
if getStructMeta(field.Elem().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
}