-
Notifications
You must be signed in to change notification settings - Fork 1
/
configstruct.go
230 lines (197 loc) · 5.22 KB
/
configstruct.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
// Package configstruct provides a parse function to fill a config struct
// with values from cli flags or environment
package configstruct // import "github.com/pteich/configstruct"
import (
"flag"
"fmt"
"os"
"reflect"
"strconv"
"strings"
"gopkg.in/yaml.v3"
)
// Parse uses a given struct c with tags and parses values from env or cli flags, it uses the default FlagSet and os.Args
func Parse(c interface{}, opts ...Option) error {
return ParseWithFlagSet(flag.NewFlagSet(os.Args[0], flag.ContinueOnError), os.Args, c, opts...)
}
// ParseWithFlagSet can use a specific FlagSet and args slice to parse data from
func ParseWithFlagSet(flagSet *flag.FlagSet, cliArgs []string, c interface{}, opts ...Option) error {
config := config{
precedenceEnv: false,
}
for _, opt := range opts {
opt(&config)
}
if c == nil {
flagSet.Parse(cliArgs[1:])
return nil
}
// read config file if set
if config.file != "" {
err := readConfigFile(c, config)
if err != nil {
return err
}
}
// use reflection to deep dive into our struct
valueRef := reflect.ValueOf(c)
confType := valueRef.Elem().Type()
// parse arguments
parseArgs := func() error {
// iterate over struct fields for arg flags
for i := 0; i < confType.NumField(); i++ {
field := confType.Field(i)
value := valueRef.Elem().Field(i)
name := field.Tag.Get("name")
required := field.Tag.Get("required") == "true"
arg, err := strconv.Atoi(field.Tag.Get("arg"))
if err != nil {
arg = -1
}
if arg > 0 {
argVal := flagSet.Arg(arg - 1)
if required && argVal == "" {
flagSet.Usage()
return fmt.Errorf("argument %s is required", name)
}
if argVal != "" {
value.Set(reflect.ValueOf(argVal))
}
}
}
return nil
}
// parse cli flags
parseCli := func() error {
// iterate over struct fields for cli flags
for i := 0; i < confType.NumField(); i++ {
field := confType.Field(i)
value := valueRef.Elem().Field(i)
cli := field.Tag.Get("cli")
cliAlt := field.Tag.Get("cliAlt")
usage := field.Tag.Get("usage")
setFlag := func(name string) error {
switch field.Type.Kind() {
case reflect.String:
flagSet.StringVar(valueRef.Elem().FieldByName(field.Name).Addr().Interface().(*string), name, value.String(), usage)
case reflect.Bool:
flagSet.BoolVar(valueRef.Elem().FieldByName(field.Name).Addr().Interface().(*bool), name, value.Bool(), usage)
case reflect.Int:
flagSet.IntVar(valueRef.Elem().FieldByName(field.Name).Addr().Interface().(*int), name, int(value.Int()), usage)
case reflect.Float64:
flagSet.Float64Var(valueRef.Elem().FieldByName(field.Name).Addr().Interface().(*float64), name, value.Float(), usage)
default:
return fmt.Errorf("config cli type %s not implemented", field.Type.Kind())
}
return nil
}
if cli != "" {
err := setFlag(cli)
if err != nil {
return err
}
}
if cliAlt != "" {
err := setFlag(cliAlt)
if err != nil {
return err
}
}
}
return flagSet.Parse(cliArgs[1:])
}
parseEnv := func() error {
// iterate over struct fields for env values
for i := 0; i < confType.NumField(); i++ {
field := confType.Field(i)
env := field.Tag.Get("env")
envValue, found := os.LookupEnv(env)
if found {
switch field.Type.Kind() {
case reflect.String:
valueRef.Elem().FieldByName(field.Name).SetString(envValue)
case reflect.Bool:
valueRef.Elem().FieldByName(field.Name).SetBool(false)
if strings.EqualFold(envValue, "true") {
valueRef.Elem().FieldByName(field.Name).SetBool(true)
}
case reflect.Int:
value, err := strconv.ParseInt(envValue, 0, 64)
if err == nil {
valueRef.Elem().FieldByName(field.Name).SetInt(value)
}
case reflect.Float64:
value, err := strconv.ParseFloat(envValue, 64)
if err == nil {
valueRef.Elem().FieldByName(field.Name).SetFloat(value)
}
default:
return fmt.Errorf("config env type %s not implemented", field.Type.Name())
}
}
}
return nil
}
var err error
if config.precedenceEnv {
err = parseCli()
if err != nil {
return err
}
err = parseEnv()
if err != nil {
return err
}
err = parseArgs()
if err != nil {
return err
}
return nil
}
err = parseEnv()
if err != nil {
return err
}
err = parseCli()
if err != nil {
return err
}
err = parseArgs()
if err != nil {
return err
}
return nil
}
type structFlag struct {
name string
description string
defaultValue interface{}
}
func getStructFlags(c interface{}) []structFlag {
f := make([]structFlag, 0)
valueRef := reflect.ValueOf(c)
confType := valueRef.Elem().Type()
for i := 0; i < confType.NumField(); i++ {
field := confType.Field(i)
value := valueRef.Elem().Field(i)
cli := field.Tag.Get("cli")
usage := field.Tag.Get("usage")
f = append(f, structFlag{
name: cli,
description: usage,
defaultValue: value,
})
}
return f
}
func readConfigFile(c interface{}, cfg config) error {
f, err := os.Open(cfg.file)
if err != nil {
return fmt.Errorf("could not open config file %s: %w", cfg.file, err)
}
err = yaml.NewDecoder(f).Decode(c)
if err != nil {
return fmt.Errorf("could not decode yaml config file %s: %w", cfg.file, err)
}
return nil
}