forked from cristalhq/aconfig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreflection.go
285 lines (240 loc) · 6.9 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
package aconfig
import (
"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{
defaultValueTag: field.Tag.Get(defaultValueTag),
usageTag: field.Tag.Get(usageTag),
envNameTag: l.makeTagValue(field, envNameTag, words),
flagNameTag: l.makeTagValue(field, flagNameTag, words),
}
for _, tag := range []string{jsonNameTag, yamlNameTag, tomlNameTag, hclNameTag} {
tags[tag] = l.makeTagValue(field, tag, words)
}
return tags
}
func (l *Loader) fullTag(f *fieldData, tag string) string {
sep := l.config.FlagDelimiter
if tag == envNameTag {
sep = l.config.envDelimiter
}
res := f.Tag(tag)
for p := f.parent; p != nil; p = p.parent {
res = p.Tag(tag) + sep + res
}
return 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
}
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.Slice:
return l.setSlice(field, fmt.Sprint(normalize(value)))
case reflect.Map:
return l.setMap(field, fmt.Sprint(value))
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)
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.newSimpleFieldData(reflect.New(field.field.Type.Elem()).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
}