-
Notifications
You must be signed in to change notification settings - Fork 33
/
parser.go
522 lines (453 loc) · 12.2 KB
/
parser.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
package aconfig
import (
"encoding"
"flag"
"fmt"
"reflect"
"strings"
"time"
"github.com/mitchellh/mapstructure"
)
type structParser struct {
cfg Config
fields map[string]any
flagSet *flag.FlagSet
envNames map[string]struct{}
flagNames map[string]struct{}
}
func newStructParser(cfg Config) *structParser {
return &structParser{
cfg: cfg,
flagSet: flag.NewFlagSet(cfg.FlagPrefix, flag.ContinueOnError),
envNames: map[string]struct{}{},
flagNames: map[string]struct{}{},
}
}
type parsedField struct {
name string
namefull string
value any
defaultValue any
parent *parsedField
childs map[string]any
tags map[string]string
hasChilds bool
isRequired bool
}
func (pf *parsedField) String() string {
if pf == nil {
return "<nil-pf>"
}
return fmt.Sprintf("%+v", *pf)
}
func (sp *structParser) newParseField(parent *parsedField, field reflect.StructField) (*parsedField, error) {
requiredTag := field.Tag.Get("required")
if requiredTag != "" && requiredTag != "true" {
panic(fmt.Sprintf("aconfig: value for 'required' tag can be only 'true' got: %q", requiredTag))
}
name := field.Tag.Get("name")
if name == "" {
name = field.Name
}
newName := strings.ToLower(strings.Join(splitNameByWords(name), "_"))
env := field.Tag.Get("env")
if env == "" {
env = strings.ToUpper(newName)
}
flag := field.Tag.Get("flag")
if flag == "" {
flag = newName
}
var parentName, parentEnv, parentFlag string
if parent != nil {
parentName = parent.namefull + "|"
for p := parent; p != nil; p = p.parent {
parentEnv = p.tags["env_name"]
if parentEnv != "-" {
break
}
}
for p := parent; p != nil; p = p.parent {
parentFlag = p.tags["flag_name"]
if parentFlag != "-" {
break
}
}
parentEnv += sp.cfg.envDelimiter
parentFlag += sp.cfg.FlagDelimiter
}
pfield := &parsedField{
name: name,
namefull: parentName + name,
parent: parent,
tags: map[string]string{
"usage": field.Tag.Get("usage"),
"env_name": env,
"env_full": sp.cfg.EnvPrefix + parentEnv + env,
"flag_name": flag,
"flag_full": sp.cfg.FlagPrefix + parentFlag + flag,
},
isRequired: requiredTag == "true",
}
if !sp.cfg.SkipDefaults {
// TODO: must be typed?
pfield.defaultValue = field.Tag.Get("default")
}
if env == "-" {
delete(pfield.tags, "env_full")
}
if flag == "-" {
delete(pfield.tags, "flag_full")
}
if exactName, _, ok := strings.Cut(env, ",exact"); ok {
pfield.tags["env_full"] = exactName
}
if exactName, _, ok := strings.Cut(flag, ",exact"); ok {
pfield.tags["flag_full"] = exactName
}
if !sp.cfg.AllowDuplicates {
name := pfield.tags["env_full"]
if _, ok := sp.envNames[name]; ok && name != "" {
return nil, fmt.Errorf("field %q is duplicated", name)
}
sp.envNames[name] = struct{}{}
}
if !sp.cfg.SkipFlags {
flagName := pfield.tags["flag_full"]
if flagName != "" {
if _, ok := sp.flagNames[flagName]; ok && !sp.cfg.AllowDuplicates {
return nil, fmt.Errorf("duplicate flag %q", flagName)
}
sp.flagNames[flagName] = struct{}{}
// TODO: must be typed
sp.flagSet.String(flagName, field.Tag.Get("default"), field.Tag.Get("usage"))
}
}
if sp.cfg.DontGenerateTags {
newName = name
}
for _, dec := range sp.cfg.FileDecoders {
format := dec.Format()
v := field.Tag.Get(format)
if v == "" {
v = newName
}
pfield.tags[format] = v
}
return pfield, nil
}
func (sp *structParser) parseStruct(x any) error {
value := reflect.ValueOf(x)
if value.Type().Kind() == reflect.Ptr {
value = value.Elem()
}
fields, err := sp.parseStructHelper(nil, value, map[string]any{})
if err != nil {
return err
}
sp.fields = fields
// fmt.Printf("fields: %+v\n", fields)
return nil
}
func (sp *structParser) parseStructHelper(parent *parsedField, structValue reflect.Value, res map[string]any) (map[string]any, error) {
count := structValue.NumField()
structType := structValue.Type()
for i := 0; i < count; i++ {
field := structType.Field(i)
fieldValue := structValue.Field(i)
fieldType := fieldValue.Type()
if !fieldValue.CanSet() {
continue
}
defaultTagValue := field.Tag.Get("default")
pfield, err := sp.newParseField(parent, field)
if err != nil {
return nil, err
}
// do not set defaultValue for struct or pointer type without a default value
// if fieldType.Kind() == reflect.Struct ||
// (fieldType.Kind() == reflect.Pointer && defaultTagValue == "") {
// pfield.defaultValue = nil
// }
if fieldType.Kind() == reflect.Pointer {
fieldValue = fieldValue.Elem()
fieldValue = reflect.New(fieldType)
fieldType = fieldValue.Type()
}
value := fieldValue.Interface() // to have 'value' of type field
// if !sp.cfg.SkipDefaults {
// pv := fieldValue.Addr().Interface()
// if v, ok := pv.(encoding.TextUnmarshaler); ok {
// value = defaultTagValue
// err := v.UnmarshalText([]byte(fmt.Sprint(value)))
// if err != nil {
// return nil, err
// }
// }
// pfield.value =
// res[pfield.name] = pfield
// continue
// }
switch fieldType.Kind() {
// case reflect.Array:
// TODO: same as slice + check len?
case reflect.Interface:
// TODO: just assign?
case reflect.Struct:
pfield.hasChilds = true
param := map[string]any{}
parent := pfield
if field.Anonymous {
pfield.hasChilds = false
param = res
parent = pfield.parent
}
values, err := sp.parseStructHelper(parent, fieldValue, param)
if err != nil {
return nil, err
}
// fmt.Printf("field: %+v got: %+v\n\n", pfield.name, values)
value = values
case reflect.Slice, reflect.Array:
if isPrimitive(field.Type.Elem()) {
// byte-slice case
if field.Type.Elem().Kind() == reflect.Uint8 {
value = []byte(defaultTagValue)
} else {
values := []any{}
if defaultTagValue != "" && !strings.Contains(defaultTagValue, ",") {
return nil, fmt.Errorf("incorrect default tag value for slice/array: %v", defaultTagValue)
}
for _, val := range strings.Split(defaultTagValue, ",") {
values = append(values, val)
}
value = values
}
} else {
pfield.hasChilds = true
// TODO: if value is struct - parse
// value = parseSlice(fieldValue, map[string]any{})
}
// if !sp.cfg.SkipDefaults {
// pfield.value = value
// }
case reflect.Map:
// if isPrimitive(field.Type.Elem()) {
values := map[string]any{}
parts := strings.Split(defaultTagValue, ",")
if defaultTagValue != "" && !strings.Contains(defaultTagValue, ",") {
return nil, fmt.Errorf("incorrect default tag value for map: %v", defaultTagValue)
}
if len(parts) > 1 {
for _, entry := range parts {
// fmt.Printf("parts: %+v\n", parts)
entries := strings.SplitN(entry, ":", 2)
if len(entries) != 2 {
return nil, fmt.Errorf("want 2 parts got %d (%s)", len(entries), entries)
}
// TODO: convert entry[1] to a primitive?
values[entries[0]] = entries[1]
}
}
value = values
// } else {
// pfield.hasChilds = true
// }
default:
// TODO: do not set pointer
if fieldType.Kind() == reflect.Pointer && defaultTagValue == "" {
// skip
value = nil
} else {
// TODO: when WeaklyTypedInput will be false use decodePrimitive(...)
if !sp.cfg.SkipDefaults {
value = defaultTagValue
if fieldType == reflect.TypeOf(time.Second) {
val, err := time.ParseDuration(defaultTagValue)
if err != nil {
return nil, err
}
value = val
}
}
}
}
// we should not overwrite struct because there are childs
if sp.cfg.SkipDefaults && fieldType.Kind() != reflect.Struct {
pfield.value = fieldValue.Interface()
} else {
pfield.value = value
}
// fmt.Printf("def: %v %T '%+v'\n", fieldType.String(), value, value)
res[pfield.name] = pfield
}
return res, nil
}
var fieldType = reflect.TypeOf(&parsedField{})
var hook = mapstructure.DecodeHookFuncType(func(from, to reflect.Type, data any) (any, error) {
if from != fieldType {
// fmt.Printf("hook: got %T (%+v) when %s\n", i, i, to.String())
return data, nil
}
field := data.(*parsedField)
ifaceTo := reflect.New(to).Interface()
if unmarshaller, ok := ifaceTo.(encoding.TextUnmarshaler); ok {
// TODO: only string can be here?
b := []byte(field.value.(string))
err := unmarshaller.UnmarshalText(b)
return unmarshaller, err
}
// fmt.Printf("hook: when %s do '%+v' // %+v\n\n", to.String(), field.value, field)
return field.value, nil
})
func (sp *structParser) apply(x any) error {
dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Result: x,
DecodeHook: hook,
WeaklyTypedInput: true, // TODO: temp fix?
})
if err != nil {
panic(fmt.Sprintf("aconfig: BUG with mapstructure.NewDecoder: %v", err))
}
if err := dec.Decode(sp.fields); err != nil {
return fmt.Errorf("decode: %w", err)
}
return nil
}
func (sp *structParser) applyLevel(tag string, values map[string]any) error {
if err := sp.applyLevelHelper2(sp.fields, tag, values); err != nil {
return err
}
if !sp.cfg.AllowUnknownFields {
for env, value := range values {
return fmt.Errorf("unknown field in file %q: %s=%v (see AllowUnknownFields config param)", "file", env, value)
}
}
return nil
}
func (sp *structParser) applyLevelHelper2(fields map[string]any, tag string, values map[string]any) error {
for _, field := range fields {
pfield, ok := field.(*parsedField)
if !ok {
fmt.Printf("wat in level %T (%+v)\n", field, field)
continue
}
tagValue, ok := pfield.tags[tag]
if !ok {
continue
}
value, ok := values[tagValue]
if !ok {
continue
}
switch value := value.(type) {
case map[string]any:
if pfield.hasChilds {
pfieldValue, ok := pfield.value.(map[string]any)
if !ok {
fmt.Printf("ouch %T (%+v)\n", pfield.value, pfield.value)
continue
}
err := sp.applyLevelHelper2(pfieldValue, tag, value)
if err != nil {
return err
}
} else {
pfield.value = value
}
default:
pfield.value = value
}
delete(values, tagValue)
}
return nil
}
func (sp *structParser) applyLevelHelper(fields map[string]any, tag string, values map[string]any) error {
for _, v := range fields {
field, ok := v.(*parsedField)
if !ok {
// fmt.Printf("got type %T (%v)\n", v, v)
continue
}
want := field.tags[tag]
value, ok := values[want]
if !ok {
continue
}
vval, ok := value.(map[string]any)
// TODO: can be only for leaf nodes?
if !ok {
// fmt.Printf("got val %T (%v)\n", val, val)
field.value = value
continue
}
// fmt.Printf("got map: %+v %T\n", vval, vval)
// no struct in childs - simple apply, mapstructure will take care
if field.childs == nil {
// TODO: reencode values?
field.value = vval
} else {
if err := sp.applyLevelHelper(field.childs, tag, vval); err != nil {
return err
}
}
}
return nil
}
func (sp *structParser) applyFlat(tag string, values map[string]any) error {
allowUnknown := true
prefix := ""
switch tag {
case "env":
allowUnknown, prefix = sp.cfg.AllowUnknownEnvs, sp.cfg.EnvPrefix
case "flag":
allowUnknown, prefix = sp.cfg.AllowUnknownFlags, sp.cfg.FlagPrefix
}
dupls := map[string]struct{}{}
if err := sp.applyFlatHelper(sp.fields, tag, values); err != nil {
return err
}
if allowUnknown || prefix == "" {
return nil
}
for name := range dupls {
delete(values, name)
}
for key, value := range values {
if strings.HasPrefix(key, prefix) {
return fmt.Errorf("unknown %s %s=%v (see AllowUnknownXXX config param)", tag, key, value)
}
}
return nil
}
func (sp *structParser) applyFlatHelper(fields map[string]any, tag string, values map[string]any) error {
for _, field := range fields {
pfield, ok := field.(*parsedField)
if !ok {
fmt.Printf("wat in flat %T (%+v)\n", field, field)
continue
}
tagValue, ok := pfield.tags[tag+"_full"]
if !ok {
continue
}
value, ok := values[tagValue]
if !ok {
if !pfield.hasChilds {
continue
}
if err := sp.applyFlatHelper(pfield.value.(map[string]any), tag, values); err != nil {
return err
}
continue
}
pfield.value = value
if !sp.cfg.AllowDuplicates {
delete(values, tagValue)
}
}
return nil
}
func isPrimitive(v reflect.Type) bool {
return v.Kind() < reflect.Array || v.Kind() == reflect.String
}