-
Notifications
You must be signed in to change notification settings - Fork 1
/
wonsz.go
227 lines (203 loc) · 6.84 KB
/
wonsz.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
package wonsz
import (
"fmt"
"github.com/sevlyar/retag"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
globalViper "github.com/spf13/viper"
"reflect"
)
var cfgOpts ConfigOpts
var cfg interface{}
var viper *globalViper.Viper
// ConfigOpts provide additional options to configure Wonsz.
type ConfigOpts struct {
// Environment variables prefix.
// E.g. if your prefix is "wonsz", the env registry will look for env variables that start with "WONSZ_".
EnvPrefix string
// Paths to search for the config file in.
ConfigPaths []string
// Type of the configuration file, e.g. "json".
// Wonsz use Viper for loading the configuration file,
// so you can use any type of configuration file that Viper supports.
ConfigType string
// Name for the config file. Does not include extension.
ConfigName string
// Pass own viper instance. Default is global viper instance.
Viper *globalViper.Viper
}
// Get returns a config struct instance to which Wonsz binds configuration.
func Get() interface{} {
return cfg
}
// GetViper returns a viper instance used by Wonsz.
func GetViper() *globalViper.Viper {
return viper
}
// BindConfig binds configuration structure to config file, environment variables and cobra command flags.
// The config parameter should be a pointer to configuration structure.
// You can pass nil to rootCmd, if you don't want to bind cobra command flags with config.
func BindConfig(config interface{}, rootCmd *cobra.Command, options ConfigOpts) error {
if !(reflect.TypeOf(config).Kind() == reflect.Ptr && reflect.TypeOf(config).Elem().Kind() == reflect.Struct) {
return fmt.Errorf("config parameter is not a pointer to a structure. Maybe you should use & operator")
}
// prepare for processing
cfgOpts = options
if cfgOpts.Viper != nil {
viper = cfgOpts.Viper
} else {
viper = globalViper.GetViper()
}
cfg = retag.Convert(config, mapstructureRetagger{})
if rootCmd == nil { // only viper
initializeViper()
return nil
}
cobra.OnInitialize(initializeViper)
confType := reflect.TypeOf(cfg).Elem()
for i := 0; i < confType.NumField(); i++ {
field := confType.Field(i)
if field.Anonymous {
continue
}
dashedName := camelCaseToDashedLowered(field.Name)
underscoredName := camelCaseToUnderscoredLowered(field.Name)
var err error
flags := rootCmd.PersistentFlags()
usageHint := field.Tag.Get("usage")
if shortcut, ok := field.Tag.Lookup("shortcut"); ok {
err = bindPFlag(flags, field, dashedName, shortcut, usageHint)
} else {
err = bindFlag(flags, field, dashedName, usageHint)
}
if err != nil {
return err
}
targetFlag := flags.Lookup(dashedName)
if targetFlag == nil {
return fmt.Errorf("flag %s not found, despite successful binding", dashedName)
}
err = viper.BindPFlag(underscoredName, targetFlag)
if err != nil {
return err
}
}
return nil
}
func initializeViper() {
viper.SetEnvPrefix(cfgOpts.EnvPrefix)
for _, path := range cfgOpts.ConfigPaths {
viper.AddConfigPath(path)
}
viper.SetConfigType(cfgOpts.ConfigType)
viper.SetConfigName(cfgOpts.ConfigName)
bindEnvsAndSetDefaults()
viper.AutomaticEnv()
if err := viper.ReadInConfig(); err != nil {
logrus.Infof("Config file not found.")
} else {
logrus.Infof("Using config file: %v.", viper.ConfigFileUsed())
}
if err := viper.Unmarshal(&cfg); err != nil {
logrus.WithError(err).Fatal("Cannot unmarshall config into Config struct.")
}
}
func bindEnvsAndSetDefaults() {
el := reflect.TypeOf(cfg).Elem()
for i := 0; i < el.NumField(); i++ {
field := el.Field(i)
defaultVal := field.Tag.Get("default")
mapping := field.Tag.Get("mapstructure")
if defaultVal != "" {
viper.SetDefault(mapping, defaultVal)
} else {
err := viper.BindEnv(mapping)
if err != nil {
logrus.Fatal(err)
}
}
}
}
func bindPFlag(flags *pflag.FlagSet, field reflect.StructField, dashedName, shortcut, usageHint string) error {
switch field.Type.Kind() {
case reflect.String:
flags.StringP(dashedName, shortcut, "", usageHint)
case reflect.Int64:
flags.Int64P(dashedName, shortcut, 0, usageHint)
case reflect.Int32:
flags.Int32P(dashedName, shortcut, 0, usageHint)
case reflect.Int16:
flags.Int16P(dashedName, shortcut, 0, usageHint)
case reflect.Int8:
flags.Int8P(dashedName, shortcut, 0, usageHint)
case reflect.Int:
flags.IntP(dashedName, shortcut, 0, usageHint)
case reflect.Float64:
flags.Float64P(dashedName, shortcut, 0, usageHint)
case reflect.Float32:
flags.Float32P(dashedName, shortcut, 0, usageHint)
case reflect.Bool:
flags.BoolP(dashedName, shortcut, false, usageHint)
case reflect.Array:
if field.Type.Elem().Kind() == reflect.String {
flags.StringArrayP(dashedName, shortcut, []string{}, usageHint)
} else {
return fmt.Errorf("unsupported flag %s type: %s. only string arrays are supported", dashedName, field.Type.String())
}
case reflect.Slice:
if field.Type.Elem().Kind() == reflect.String {
flags.StringSliceP(dashedName, shortcut, []string{}, usageHint)
} else {
return fmt.Errorf("unsupported flag %s type: %s. only string slices are supported", dashedName, field.Type.String())
}
case reflect.Map:
if field.Type.Elem().Kind() == reflect.String {
flags.StringToStringP(dashedName, shortcut, map[string]string{}, usageHint)
} else {
return fmt.Errorf("unsupported flag %s type: %s. only map[string]string maps are supported", dashedName, field.Type.String())
}
}
return nil
}
func bindFlag(flags *pflag.FlagSet, field reflect.StructField, dashedName, usageHint string) error {
switch field.Type.Kind() {
case reflect.String:
flags.String(dashedName, "", usageHint)
case reflect.Int64:
flags.Int64(dashedName, 0, usageHint)
case reflect.Int32:
flags.Int32(dashedName, 0, usageHint)
case reflect.Int16:
flags.Int16(dashedName, 0, usageHint)
case reflect.Int8:
flags.Int8(dashedName, 0, usageHint)
case reflect.Int:
flags.Int(dashedName, 0, usageHint)
case reflect.Float64:
flags.Float64(dashedName, 0, usageHint)
case reflect.Float32:
flags.Float32(dashedName, 0, usageHint)
case reflect.Bool:
flags.Bool(dashedName, false, usageHint)
case reflect.Array:
if field.Type.Elem().Kind() == reflect.String {
flags.StringArray(dashedName, []string{}, usageHint)
} else {
return fmt.Errorf("unsupported flag %s type: %s. only string arrays are supported", dashedName, field.Type.String())
}
case reflect.Slice:
if field.Type.Elem().Kind() == reflect.String {
flags.StringSlice(dashedName, []string{}, usageHint)
} else {
return fmt.Errorf("unsupported flag %s type: %s. only string slices are supported", dashedName, field.Type.String())
}
case reflect.Map:
if field.Type.Elem().Kind() == reflect.String {
flags.StringToString(dashedName, map[string]string{}, usageHint)
} else {
return fmt.Errorf("unsupported flag %s type: %s. only map[string]string maps are supported", dashedName, field.Type.String())
}
}
return nil
}