-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
560 lines (500 loc) · 12.5 KB
/
main.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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
package easyconfig
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"github.com/BurntSushi/toml"
"github.com/fatih/color"
"github.com/iancoleman/strcase"
"github.com/joho/godotenv"
"gopkg.in/yaml.v2"
"olympos.io/encoding/edn"
)
type (
Loader struct {
Sources []Source
HelpMSG string
DisableHelpMsg bool
}
errCollector []error
Source interface {
Load(structPtr interface{}) error
}
// FileSource satisifies the loader interface. It loads the
// configuration from the given file.
FileSource struct {
Path string
}
// FileSource loads configuration from the given .json file.
JSONSource struct {
Path string
}
// YAMLSource loads configuration from the given .yaml or .yml file.
YAMLSource struct {
Path string
}
// TOMLSource loads configuration from the given .toml file.
TOMLSource struct {
Path string
}
// EDNSource loads configuration from the given .edn file.
EDNSource struct {
Path string
}
// DirSource loads configuration from kubernetes ConfigMap and Secret mountPath directory
DirSource struct {
Path string
}
// EnvFileSource loads configuration from the given .env file.
EnvFileSource struct {
Prefix string
Path string
}
// EnvSource loads configuration from environment variables
EnvSource struct {
Prefix string
}
// FlagsSource loads configuration from flags
FlagsSource struct {
}
strErr string
)
var (
Acronims = []string{"API", "SMTP", "PostgreSQL", "SQL", "JSON", "YAML", "DB", "AI", "CRM", "HTTPS", "HTTP", "FTP", "SSH"}
bold = color.New(color.Bold)
)
func (e strErr) Error() string {
return string(e)
}
const (
ErrIsDirectory strErr = "file is a directory"
ErrUnknownFileType strErr = "unknown file type"
)
func (c *errCollector) Collect(e error) {
if e != nil {
*c = append(*c, e)
}
}
func (c *errCollector) Error() (err error) {
if len(*c) == 0 {
return nil
}
ret := ""
for _, e := range *c {
ret += fmt.Sprintf("%s\n", e.Error())
}
return errors.New(ret)
}
func NewLoader(sources []Source, helpMessage ...string) *Loader {
for _, acron := range Acronims {
strcase.ConfigureAcronym(acron, strings.ToLower(acron))
}
msg := fmt.Sprintf("\nUsage:\n %s [arguments]", filepath.Base(os.Args[0]))
if len(helpMessage) > 0 {
msg = strings.Join(helpMessage, "\n")
}
return &Loader{
Sources: sources,
HelpMSG: msg,
DisableHelpMsg: len(msg) == 0,
}
}
// Load configuration
func (l Loader) Load(structPtr interface{}) error {
if !l.DisableHelpMsg && len(os.Args) == 2 && strings.HasSuffix(strings.ToLower(strings.Split(os.Args[1], "=")[0]), "help") {
l.Help(structPtr)
os.Exit(0)
}
errs := new(errCollector)
for _, src := range l.Sources {
errs.Collect(src.Load(structPtr))
}
return errs.Error()
}
// Load configuration
func (l Loader) Help(structPtr interface{}) {
structElem := reflect.ValueOf(structPtr).Elem()
tags := []string{}
fromEnv := false
fromFlag := false
fromDir := false
prefix := ""
for _, source := range l.Sources {
if t, ok := source.(EnvFileSource); ok {
fromEnv = true
prefix = t.Prefix
}
if t, ok := source.(EnvSource); ok {
fromEnv = true
prefix = t.Prefix
}
if t, ok := source.(*EnvFileSource); ok {
fromEnv = true
prefix = t.Prefix
}
if t, ok := source.(*EnvSource); ok {
prefix = t.Prefix
fromEnv = true
}
if _, ok := source.(FlagsSource); ok {
fromFlag = true
}
if _, ok := source.(*FlagsSource); ok {
fromFlag = true
}
if _, ok := source.(DirSource); ok {
fromDir = true
}
if _, ok := source.(*DirSource); ok {
fromDir = true
}
if _, ok := source.(FileSource); ok {
fromDir = true
}
if _, ok := source.(*FileSource); ok {
fromDir = true
}
}
if fromFlag {
tags = append(tags, "flag")
}
if fromEnv {
tags = append(tags, "env")
}
if fromDir {
tags = append(tags, "dir")
}
fmt.Println(l.HelpMSG)
for _, tag := range tags {
switch tag {
case "flag":
fmt.Printf("\nThe commands are:\n\n")
case "dir":
fmt.Printf("\nConfiguration directory files to use:\n\n")
default:
fmt.Printf("\nEnvironment variables to use:\n\n")
}
for i := 0; i < structElem.NumField(); i++ {
field := structElem.Type().Field(i)
elem := structElem.Field(i).Interface()
tagVal := field.Tag.Get(tag)
if tagVal == "-" {
continue
}
fieldName, _ := convertName(field.Name, tag, tagVal, prefix)
bold.Printf(" %s\n", fieldName)
if tag == "flag" {
printed := false
switch v := elem.(type) {
case string:
if v != "" {
printed = true
fmt.Printf(" Set value of %s. Default: %q\n", field.Name, v)
}
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64:
if v != 0 {
printed = true
fmt.Printf(" Set number value of %s. Default: %v\n", field.Name, elem)
}
case bool:
printed = true
fmt.Printf(" Set value of %s. Default: %v\n", field.Name, elem)
}
if !printed {
fmt.Printf(" Set value of %s\n", field.Name)
}
}
}
}
}
// Load config from file
func (s FileSource) Load(structPtr interface{}) error {
if info, err := os.Stat(s.Path); err != nil {
return err
} else {
if info.IsDir() {
return (&DirSource{Path: s.Path}).Load(structPtr)
}
ext := filepath.Ext(s.Path)
switch ext {
case ".json":
return (&JSONSource{Path: s.Path}).Load(structPtr)
case ".yaml", ".yml":
return (&YAMLSource{Path: s.Path}).Load(structPtr)
case ".env":
return (&EnvFileSource{Path: s.Path}).Load(structPtr)
case ".toml":
return (&TOMLSource{Path: s.Path}).Load(structPtr)
case ".edn":
return (&EDNSource{Path: s.Path}).Load(structPtr)
default:
if err := (&JSONSource{Path: s.Path}).Load(structPtr); err == nil {
return nil
}
if err := (&YAMLSource{Path: s.Path}).Load(structPtr); err == nil {
return nil
}
if err := (&EnvFileSource{Path: s.Path}).Load(structPtr); err == nil {
return nil
}
if err := (&TOMLSource{Path: s.Path}).Load(structPtr); err == nil {
return nil
}
return ErrUnknownFileType
}
}
}
// Load JSON configuration file
func (s JSONSource) Load(structPtr interface{}) error {
file, err := getFile(s.Path)
if err != nil {
return err
}
defer file.Close()
return json.NewDecoder(file).Decode(structPtr)
}
// Load YAML configuration file
func (s YAMLSource) Load(structPtr interface{}) error {
file, err := getFile(s.Path)
if err != nil {
return err
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
return err
}
return yaml.Unmarshal(data, structPtr)
}
// Load TOML configuration file
func (s TOMLSource) Load(structPtr interface{}) error {
file, err := getFile(s.Path)
if err != nil {
return err
}
defer file.Close()
_, err = toml.DecodeReader(file, structPtr)
return err
}
// Load EDN configuration file
func (s EDNSource) Load(structPtr interface{}) error {
file, err := getFile(s.Path)
if err != nil {
return err
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
return err
}
return edn.Unmarshal(data, structPtr)
}
// Load ENV configuration file
func (s EnvFileSource) Load(structPtr interface{}) error {
file, err := getFile(s.Path)
if err != nil {
return err
}
defer file.Close()
envMap, err := godotenv.Parse(file)
if err != nil {
return err
}
return map2struct("env", s.Prefix, envMap, structPtr)
}
// Load configuration from environment variables
func (s EnvSource) Load(structPtr interface{}) error {
envMap := map[string]string{}
for _, s := range os.Environ() {
if strings.Contains(s, "=") {
p := strings.SplitN(s, "=", 2)
envMap[p[0]] = p[1]
}
}
return map2struct("env", s.Prefix, envMap, structPtr)
}
// Load configuration from environment variables
func (s DirSource) Load(structPtr interface{}) error {
dirMap := map[string]string{}
files, err := ioutil.ReadDir(s.Path)
if err != nil {
return err
}
for _, file := range files {
if !file.IsDir() && file.Size() < 10485760 { // 10 Mb
data, err := ioutil.ReadFile(filepath.Join(s.Path, file.Name()))
if err != nil {
continue
}
dirMap[file.Name()] = string(data)
}
}
return map2struct("dir", "", dirMap, structPtr)
}
// Load configuration from the command-line.
func (s FlagsSource) Load(structPtr interface{}) error {
argsMap := map[string]string{}
prev := ""
for _, s := range os.Args[1:] {
if strings.HasPrefix(s, "-") {
prev = ""
if strings.Contains(s, "=") {
p := strings.SplitN(s, "=", 2)
argsMap[p[0]] = p[1]
} else {
prev = s
}
} else if prev != "" {
argsMap[prev] = s
}
}
return map2struct("flag", "", argsMap, structPtr)
}
func getFile(path string) (*os.File, error) {
pwd, err := os.Getwd()
if !filepath.IsAbs(path) && err == nil {
path = filepath.Join(pwd, path)
}
if _, err := os.Stat(path); err != nil {
return nil, err
}
return os.Open(path)
}
func map2struct(tag, prefix string, mp map[string]string, structPtr interface{}) error {
for key, value := range mp {
key = strings.TrimSpace(key)
if key != "" && value != "" {
if structPtr != nil {
setValue(tag, prefix, structPtr, key, value)
}
}
}
return nil
}
func setValue(tag, prefix string, structPtr interface{}, key string, value string) {
structElem := reflect.ValueOf(structPtr).Elem()
for i := 0; i < structElem.NumField(); i++ {
field := structElem.Type().Field(i)
tagVal := strings.TrimSpace(field.Tag.Get(tag))
if tagVal == "-" {
continue
}
fieldName, separator := convertName(field.Name, tag, tagVal, prefix)
if tag == "env" {
key = strings.ToUpper(key)
}
elemPtr := structElem.Field(i).Addr().Interface()
if fieldName == key {
switch field.Type.Kind() {
case reflect.Slice:
setSlice(elemPtr, value, separator)
default:
setField(elemPtr, value)
}
}
}
}
func convertName(name, tag, tagVal, prefix string) (fieldName, separator string) {
separator = ","
if tag == "env" {
separator = ":"
fieldName = strcase.ToScreamingSnake(name)
} else if tag == "dir" {
fieldName = strcase.ToKebab(name)
} else {
fieldName = name
for _, acron := range Acronims {
if strings.HasPrefix(fieldName, acron) {
fieldName = strings.Replace(fieldName, acron, strings.ToLower(acron), 1)
}
}
fieldName = "-" + strcase.ToLowerCamel(fieldName)
}
if strings.Contains(tagVal, ",") {
p := strings.SplitN(tagVal, ",", 2)
tagVal = p[0]
separator = p[1]
}
if tagVal != "" {
fieldName = tagVal
if tag == "flag" && strings.HasPrefix(fieldName, "-") {
fieldName = "-" + fieldName
}
}
if tag == "env" {
prefix = strings.TrimSpace(prefix)
if prefix != "" && !strings.HasSuffix(prefix, "_") && !strings.HasSuffix(prefix, "-") {
prefix += "_"
}
if prefix != "" && !strings.HasPrefix(fieldName, prefix) {
fieldName = prefix + fieldName
}
fieldName = strings.ToUpper(fieldName)
}
return fieldName, separator
}
func setSlice(slicePtr interface{}, value string, separator string) {
if separator == "" {
separator = ":"
}
slice := reflect.ValueOf(slicePtr).Elem()
for _, part := range strings.Split(value, separator) {
fieldPtr := reflect.New(slice.Type().Elem())
setField(fieldPtr.Interface(), part)
slice.Set(reflect.Append(slice, fieldPtr.Elem()))
}
}
func setField(fieldPtr interface{}, fieldValue string) {
field := reflect.ValueOf(fieldPtr).Elem()
if field.IsValid() && field.CanSet() {
switch field.Kind() {
case reflect.String:
field.SetString(fieldValue)
case reflect.Int:
r, _ := strconv.ParseInt(fieldValue, 10, 0)
field.SetInt(r)
case reflect.Int8:
r, _ := strconv.ParseInt(fieldValue, 10, 8)
field.SetInt(r)
case reflect.Int16:
r, _ := strconv.ParseInt(fieldValue, 10, 16)
field.SetInt(r)
case reflect.Int32:
r, _ := strconv.ParseInt(fieldValue, 10, 32)
field.SetInt(r)
case reflect.Int64:
r, _ := strconv.ParseInt(fieldValue, 10, 64)
field.SetInt(r)
case reflect.Uint:
r, _ := strconv.ParseUint(fieldValue, 10, 0)
field.SetUint(r)
case reflect.Uint8:
r, _ := strconv.ParseUint(fieldValue, 10, 8)
field.SetUint(r)
case reflect.Uint16:
r, _ := strconv.ParseUint(fieldValue, 10, 16)
field.SetUint(r)
case reflect.Uint32:
r, _ := strconv.ParseUint(fieldValue, 10, 32)
field.SetUint(r)
case reflect.Uint64:
r, _ := strconv.ParseUint(fieldValue, 10, 64)
field.SetUint(r)
case reflect.Bool:
r, _ := strconv.ParseBool(fieldValue)
field.SetBool(r)
case reflect.Float32:
r, _ := strconv.ParseFloat(fieldValue, 32)
field.SetFloat(r)
case reflect.Float64:
r, _ := strconv.ParseFloat(fieldValue, 64)
field.SetFloat(r)
}
}
}