-
Notifications
You must be signed in to change notification settings - Fork 32
/
reflection.go
429 lines (369 loc) · 10.6 KB
/
reflection.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
package aconfig
import (
"encoding"
"fmt"
"reflect"
"strconv"
"strings"
"time"
)
type fieldData struct {
name string
parent *fieldData
field reflect.StructField
value reflect.Value
isSet bool
isRequired bool
tags map[string]string
}
func (f *fieldData) Name() string {
return f.name
}
func (f *fieldData) Tag(tag string) string {
if t, ok := f.tags[tag]; ok {
return t
}
return f.field.Tag.Get(tag)
}
func (f *fieldData) Parent() (Field, bool) {
return f.parent, f.parent != nil
}
func (l *Loader) newSimpleFieldData(value reflect.Value) *fieldData {
return l.newFieldData(reflect.StructField{}, value, nil)
}
func (l *Loader) newFieldData(field reflect.StructField, value reflect.Value, parent *fieldData) *fieldData {
requiredTag := field.Tag.Get("required")
if requiredTag != "" && requiredTag != "true" {
panic(fmt.Sprintf("aconfig: incorrect value for 'required' tag: %v", requiredTag))
}
fd := &fieldData{
name: makeName(field.Name, parent),
parent: parent,
value: value,
field: field,
isSet: false,
isRequired: requiredTag == "true",
tags: l.tagsForField(field),
}
return fd
}
func (l *Loader) tagsForField(field reflect.StructField) map[string]string {
words := splitNameByWords(field.Name)
tags := map[string]string{
"default": field.Tag.Get("default"),
"usage": field.Tag.Get("usage"),
"env": l.makeTagValue(field, "env", words),
"flag": l.makeTagValue(field, "flag", words),
}
for _, dec := range l.config.FileDecoders {
tags[dec.Format()] = l.makeTagValue(field, dec.Format(), words)
}
return tags
}
func (l *Loader) fullTag(prefix string, f *fieldData, tag string) string {
sep := "."
if tag == "flag" {
sep = l.config.FlagDelimiter
}
if tag == "env" {
sep = l.config.envDelimiter
}
res := f.Tag(tag)
if res == "-" {
return ""
}
if before, _, ok := cut(res, ",exact"); ok {
return before
}
if before, _, ok := cut(res, ",omitempty"); ok {
return before
}
for p := f.parent; p != nil; p = p.parent {
if p.Tag(tag) != "-" {
res = p.Tag(tag) + sep + res
}
}
return prefix + res
}
func (l *Loader) getFields(x interface{}) []*fieldData {
value := reflect.ValueOf(x)
for value.Type().Kind() == reflect.Ptr {
value = value.Elem()
}
return l.getFieldsHelper(value, nil)
}
func (l *Loader) getFieldsHelper(valueObject reflect.Value, parent *fieldData) []*fieldData {
typeObject := valueObject.Type()
count := valueObject.NumField()
fields := make([]*fieldData, 0, count)
for i := 0; i < count; i++ {
value := valueObject.Field(i)
field := typeObject.Field(i)
if !value.CanSet() {
continue
}
fd := l.newFieldData(field, value, parent)
// if it's a struct - expand and process it's fields
kind := field.Type.Kind()
if kind == reflect.Ptr {
kind = field.Type.Elem().Kind()
}
if kind == reflect.Struct {
var subFieldParent *fieldData
if field.Anonymous {
subFieldParent = parent
} else {
subFieldParent = fd
}
if field.Type.Kind() == reflect.Ptr {
value.Set(reflect.New(field.Type.Elem()))
value = value.Elem()
}
fields = append(fields, l.getFieldsHelper(value, subFieldParent)...)
continue
}
fields = append(fields, fd)
}
return fields
}
func (l *Loader) setFieldData(field *fieldData, value interface{}) error {
// unwrap pointers
for field.value.Type().Kind() == reflect.Ptr {
if field.value.IsNil() {
field.value.Set(reflect.New(field.value.Type().Elem()))
}
field.value = field.value.Elem()
}
if value == "" {
return nil
}
if field.value.CanAddr() {
pv := field.value.Addr().Interface()
if v, ok := pv.(encoding.TextUnmarshaler); ok {
return v.UnmarshalText([]byte(fmt.Sprint(value)))
}
}
switch kind := field.value.Type().Kind(); kind {
case reflect.Bool:
return l.setBool(field, fmt.Sprint(value))
case reflect.String:
return l.setString(field, fmt.Sprint(value))
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:
return l.setInt(field, fmt.Sprint(value))
case reflect.Int64:
return l.setInt64(field, fmt.Sprint(value))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return l.setUint(field, fmt.Sprint(value))
case reflect.Float32, reflect.Float64:
return l.setFloat(field, fmt.Sprint(value))
case reflect.Interface:
return l.setInterface(field, value)
case reflect.Struct:
fd := l.newFieldData(reflect.StructField{}, field.value, nil)
return l.m2s(mii(value), fd.value)
case reflect.Slice:
if field.field.Type.Elem().Kind() == reflect.Struct {
if value == nil {
return nil
}
if v, ok := value.([]interface{}); ok {
slice := reflect.MakeSlice(field.field.Type, len(v), len(v))
for i, val := range v {
vv := mii(val)
fd := l.newFieldData(reflect.StructField{}, slice.Index(i), nil)
if err := l.m2s(vv, fd.value); err != nil {
return err
}
}
field.value.Set(slice)
return nil
}
v, ok := value.([]map[string]interface{})
if !ok {
panic(fmt.Errorf("%T %v", value, value))
}
slice := reflect.MakeSlice(field.field.Type, len(v), len(v))
for i, val := range v {
fd := l.newFieldData(reflect.StructField{}, slice.Index(i), nil)
if err := l.m2s(val, fd.value); err != nil {
return err
}
}
field.value.Set(slice)
return nil
}
return l.setSlice(field, sliceToString(value))
case reflect.Map:
v, ok := value.(map[string]interface{})
if !ok {
return l.setMap(field, fmt.Sprint(value))
}
mapp := reflect.MakeMapWithSize(field.field.Type, len(v))
for key, val := range v {
fdk := l.newSimpleFieldData(reflect.New(field.field.Type.Key()).Elem())
if err := l.setFieldData(fdk, key); err != nil {
return fmt.Errorf("incorrect map key %q: %w", key, err)
}
fdv := l.newFieldData(reflect.StructField{}, reflect.New(field.value.Type().Elem()).Elem(), field)
fdv.field.Type = field.value.Type().Elem()
if err := l.setFieldData(fdv, val); err != nil {
return fmt.Errorf("incorrect map value %q: %w", val, err)
}
mapp.SetMapIndex(fdk.value, fdv.value)
}
field.value.Set(mapp)
return nil
default:
return fmt.Errorf("type kind %q isn't supported", kind)
}
}
func (*Loader) setBool(field *fieldData, value string) error {
val, err := strconv.ParseBool(value)
if err != nil {
return err
}
field.value.SetBool(val)
return nil
}
func (*Loader) setInt(field *fieldData, value string) error {
val, err := strconv.ParseInt(value, 0, field.value.Type().Bits())
if err != nil {
return err
}
field.value.SetInt(val)
return nil
}
func (l *Loader) setInt64(field *fieldData, value string) error {
if field.field.Type == reflect.TypeOf(time.Second) {
val, err := time.ParseDuration(value)
if err != nil {
return err
}
field.value.Set(reflect.ValueOf(val))
return nil
}
return l.setInt(field, value)
}
func (*Loader) setUint(field *fieldData, value string) error {
val, err := strconv.ParseUint(value, 0, field.value.Type().Bits())
if err != nil {
return err
}
field.value.SetUint(val)
return nil
}
func (*Loader) setFloat(field *fieldData, value string) error {
val, err := strconv.ParseFloat(value, field.value.Type().Bits())
if err != nil {
return err
}
field.value.SetFloat(val)
return nil
}
func (*Loader) setString(field *fieldData, value string) error {
field.value.SetString(value)
return nil
}
func (*Loader) setInterface(field *fieldData, value interface{}) error {
field.value.Set(reflect.ValueOf(value))
return nil
}
func (l *Loader) setSlice(field *fieldData, value string) error {
// Special case for []byte
if field.field.Type.Elem().Kind() == reflect.Uint8 {
value := reflect.ValueOf([]byte(value))
field.value.Set(value)
return nil
}
vals := strings.Split(value, ",")
slice := reflect.MakeSlice(field.field.Type, len(vals), len(vals))
for i, val := range vals {
val = strings.TrimSpace(val)
fd := l.newFieldData(reflect.StructField{}, slice.Index(i), nil)
fd.field.Type = field.field.Type.Elem()
if err := l.setFieldData(fd, val); err != nil {
return fmt.Errorf("incorrect slice item %q: %w", val, err)
}
}
field.value.Set(slice)
return nil
}
func (l *Loader) setMap(field *fieldData, value string) error {
vals := strings.Split(value, ",")
mapField := reflect.MakeMapWithSize(field.field.Type, len(vals))
for _, val := range vals {
entry := strings.SplitN(val, ":", 2)
if len(entry) != 2 {
return fmt.Errorf("incorrect map item: %s", val)
}
key := strings.TrimSpace(entry[0])
val := strings.TrimSpace(entry[1])
fdk := l.newSimpleFieldData(reflect.New(field.field.Type.Key()).Elem())
if err := l.setFieldData(fdk, key); err != nil {
return fmt.Errorf("incorrect map key %q: %w", key, err)
}
fdv := l.newFieldData(reflect.StructField{}, reflect.New(field.value.Type().Elem()).Elem(), field)
fdv.field.Type = field.value.Type().Elem()
if err := l.setFieldData(fdv, val); err != nil {
return fmt.Errorf("incorrect map value %q: %w", val, err)
}
mapField.SetMapIndex(fdk.value, fdv.value)
}
field.value.Set(mapField)
return nil
}
func (l *Loader) m2s(m map[string]interface{}, structValue reflect.Value) error {
for name, value := range m {
name = strings.Title(name)
structFieldValue := structValue.FieldByName(name)
if !structFieldValue.IsValid() {
return fmt.Errorf("no such field %q in struct", name)
}
if !structFieldValue.CanSet() {
return fmt.Errorf("cannot set %q field value", name)
}
val := reflect.ValueOf(value)
if structFieldValue.Type() != val.Type() {
if structFieldValue.Kind() == reflect.Slice && val.Kind() == reflect.Slice {
vals := value.([]interface{})
slice := reflect.MakeSlice(structFieldValue.Type(), len(vals), len(vals))
if isPrimitive(structFieldValue.Type().Elem()) {
for i := 0; i < len(vals); i++ {
fd := l.newFieldData(reflect.StructField{}, slice.Index(i), nil)
if err := l.setFieldData(fd, vals[i]); err != nil {
return fmt.Errorf("incorrect slice item %q: %w", vals[i], err)
}
}
} else {
for i := 0; i < len(vals); i++ {
a := mii(vals[i])
b := slice.Index(i)
if err := l.m2s(a, b); err != nil {
return err
}
}
}
structFieldValue.Set(slice)
continue
} else {
return fmt.Errorf("provided value type do not match struct field type (%v and %v)", structFieldValue.Type(), val.Type())
}
}
structFieldValue.Set(val)
}
return nil
}
func mii(m interface{}) map[string]interface{} {
switch m := m.(type) {
case map[string]interface{}:
return m
case map[interface{}]interface{}:
res := map[string]interface{}{}
for k, v := range m {
res[k.(string)] = v
}
return res
default:
panic(fmt.Sprintf("%T %v", m, m))
}
}