-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathviper.go
376 lines (346 loc) · 9.96 KB
/
viper.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
package cli
import (
"fmt"
"os"
"path"
"strings"
"time"
"github.com/influxdata/influxdb/v2/kit/platform"
"github.com/spf13/cast"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"go.uber.org/zap/zapcore"
)
// Opt is a single command-line option
type Opt struct {
DestP interface{} // pointer to the destination
EnvVar string
Flag string
Hidden bool
Persistent bool
Required bool
Short rune // using rune b/c it guarantees correctness. a short must always be a string of length 1
Default interface{}
Desc string
}
// Program parses CLI options
type Program struct {
// Run is invoked by cobra on execute.
Run func() error
// Name is the name of the program in help usage and the env var prefix.
Name string
// Opts are the command line/env var options to the program
Opts []Opt
}
// NewCommand creates a new cobra command to be executed that respects env vars.
//
// Uses the upper-case version of the program's name as a prefix
// to all environment variables.
//
// This is to simplify the viper/cobra boilerplate.
func NewCommand(v *viper.Viper, p *Program) (*cobra.Command, error) {
cmd := &cobra.Command{
Use: p.Name,
Args: cobra.NoArgs,
RunE: func(_ *cobra.Command, _ []string) error {
return p.Run()
},
}
v.SetEnvPrefix(strings.ToUpper(p.Name))
v.AutomaticEnv()
// This normalizes "-" to an underscore in env names.
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
// done before we bind flags to viper keys.
// order of precedence (1 highest -> 3 lowest):
// 1. flags
// 2. env vars
// 3. config file
if err := initializeConfig(v); err != nil {
return nil, fmt.Errorf("failed to load config file: %w", err)
}
if err := BindOptions(v, cmd, p.Opts); err != nil {
return nil, fmt.Errorf("failed to bind config options: %w", err)
}
return cmd, nil
}
func initializeConfig(v *viper.Viper) error {
configPath := v.GetString("CONFIG_PATH")
if configPath == "" {
// Default to looking in the working directory of the running process.
configPath = "."
}
switch strings.ToLower(path.Ext(configPath)) {
case ".json", ".toml", ".yaml", ".yml":
v.SetConfigFile(configPath)
default:
v.AddConfigPath(configPath)
}
if err := v.ReadInConfig(); err != nil && !os.IsNotExist(err) {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
return err
}
}
return nil
}
// BindOptions adds opts to the specified command and automatically
// registers those options with viper.
func BindOptions(v *viper.Viper, cmd *cobra.Command, opts []Opt) error {
for _, o := range opts {
flagset := cmd.Flags()
if o.Persistent {
flagset = cmd.PersistentFlags()
}
envVal := lookupEnv(v, &o)
hasShort := o.Short != 0
switch destP := o.DestP.(type) {
case *string:
var d string
if o.Default != nil {
d = o.Default.(string)
}
if hasShort {
flagset.StringVarP(destP, o.Flag, string(o.Short), d, o.Desc)
} else {
flagset.StringVar(destP, o.Flag, d, o.Desc)
}
if err := v.BindPFlag(o.Flag, flagset.Lookup(o.Flag)); err != nil {
return fmt.Errorf("failed to bind flag %q: %w", o.Flag, err)
}
if envVal != nil {
if s, err := cast.ToStringE(envVal); err == nil {
*destP = s
}
}
case *int:
var d int
if o.Default != nil {
d = o.Default.(int)
}
if hasShort {
flagset.IntVarP(destP, o.Flag, string(o.Short), d, o.Desc)
} else {
flagset.IntVar(destP, o.Flag, d, o.Desc)
}
if err := v.BindPFlag(o.Flag, flagset.Lookup(o.Flag)); err != nil {
return fmt.Errorf("failed to bind flag %q: %w", o.Flag, err)
}
if envVal != nil {
if i, err := cast.ToIntE(envVal); err == nil {
*destP = i
}
}
case *int32:
var d int32
if o.Default != nil {
// N.B. since our CLI kit types default values as interface{} and
// literal numbers get typed as int by default, it's very easy to
// create an int32 CLI flag with an int default value.
//
// The compiler doesn't know to complain in that case, so you end up
// with a runtime panic when trying to bind the CLI options.
//
// To avoid that headache, we support both int32 and int defaults
// for int32 fields. This introduces a new runtime bomb if somebody
// specifies an int default > math.MaxInt32, but that's hopefully
// less likely.
var ok bool
d, ok = o.Default.(int32)
if !ok {
d = int32(o.Default.(int))
}
}
if hasShort {
flagset.Int32VarP(destP, o.Flag, string(o.Short), d, o.Desc)
} else {
flagset.Int32Var(destP, o.Flag, d, o.Desc)
}
if err := v.BindPFlag(o.Flag, flagset.Lookup(o.Flag)); err != nil {
return fmt.Errorf("failed to bind flag %q: %w", o.Flag, err)
}
if envVal != nil {
if i, err := cast.ToInt32E(envVal); err == nil {
*destP = i
}
}
case *int64:
var d int64
if o.Default != nil {
// N.B. since our CLI kit types default values as interface{} and
// literal numbers get typed as int by default, it's very easy to
// create an int64 CLI flag with an int default value.
//
// The compiler doesn't know to complain in that case, so you end up
// with a runtime panic when trying to bind the CLI options.
//
// To avoid that headache, we support both int64 and int defaults
// for int64 fields.
var ok bool
d, ok = o.Default.(int64)
if !ok {
d = int64(o.Default.(int))
}
}
if hasShort {
flagset.Int64VarP(destP, o.Flag, string(o.Short), d, o.Desc)
} else {
flagset.Int64Var(destP, o.Flag, d, o.Desc)
}
if err := v.BindPFlag(o.Flag, flagset.Lookup(o.Flag)); err != nil {
return fmt.Errorf("failed to bind flag %q: %w", o.Flag, err)
}
if envVal != nil {
if i, err := cast.ToInt64E(envVal); err == nil {
*destP = i
}
}
case *bool:
var d bool
if o.Default != nil {
d = o.Default.(bool)
}
if hasShort {
flagset.BoolVarP(destP, o.Flag, string(o.Short), d, o.Desc)
} else {
flagset.BoolVar(destP, o.Flag, d, o.Desc)
}
if err := v.BindPFlag(o.Flag, flagset.Lookup(o.Flag)); err != nil {
return fmt.Errorf("failed to bind flag %q: %w", o.Flag, err)
}
if envVal != nil {
if b, err := cast.ToBoolE(envVal); err == nil {
*destP = b
}
}
case *time.Duration:
var d time.Duration
if o.Default != nil {
d = o.Default.(time.Duration)
}
if hasShort {
flagset.DurationVarP(destP, o.Flag, string(o.Short), d, o.Desc)
} else {
flagset.DurationVar(destP, o.Flag, d, o.Desc)
}
if err := v.BindPFlag(o.Flag, flagset.Lookup(o.Flag)); err != nil {
return fmt.Errorf("failed to bind flag %q: %w", o.Flag, err)
}
if envVal != nil {
if d, err := cast.ToDurationE(envVal); err == nil {
*destP = d
}
}
case *[]string:
var d []string
if o.Default != nil {
d = o.Default.([]string)
}
if hasShort {
flagset.StringSliceVarP(destP, o.Flag, string(o.Short), d, o.Desc)
} else {
flagset.StringSliceVar(destP, o.Flag, d, o.Desc)
}
if err := v.BindPFlag(o.Flag, flagset.Lookup(o.Flag)); err != nil {
return fmt.Errorf("failed to bind flag %q: %w", o.Flag, err)
}
if envVal != nil {
if ss, err := cast.ToStringSliceE(envVal); err == nil {
*destP = ss
}
}
case *map[string]string:
var d map[string]string
if o.Default != nil {
d = o.Default.(map[string]string)
}
if hasShort {
flagset.StringToStringVarP(destP, o.Flag, string(o.Short), d, o.Desc)
} else {
flagset.StringToStringVar(destP, o.Flag, d, o.Desc)
}
if err := v.BindPFlag(o.Flag, flagset.Lookup(o.Flag)); err != nil {
return fmt.Errorf("failed to bind flag %q: %w", o.Flag, err)
}
if envVal != nil {
if sms, err := cast.ToStringMapStringE(envVal); err == nil {
*destP = sms
}
}
case pflag.Value:
if hasShort {
flagset.VarP(destP, o.Flag, string(o.Short), o.Desc)
} else {
flagset.Var(destP, o.Flag, o.Desc)
}
if o.Default != nil {
_ = destP.Set(o.Default.(string))
}
if err := v.BindPFlag(o.Flag, flagset.Lookup(o.Flag)); err != nil {
return fmt.Errorf("failed to bind flag %q: %w", o.Flag, err)
}
if envVal != nil {
if s, err := cast.ToStringE(envVal); err == nil {
_ = destP.Set(s)
}
}
case *platform.ID:
var d platform.ID
if o.Default != nil {
d = o.Default.(platform.ID)
}
if hasShort {
IDVarP(flagset, destP, o.Flag, string(o.Short), d, o.Desc)
} else {
IDVar(flagset, destP, o.Flag, d, o.Desc)
}
if envVal != nil {
if s, err := cast.ToStringE(envVal); err == nil {
_ = (*destP).DecodeFromString(s)
}
}
case *zapcore.Level:
var l zapcore.Level
if o.Default != nil {
l = o.Default.(zapcore.Level)
}
if hasShort {
LevelVarP(flagset, destP, o.Flag, string(o.Short), l, o.Desc)
} else {
LevelVar(flagset, destP, o.Flag, l, o.Desc)
}
if envVal != nil {
if s, err := cast.ToStringE(envVal); err == nil {
_ = (*destP).Set(s)
}
}
default:
// if you get this error, sorry about that!
// anyway, go ahead and make a PR and add another type.
return fmt.Errorf("unknown destination type %t", o.DestP)
}
// N.B. these "Mark" calls must run after the block above,
// otherwise cobra will return a "no such flag" error.
// Cobra will complain if a flag marked as required isn't present on the CLI.
// To support setting required args via config and env variables, we only enforce
// the required check if we didn't find a value in the viper instance.
if o.Required && envVal == nil {
if err := cmd.MarkFlagRequired(o.Flag); err != nil {
return fmt.Errorf("failed to mark flag %q as required: %w", o.Flag, err)
}
}
if o.Hidden {
if err := flagset.MarkHidden(o.Flag); err != nil {
return fmt.Errorf("failed to mark flag %q as hidden: %w", o.Flag, err)
}
}
}
return nil
}
// lookupEnv returns the value for a CLI option found in the environment, if any.
func lookupEnv(v *viper.Viper, o *Opt) interface{} {
envVar := o.Flag
if o.EnvVar != "" {
envVar = o.EnvVar
}
return v.Get(envVar)
}