-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode.go
395 lines (313 loc) · 10.1 KB
/
decode.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
package confiq
import (
"encoding"
"errors"
"fmt"
"reflect"
"strings"
)
const sliceSplitChar = ";"
// Collection of decode errors.
var (
ErrInvalidTarget = errors.New("target must be non-nil pointer to a slice, map or struct that has at least one exported field with a the configured tag")
ErrNoTargetFieldsAreSet = errors.New("none of the target fields were set from config values")
)
var (
errCannotDecodeCustomTypeField = errors.New("cannot decode field with custom decoder")
errCannotDecodeNonRequiredField = errors.New("cannot decode non-strict field")
errCannotDecodeNonSliceValueToTarget = errors.New("cannot decode non-slice value to target")
errCannotUnmarshalPrimitive = errors.New("cannot unmarshal primitive as text")
errCannotHaveDefaultForRequiredField = errors.New("cannot have default value for required field")
errUnsupportedPrimitiveKind = errors.New("unsupported primitive kind")
)
type (
decoderFunc func(targetField reflect.Value, value any) error
fieldDecoderFunc func(targetField reflect.Value, value any, strict bool) (int, error)
)
type fieldOptions struct {
path string
strict bool
required bool
defaultValue *string
}
type Decoder interface {
Decode(value any) error
}
// Decode decodes the configuration values into the target struct.
func (c *ConfigSet) Decode(target interface{}, options ...decodeOption) error {
return c.decode(target, options)
}
func (c *ConfigSet) decode(target interface{}, options []decodeOption) error {
decodeSettings := &decodeSettings{
strict: false,
prefix: "",
}
for _, option := range options {
option(decodeSettings)
}
targetValue := reflect.ValueOf(target)
if targetValue.Kind() != reflect.Ptr || targetValue.IsNil() {
return ErrInvalidTarget
}
targetValue = targetValue.Elem()
decodedFieldCount, err := c.decodeField(targetValue, fieldOptions{
path: decodeSettings.prefix,
strict: decodeSettings.strict,
required: false,
defaultValue: nil,
})
if err != nil {
return err
} else if decodedFieldCount == 0 {
return ErrNoTargetFieldsAreSet
}
return nil
}
func (c *ConfigSet) getFieldConfigValue(fieldOpts fieldOptions) (any, error) {
if fieldOpts.required && fieldOpts.defaultValue != nil {
return nil, fmt.Errorf("%w: %s", errCannotHaveDefaultForRequiredField, fieldOpts.path)
}
configValue, err := c.getByPath(fieldOpts.path)
if err != nil {
if fieldOpts.required {
return nil, fmt.Errorf("field is required: %w", err)
}
if fieldOpts.defaultValue != nil {
return *fieldOpts.defaultValue, nil
}
return nil, errCannotDecodeNonRequiredField
}
return configValue, nil
}
func (c *ConfigSet) decodeField(targetValue reflect.Value, fieldOpts fieldOptions) (int, error) {
fieldConfigValue, err := c.getFieldConfigValue(fieldOpts)
if err != nil {
if !errors.Is(err, errCannotDecodeNonRequiredField) {
return 0, err
}
}
var (
decodedFields int
decodeErr error
fieldDecoder fieldDecoderFunc
)
if commonDecoder := getCommonDecoder(targetValue.Type()); commonDecoder != nil {
if err := commonDecoder(targetValue, fieldConfigValue); err != nil {
if fieldOpts.strict {
return 0, fmt.Errorf("error decoding field value: %w", err)
}
return 0, nil
}
return 1, nil
}
if targetValue.Kind() == reflect.Ptr {
dereferencedTargetValue := reflect.New(targetValue.Type().Elem()).Elem()
decodedFields, err := c.decodeField(dereferencedTargetValue, fieldOpts)
if err != nil {
if fieldOpts.strict {
return 0, fmt.Errorf("error decoding pointer value: %w", err)
}
return 0, nil
}
targetValue.Set(dereferencedTargetValue.Addr())
return decodedFields, nil
}
// check if targetValue implements Decoder interface
if decoder, ok := targetValue.Addr().Interface().(Decoder); ok {
if err := decoder.Decode(fieldConfigValue); err != nil {
return 0, fmt.Errorf("%w: %w", errCannotDecodeCustomTypeField, err)
}
return 1, nil
}
switch targetValue.Kind() {
case reflect.Map:
fieldDecoder = c.decodeMap
case reflect.Slice:
fieldDecoder = c.decodeSlice
case reflect.Struct:
fieldDecoder = c.decodeStruct
default:
fieldDecoder = c.decodePrimitiveType
}
decodedFields, decodeErr = fieldDecoder(targetValue, fieldConfigValue, fieldOpts.strict)
if decodeErr != nil {
return 0, decodeErr
}
return decodedFields, nil
}
func (c *ConfigSet) decodeMap(targetMapValue reflect.Value, configValue any, strict bool) (int, error) {
var (
configMapValue = reflect.ValueOf(configValue)
targetMapValueType = targetMapValue.Type()
targetKeyType = targetMapValueType.Key()
targetValueType = targetMapValueType.Elem()
setFieldCount = 0
)
// setup empty map
targetMapValue.Set(reflect.MakeMap(targetMapValueType))
for _, key := range configMapValue.MapKeys() {
var (
k = reflect.New(targetKeyType).Elem()
v = reflect.New(targetValueType).Elem()
)
// decode map key
_, err := c.decodePrimitiveType(k, key.Interface(), strict)
if err != nil {
return 0, fmt.Errorf("error decoding map key: %w", err)
}
// decode map value
decodedFieldCount, err := c.subValue(configValue).
decodeField(v, fieldOptions{
path: keySegment(key.String()).String(),
strict: strict,
required: false,
defaultValue: nil,
})
if err != nil {
return 0, fmt.Errorf("error decoding map value: %w", err)
}
targetMapValue.SetMapIndex(k, v)
setFieldCount += decodedFieldCount
}
return setFieldCount, nil
}
func (c *ConfigSet) decodeStruct(targetStructValue reflect.Value, configValue any, strict bool) (int, error) {
var (
targetStructType = targetStructValue.Type()
setFieldCount = 0
)
for i := range targetStructValue.NumField() {
// get the struct field's tag and options
targetStructFieldOpts := c.readTag(targetStructType.Field(i), c.decoder.tag)
// get the struct field's reflection value
targetStructFieldValue := targetStructValue.Field(i)
// check if the field is exported
if !targetStructFieldValue.CanSet() || !targetStructFieldValue.Addr().CanInterface() {
continue
}
// set the field's strictness
targetStructFieldOpts.strict = strict || targetStructFieldOpts.strict
// decode the field
decodedFieldCount, err := c.subValue(configValue).
decodeField(targetStructFieldValue, targetStructFieldOpts)
if err != nil {
return 0, fmt.Errorf("error decoding struct field value: %w", err)
}
setFieldCount += decodedFieldCount
}
return setFieldCount, nil
}
func (c *ConfigSet) decodeSlice(targetSliceValue reflect.Value, configValue any, strict bool) (int, error) {
var (
configSliceValue = reflect.ValueOf(configValue)
configSliceValueKind = configSliceValue.Kind()
setFieldCount = 0
)
if configSliceValueKind != reflect.Slice {
if configSliceValueKind != reflect.String {
return 0, fmt.Errorf("%w: %v", errCannotDecodeNonSliceValueToTarget, configSliceValueKind)
}
return c.decodeSlice(targetSliceValue, strings.Split(configSliceValue.String(), sliceSplitChar), strict)
}
configSliceValueLength := configSliceValue.Len()
// Set slice to the same length as the config slice
targetSliceValue.Set(reflect.MakeSlice(targetSliceValue.Type(), configSliceValueLength, configSliceValueLength))
// Decode each element based on its type
for i := range configSliceValueLength {
decodedFieldCount, err := c.subValue(configValue).
decodeField(targetSliceValue.Index(i), fieldOptions{
path: indexSegment(i).String(),
strict: strict,
required: false,
defaultValue: nil,
})
if err != nil {
return setFieldCount, fmt.Errorf("error decoding slice element value: %w", err)
}
setFieldCount += decodedFieldCount
}
return setFieldCount, nil
}
func (c *ConfigSet) decodePrimitiveType(primitiveValue reflect.Value, configValue any, strict bool) (int, error) {
primitiveInterface := primitiveValue.Addr().Interface()
// check if primitive implements encoding.TextUnmarshaler interface
if unmarshaler, ok := primitiveInterface.(encoding.TextUnmarshaler); ok {
if err := unmarshaler.UnmarshalText(castToBytes(configValue)); err != nil {
return 0, fmt.Errorf("%w: %w", errCannotUnmarshalPrimitive, err)
}
primitiveValue.Set(reflect.ValueOf(primitiveInterface).Elem())
return 1, nil
}
// select the appropriate decoder function based on the primitive's kind
var (
primitiveDecoderFunc decoderFunc
primitiveValueKind = primitiveValue.Kind()
)
switch primitiveValueKind {
case reflect.Bool:
primitiveDecoderFunc = decodeBool
case reflect.String:
primitiveDecoderFunc = decodeString
case reflect.Float32, reflect.Float64:
primitiveDecoderFunc = decodeFloat
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
primitiveDecoderFunc = decodeInt
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
primitiveDecoderFunc = decodeUint
default:
return 0, fmt.Errorf("%w: %v", errUnsupportedPrimitiveKind, primitiveValueKind)
}
if err := primitiveDecoderFunc(primitiveValue, configValue); err != nil {
if strict {
return 0, fmt.Errorf("error decoding primitive value: %w", err)
}
return 0, nil
}
return 1, nil
}
func (c *ConfigSet) readTag(field reflect.StructField, tag string) fieldOptions {
fieldOpts := fieldOptions{
path: "",
strict: false,
required: false,
defaultValue: nil,
}
tagValue := field.Tag.Get(tag)
if tagValue == "" {
return fieldOpts
}
tagParts := strings.Split(tagValue, ",")
fieldOpts.path = tagParts[0]
// read the remaining tag parts
for _, part := range tagParts[1:] {
if part == "strict" {
fieldOpts.strict = true
continue
}
if part == "required" {
fieldOpts.required = true
continue
}
if strings.HasPrefix(part, "default=") {
devaultValue := part[8:]
fieldOpts.defaultValue = &devaultValue
continue
}
}
return fieldOpts
}
func (c *ConfigSet) subValue(value any) *ConfigSet {
return &ConfigSet{
value: &value,
decoder: c.decoder,
}
}
func castToBytes(value any) []byte {
return []byte(castToString(value))
}
func castToString(value any) string {
if stringValue, ok := value.(string); ok {
return stringValue
}
return fmt.Sprintf("%v", value)
}