-
Notifications
You must be signed in to change notification settings - Fork 0
/
gofig.go
407 lines (337 loc) · 9.56 KB
/
gofig.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
package gofig
import (
"errors"
"fmt"
"os"
"reflect"
"strconv"
"strings"
)
const (
TypeBool GfType = 0
TypeInt GfType = 1
TypeFloat GfType = 2
TypeString GfType = 3
numTypes GfType = 4
)
var typeNames = []string{
"bool",
"int",
"float",
"string",
}
type GfType int
type Id struct {
valid bool
t GfType // the GfType num will correspond to the index in the Gofig.valsByType slice
valIdx int // the index of the value in the slice of the corresponding GfType
}
/*
valsByType has this structure:
[
[]bool,
[]int,
[]float64,
[]string,
]
*/
type Gofig struct {
initialized bool
valsByType [numTypes]any // slice of slices corresponding to the different types the config options could be.
}
type InitOpt struct {
Name string // The name of the config option (e.g. "ENV_VAR_A")
Description string // A description of the config option
Type GfType // The type of the config option (e.g. TypeBool, TypeInt, TypeFloat, TypeString)
Required bool // Whether the config option is required
Default any // The default value of the config option. Doesn't do anything if the config option is required.
IdPtr *Id // Pointer to the Id of the config option. This is where you store the Id. The Id value be set after the call to Init.
}
/*
**********************
+-----------------+
|Error Definitions|
+-----------------+
**********************
*/
var ErrNoInputOpts = errors.New("no initOpts provided. must provice initOpts to initialize a Gofig object")
var ErrInvalidId = errors.New("invalid id")
var ErrNotInitialized = errors.New("Gofig not initialized. Call Init() first")
var ErrDefaultValueIsWrongTypeWhenNotRequired = func(initOpt InitOpt) error {
return fmt.Errorf(
"config: `%v`. type: `%v`. default value of `%v` is not of type `%v`",
initOpt.Name,
typeNames[initOpt.Type],
initOpt.Default,
typeNames[initOpt.Type],
)
}
var ErrRequiredConfigNotSet = func(name string) error {
return fmt.Errorf("required config option %s not set", name)
}
var ErrDefaultNotNilWhenRequired = func(initOpt InitOpt) error {
return fmt.Errorf("config: `%v`. required: true. default value: `%v`. default value must be nil when config is required", initOpt.Name, initOpt.Default)
}
var ErrDefaultIsNilWhenNotRequired = func(initOpt InitOpt) error {
return fmt.Errorf("config: `%v`. required: false. default value: `nil`. default value must not be nil when config is not required", initOpt.Name)
}
var ErrWrongTypeSetInEnvironment = func(initOpt InitOpt, valFromEnviron string) error {
return fmt.Errorf("config `%s` of type `%s` was not set as `%s` in environment. environment value: `%s`", initOpt.Name, typeNames[initOpt.Type], typeNames[initOpt.Type], valFromEnviron)
}
/**********************
+-----------------+
|Private functions|
+-----------------+
***********************/
func isDefaultTypeCorrect(initOpt InitOpt) bool {
var GfTypeMapReflectionKind = map[GfType]reflect.Kind{
TypeBool: reflect.Bool,
TypeInt: reflect.Int,
TypeFloat: reflect.Float64,
TypeString: reflect.String,
}
if !initOpt.Required {
defaultValKind := reflect.TypeOf(initOpt.Default).Kind()
if defaultValKind != GfTypeMapReflectionKind[initOpt.Type] {
return false
}
}
return true
}
func validateCommonGetInputs(gfInitializd bool, id Id) error {
if !gfInitializd {
return ErrNotInitialized
}
if !id.valid {
return ErrInvalidId
}
if id.t < 0 || id.t >= numTypes {
return ErrInvalidId
}
if id.valIdx < 0 {
return ErrInvalidId
}
return nil
}
/***********************
+---------------+
| Public API |
+---------------+
***********************/
/*
DocString returns a string that contains the documentation for the config options passed in.
*/
func DocString(initOpts []InitOpt) (string, error) {
if len(initOpts) == 0 {
return "", ErrNoInputOpts
}
var docs string
for _, initOpt := range initOpts {
docs += fmt.Sprintf(
"%s\n\tDescription: %s\n\tType: %s\n\tRequired: %v\n",
initOpt.Name,
initOpt.Description,
typeNames[initOpt.Type],
initOpt.Required,
)
if !initOpt.Required {
docs += fmt.Sprintf("\tDefault: %v\n", initOpt.Default)
}
}
return docs, nil
}
/*
Init initializes the Gofig object with the config options passed in.
If Gofig has already been initialized, Init will return an error.
*/
func Init(initOpts []InitOpt) (Gofig, error) {
gf := Gofig{}
var valsBool []bool
var valsInt []int
var valsFloat []float64
var valsString []string
if len(initOpts) == 0 {
return gf, ErrNoInputOpts
}
for _, initOpt := range initOpts {
if initOpt.Required && initOpt.Default != nil {
return gf, ErrDefaultNotNilWhenRequired(initOpt)
}
if !initOpt.Required && initOpt.Default == nil {
return gf, ErrDefaultIsNilWhenNotRequired(initOpt)
}
initOpt.IdPtr.t = initOpt.Type
switch initOpt.Type {
case TypeBool:
if ok := isDefaultTypeCorrect(initOpt); !ok {
return gf, ErrDefaultValueIsWrongTypeWhenNotRequired(initOpt)
}
var val bool
if !initOpt.Required {
val = initOpt.Default.(bool)
}
valStr, exists := os.LookupEnv(initOpt.Name)
if !exists && initOpt.Required {
return gf, ErrRequiredConfigNotSet(initOpt.Name)
}
valConv := strings.ToUpper(valStr) == "TRUE"
if valConv != val {
val = valConv
}
initOpt.IdPtr.valIdx = len(valsBool)
valsBool = append(valsBool, val)
case TypeInt:
if ok := isDefaultTypeCorrect(initOpt); !ok {
return gf, ErrDefaultValueIsWrongTypeWhenNotRequired(initOpt)
}
var val int
if !initOpt.Required {
val = initOpt.Default.(int)
}
valStr, exists := os.LookupEnv(initOpt.Name)
if !exists && initOpt.Required {
return gf, ErrRequiredConfigNotSet(initOpt.Name)
}
valConv, err := strconv.Atoi(valStr)
if err != nil {
return gf, ErrWrongTypeSetInEnvironment(initOpt, valStr)
}
if valConv != val {
val = valConv
}
initOpt.IdPtr.valIdx = len(valsInt)
valsInt = append(valsInt, val)
case TypeFloat:
if ok := isDefaultTypeCorrect(initOpt); !ok {
return gf, ErrDefaultValueIsWrongTypeWhenNotRequired(initOpt)
}
var val float64
if !initOpt.Required {
val = initOpt.Default.(float64)
}
valStr, exists := os.LookupEnv(initOpt.Name)
if !exists && initOpt.Required {
return gf, ErrRequiredConfigNotSet(initOpt.Name)
}
valConv, err := strconv.ParseFloat(valStr, 64)
if err != nil {
return gf, ErrWrongTypeSetInEnvironment(initOpt, valStr)
}
if valConv != val {
val = valConv
}
initOpt.IdPtr.valIdx = len(valsFloat)
valsFloat = append(valsFloat, val)
case TypeString:
if ok := isDefaultTypeCorrect(initOpt); !ok {
return gf, ErrDefaultValueIsWrongTypeWhenNotRequired(initOpt)
}
var val string
if !initOpt.Required {
val = initOpt.Default.(string)
}
valStr, exists := os.LookupEnv(initOpt.Name)
if !exists && initOpt.Required {
return gf, ErrRequiredConfigNotSet(initOpt.Name)
}
if valStr != val {
val = valStr
}
initOpt.IdPtr.valIdx = len(valsString)
valsString = append(valsString, val)
}
}
gf.valsByType[TypeBool] = valsBool
gf.valsByType[TypeInt] = valsInt
gf.valsByType[TypeFloat] = valsFloat
gf.valsByType[TypeString] = valsString
for _, opt := range initOpts {
opt.IdPtr.valid = true
}
gf.initialized = true
return gf, nil
}
/*
Get returns the value of the config option corresponding to the Id passed in.
If the Id is invalid, Get will return an error.
If Gofig has not been initialized, Get will return an error.
*/
func (gf *Gofig) Get(id Id) (any, error) {
if !gf.initialized {
return nil, ErrNotInitialized
}
if !id.valid {
return nil, ErrInvalidId
}
if id.t < 0 || id.t >= numTypes {
return nil, ErrInvalidId
}
if id.valIdx < 0 {
return nil, ErrInvalidId
}
switch id.t {
case TypeBool:
if id.valIdx >= len(gf.valsByType[id.t].([]bool)) {
return nil, ErrInvalidId
}
return gf.valsByType[id.t].([]bool)[id.valIdx], nil
case TypeInt:
if id.valIdx >= len(gf.valsByType[id.t].([]int)) {
return nil, ErrInvalidId
}
return gf.valsByType[id.t].([]int)[id.valIdx], nil
case TypeFloat:
if id.valIdx >= len(gf.valsByType[id.t].([]float64)) {
return nil, ErrInvalidId
}
return gf.valsByType[id.t].([]float64)[id.valIdx], nil
case TypeString:
if id.valIdx >= len(gf.valsByType[id.t].([]string)) {
return nil, ErrInvalidId
}
return gf.valsByType[id.t].([]string)[id.valIdx], nil
}
// if somehow we get here, just return not valid id
return nil, ErrInvalidId
}
// More Get-family functions for bool, int, float64, and string
func (gf *Gofig) GetBool(id Id) (bool, error) {
err := validateCommonGetInputs(gf.initialized, id)
if err != nil {
return false, err
}
if id.valIdx >= len(gf.valsByType[id.t].([]bool)) {
return false, ErrInvalidId
}
return gf.valsByType[id.t].([]bool)[id.valIdx], nil
}
func (gf *Gofig) GetInt(id Id) (int, error) {
err := validateCommonGetInputs(gf.initialized, id)
if err != nil {
return 0, err
}
if id.valIdx >= len(gf.valsByType[id.t].([]int)) {
return 0, ErrInvalidId
}
return gf.valsByType[id.t].([]int)[id.valIdx], nil
}
func (gf *Gofig) GetFloat(id Id) (float64, error) {
err := validateCommonGetInputs(gf.initialized, id)
if err != nil {
return 0, err
}
if id.valIdx >= len(gf.valsByType[id.t].([]float64)) {
return 0.0, ErrInvalidId
}
return gf.valsByType[id.t].([]float64)[id.valIdx], nil
}
func (gf *Gofig) GetString(id Id) (string, error) {
err := validateCommonGetInputs(gf.initialized, id)
if err != nil {
return "", err
}
if id.valIdx >= len(gf.valsByType[id.t].([]string)) {
return "", ErrInvalidId
}
return gf.valsByType[id.t].([]string)[id.valIdx], nil
}