-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgofig_pflag.go
84 lines (70 loc) · 2 KB
/
gofig_pflag.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
package gofig
import (
"fmt"
log "github.com/sirupsen/logrus"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/akutz/gofig/types"
)
// config contains the configuration information
type config struct {
v *viper.Viper
flagSets map[string]*pflag.FlagSet
disableEnvVarSubstitution bool
}
func newConfigObj() *config {
return &config{
v: viper.New(),
flagSets: map[string]*pflag.FlagSet{},
disableEnvVarSubstitution: DisableEnvVarSubstitution,
}
}
func (c *config) FlagSets() map[string]*pflag.FlagSet {
return c.flagSets
}
func (c *config) processRegKeys(r types.ConfigRegistration) {
fsn := fmt.Sprintf("%s Flags", r.Name())
fs, ok := c.flagSets[fsn]
if !ok {
fs = &pflag.FlagSet{}
c.flagSets[fsn] = fs
}
for k := range r.Keys() {
if fs.Lookup(k.FlagName()) != nil {
continue
}
evn := k.EnvVarName()
if LogRegKey {
log.WithFields(log.Fields{
"keyName": k.KeyName(),
"keyType": k.KeyType(),
"flagName": k.FlagName(),
"envVar": evn,
"defaultValue": k.DefaultValue(),
"usage": k.Description(),
}).Debug("adding flag")
}
// bind the environment variable
c.v.BindEnv(k.KeyName(), evn)
if k.Short() == "" {
switch k.KeyType() {
case types.String, types.SecureString:
fs.String(k.FlagName(), k.DefaultValue().(string), k.Description())
case types.Int:
fs.Int(k.FlagName(), k.DefaultValue().(int), k.Description())
case types.Bool:
fs.Bool(k.FlagName(), k.DefaultValue().(bool), k.Description())
}
} else {
switch k.KeyType() {
case types.String, types.SecureString:
fs.StringP(k.FlagName(), k.Short(), k.DefaultValue().(string), k.Description())
case types.Int:
fs.IntP(k.FlagName(), k.Short(), k.DefaultValue().(int), k.Description())
case types.Bool:
fs.BoolP(k.FlagName(), k.Short(), k.DefaultValue().(bool), k.Description())
}
}
c.v.BindPFlag(k.KeyName(), fs.Lookup(k.FlagName()))
}
}