forked from Rheisen/bconf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
field.go
492 lines (389 loc) · 10.8 KB
/
field.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
package bconf
import (
"fmt"
"reflect"
"strconv"
"strings"
"time"
"github.com/rheisen/bconf/bconfconst"
)
// Fields is a slice of Field elements providing context for configuration values
type Fields []*Field
// Field is a data structure that provides context for a configuration value
type Field struct {
// fieldValue contains a mapping of loader names to field value
fieldValue map[string]any
// Validator defines a function that runs during validation to check a value against validity constraints
Validator func(value any) error
// DefaultGenerator defines a function that creates a base value for a field
DefaultGenerator func() (any, error)
// Default defines a base value for a field
Default any
// generatedDefault tracks the value generated from the default generator function
generatedDefault any
// overrideValue tracks a user set field value
overrideValue any
// Key is a required field that defines the field lookup value
Key string
// Type is a required field that defines the type of value the field contains
Type string
// Description defines a summary of the field contents
Description string
// Enumeration defines a list of acceptable inputs for the field value
Enumeration []any
// LoadConditions defines the conditions required for a field to load values
LoadConditions LoadConditions
// fieldFound is a reverse priority list of where field values were found, e.g. last value has highest priority
fieldFound []string
// Required defines whether a field value must be set in order for the field to be valid
Required bool
// Sensitive identifies the field value as sensitive
Sensitive bool
}
func (f *Field) Clone() *Field {
clone := *f
clone.fieldFound = make([]string, len(f.fieldFound))
copy(clone.fieldFound, f.fieldFound)
clone.Enumeration = make([]any, len(f.Enumeration))
copy(clone.Enumeration, f.Enumeration)
if len(f.fieldValue) > 0 {
clone.fieldValue = make(map[string]any, len(f.fieldValue))
for key, value := range f.fieldValue {
clone.fieldValue[key] = value
}
}
if len(f.LoadConditions) > 0 {
clone.LoadConditions = make(LoadConditions, len(f.LoadConditions))
for idx, value := range f.LoadConditions {
clone.LoadConditions[idx] = value.Clone()
}
}
return &clone
}
func (f *Field) generateDefault() error {
if f.DefaultGenerator == nil {
return nil
}
generatedDefault, err := f.DefaultGenerator()
if err != nil {
return fmt.Errorf("problem generating default field value: %w", err)
}
f.generatedDefault = generatedDefault
return nil
}
func (f *Field) validate() []error {
errs := []error{}
if f.Key == "" {
errs = append(errs, fmt.Errorf("invalid key value: cannot be blank"))
}
if f.Type == "" {
errs = append(errs, fmt.Errorf("invalid field-type value: cannot be blank"))
}
if len(errs) > 0 {
return errs
}
fieldTypeFound := false
for _, fieldType := range FieldTypes() {
if fieldType != f.Type {
continue
}
fieldTypeFound = true
if fieldErrors := f.validateNoConflictingParams(); len(fieldErrors) > 0 {
errs = append(errs, fieldErrors...)
}
if err := f.validateDefaultFieldType(fieldType); err != nil {
errs = append(errs, err)
}
if err := f.validateGeneratedDefaultFieldType(fieldType); err != nil {
errs = append(errs, err)
}
if validationErrs := f.validateEnumerationValuesFieldType(fieldType); len(validationErrs) > 0 {
errs = append(errs, validationErrs...)
}
// Return here before validating default values existing in enumeration list
if len(errs) > 0 {
return errs
}
if err := f.validateDefaultValuesInEnumeration(); err != nil {
errs = append(errs, err)
}
if err := f.validateDefaultValuesPassValidatorFunc(); err != nil {
errs = append(errs, err)
}
}
if !fieldTypeFound {
errs = append(errs, fmt.Errorf("invalid field type specified: '%s'", f.Type))
}
return errs
}
func (f *Field) validateNoConflictingParams() []error {
errs := []error{}
if f.Default != nil && f.DefaultGenerator != nil {
errs = append(errs, fmt.Errorf(bconfconst.ErrorFieldDefaultSetting))
}
if f.Required && f.Default != nil || f.Required && f.DefaultGenerator != nil {
errs = append(errs, fmt.Errorf(bconfconst.ErrorFieldRequiredWithDefault))
}
return errs
}
func (f *Field) validateDefaultFieldType(fieldType string) error {
if f.Default == nil {
return nil
}
if reflect.TypeOf(f.Default).String() == fieldType {
return nil
}
return fmt.Errorf(
"invalid default type: expected '%s', found '%s'",
fieldType,
reflect.TypeOf(f.Default).String(),
)
}
func (f *Field) validateGeneratedDefaultFieldType(fieldType string) error {
if f.generatedDefault == nil {
return nil
}
if reflect.TypeOf(f.generatedDefault).String() == fieldType {
return nil
}
return fmt.Errorf(
"invalid generated default type: expected '%s', found '%s'",
fieldType,
reflect.TypeOf(f.generatedDefault).String(),
)
}
func (f *Field) validateEnumerationValuesFieldType(fieldType string) []error {
if f.Enumeration == nil || len(f.Enumeration) < 1 {
return nil
}
errs := []error{}
for _, val := range f.Enumeration {
if reflect.TypeOf(val).String() == fieldType {
continue
}
errs = append(
errs,
fmt.Errorf(
"invalid enumeration value type: expected '%s', found '%s'",
fieldType,
reflect.TypeOf(val).String(),
),
)
}
return errs
}
func (f *Field) validateDefaultValuesInEnumeration() error {
if f.Default != nil && !f.valueInEnumeration(f.Default) {
return fmt.Errorf(
"invalid default value: default value '%s' expected in enumeration list",
f.Default,
)
}
if f.generatedDefault != nil && !f.valueInEnumeration(f.generatedDefault) {
return fmt.Errorf(
"invalid generated default value: default value '%s' expected in enumeration list",
f.Default,
)
}
return nil
}
func (f *Field) validateDefaultValuesPassValidatorFunc() error {
if f.Default != nil && f.Validator != nil {
if err := f.Validator(f.Default); err != nil {
return fmt.Errorf(
"invalid default value: error from field validator: %w",
err,
)
}
}
if f.generatedDefault != nil && f.Validator != nil {
if err := f.Validator(f.generatedDefault); err != nil {
return fmt.Errorf(
"invalid generated default value: error from field validator: %w",
err,
)
}
}
return nil
}
func (f *Field) getValue() (any, error) {
if f.overrideValue != nil {
return f.overrideValue, nil
}
if f.fieldFound != nil && len(f.fieldFound) > 0 {
value := f.fieldValue[f.fieldFound[len(f.fieldFound)-1]]
return value, nil
}
if f.Default != nil {
return f.Default, nil
}
if f.generatedDefault != nil {
return f.generatedDefault, nil
}
return nil, fmt.Errorf("empty field value")
}
// func (f *Field) getValueFrom(loader string) (any, error) {
// if f.fieldValue == nil {
// return nil, fmt.Errorf("")
// }
// value, found := f.fieldValue[loader]
// if !found {
// return nil, fmt.Errorf("")
// }
// return value, nil
// }
func (f *Field) set(loaderName, value string) error {
parsedValue, err := f.parseString(value)
if err != nil {
return fmt.Errorf("problem parsing value to field-type: %w", err)
}
if !f.valueInEnumeration(parsedValue) {
return fmt.Errorf("value not found in enumeration list")
}
if f.Validator != nil {
if err := f.Validator(parsedValue); err != nil {
return fmt.Errorf("value validation error: %w", err)
}
}
if f.fieldValue == nil {
f.fieldValue = map[string]any{loaderName: parsedValue}
} else {
f.fieldValue[loaderName] = value
}
if f.fieldFound == nil {
f.fieldFound = []string{loaderName}
} else {
f.fieldFound = append(f.fieldFound, loaderName)
}
return nil
}
func (f *Field) setOverride(value any) error {
if reflect.TypeOf(value).String() != f.Type {
return fmt.Errorf(
"invalid value field-type: expected '%s', found '%s'",
f.Type,
reflect.TypeOf(value).String(),
)
}
if !f.valueInEnumeration(value) {
return fmt.Errorf("value not found in enumeration list")
}
if f.Validator != nil {
if err := f.Validator(value); err != nil {
return fmt.Errorf("value validation error: %w", err)
}
}
f.overrideValue = value
return nil
}
func (f *Field) parseString(value string) (any, error) {
switch f.Type {
case String:
return value, nil
case Strings:
return f.parseToStrings(value), nil
case Bool:
return strconv.ParseBool(value)
case Bools:
return f.parseToBools(value)
case Int:
return strconv.Atoi(value)
case Ints:
return f.parseToInts(value)
case Time:
return time.Parse(time.RFC3339, value)
case Times:
return f.parseToTimes(value)
case Duration:
return time.ParseDuration(value)
case Durations:
return f.parseToDurations(value)
default:
return "", fmt.Errorf("unsupported field type: %s", f.Type)
}
}
func (f *Field) parseToStrings(value string) []string {
if value == "" {
return []string{}
}
list := strings.Split(value, ",")
values := make([]string, len(list))
for idx, elem := range list {
parsedValue := strings.Trim(elem, " ")
values[idx] = parsedValue
}
return values
}
func (f *Field) parseToBools(value string) ([]bool, error) {
list := strings.Split(value, ",")
values := make([]bool, len(list))
for idx, elem := range list {
parsedValue, err := strconv.ParseBool(strings.Trim(elem, " "))
if err != nil {
return nil, err
}
values[idx] = parsedValue
}
return values, nil
}
func (f *Field) parseToInts(value string) ([]int, error) {
list := strings.Split(value, ",")
values := make([]int, len(list))
for idx, elem := range list {
parsedValue, err := strconv.Atoi(strings.Trim(elem, " "))
if err != nil {
return nil, err
}
values[idx] = parsedValue
}
return values, nil
}
func (f *Field) parseToTimes(value string) ([]time.Time, error) {
list := strings.Split(value, ",")
values := make([]time.Time, len(list))
for idx, elem := range list {
parsedValue, err := time.Parse(time.RFC3339, strings.Trim(elem, " "))
if err != nil {
return nil, err
}
values[idx] = parsedValue
}
return values, nil
}
func (f *Field) parseToDurations(value string) ([]time.Duration, error) {
list := strings.Split(value, ",")
values := make([]time.Duration, len(list))
for idx, elem := range list {
parsedValue, err := time.ParseDuration(strings.Trim(elem, " "))
if err != nil {
return nil, err
}
values[idx] = parsedValue
}
return values, nil
}
func (f *Field) valueInEnumeration(value any) bool {
if len(f.Enumeration) < 1 {
return true
}
for _, acceptedValue := range f.Enumeration {
if value == acceptedValue {
return true
}
}
return false
}
func (f *Field) enumerationString() string {
builder := strings.Builder{}
if len(f.Enumeration) > 0 {
builder.WriteString("[")
for index, value := range f.Enumeration {
if index != 0 {
builder.WriteString(", ")
}
builder.WriteString(fmt.Sprintf("'%s'", value))
}
builder.WriteString("]")
}
return builder.String()
}