-
Notifications
You must be signed in to change notification settings - Fork 0
/
flag.go
255 lines (233 loc) · 6.99 KB
/
flag.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
/*
Copyright IBM Corp. 2017 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package util
import (
"fmt"
"reflect"
"strconv"
"strings"
"time"
"github.com/cloudflare/cfssl/log"
"github.com/mitchellh/mapstructure"
logging "github.com/op/go-logging"
"github.com/pkg/errors"
"github.com/spf13/cast"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
const (
// TagDefault is the tag name for a default value of a field as recognized
// by RegisterFlags.
TagDefault = "def"
// TagHelp is the tag name for a help message of a field as recognized
// by RegisterFlags.
TagHelp = "help"
// TagOpt is the tag name for a one character option of a field as recognized
// by RegisterFlags. For example, a value of "d" reserves "-d" for the
// command line argument.
TagOpt = "opt"
// TagSkip is the tag name which causes the field to be skipped by
// RegisterFlags.
TagSkip = "skip"
// TagHide is the tag name which causes the field to be hidden
TagHide = "hide"
)
// RegisterFlags registers flags for all fields in an arbitrary 'config' object.
// This method recognizes the following field tags:
// "def" - the default value of the field;
// "opt" - the optional one character short name to use on the command line;
// "help" - the help message to display on the command line;
// "skip" - to skip the field.
func RegisterFlags(v *viper.Viper, flags *pflag.FlagSet, config interface{},
tags map[string]string) error {
fr := &flagRegistrar{flags: flags, tags: tags, viper: v}
return ParseObj(config, fr.Register, tags)
}
type flagRegistrar struct {
flags *pflag.FlagSet
tags map[string]string
viper *viper.Viper
}
func (fr *flagRegistrar) Register(f *Field) (err error) {
// Don't register non-leaf fields
if !f.Leaf {
return nil
}
// Don't register fields with no address
if f.Addr == nil {
return errors.Errorf("Field is not addressable: %s", f.Path)
}
skip := fr.getTag(f, TagSkip)
if skip != "" {
return nil
}
help := fr.getTag(f, TagHelp)
opt := fr.getTag(f, TagOpt)
def := fr.getTag(f, TagDefault)
hide := fr.getHideBooleanTag(f)
switch f.Kind {
case reflect.String:
if help == "" && !hide {
return errors.Errorf("Field is missing a help tag: %s", f.Path)
}
fr.flags.StringVarP(f.Addr.(*string), f.Path, opt, def, help)
case reflect.Int:
if help == "" && !hide {
return errors.Errorf("Field is missing a help tag: %s", f.Path)
}
var intDef int
if def != "" {
intDef, err = strconv.Atoi(def)
if err != nil {
return errors.Errorf("Invalid integer value in 'def' tag of %s field", f.Path)
}
}
fr.flags.IntVarP(f.Addr.(*int), f.Path, opt, intDef, help)
case reflect.Int64:
if help == "" && !hide {
return errors.Errorf("Field is missing a help tag: %s", f.Path)
}
d, ok := f.Addr.(*time.Duration)
if !ok {
var intDef int64
if def != "" {
intDef, err = strconv.ParseInt(def, 10, 64)
if err != nil {
return errors.Errorf("Invalid int64 value in 'def' tag of %s field", f.Path)
}
}
fr.flags.Int64VarP(f.Addr.(*int64), f.Path, opt, intDef, help)
} else {
var intDef time.Duration
if def != "" {
intDef, err = time.ParseDuration(def)
if err != nil {
return errors.Errorf("Invalid duration value in 'def' tag of %s field", f.Path)
}
}
fr.flags.DurationVarP(d, f.Path, opt, intDef, help)
}
case reflect.Bool:
if help == "" && !hide {
return errors.Errorf("Field is missing a help tag: %s", f.Path)
}
var boolDef bool
if def != "" {
boolDef, err = strconv.ParseBool(def)
if err != nil {
return errors.Errorf("Invalid boolean value in 'def' tag of %s field", f.Path)
}
}
fr.flags.BoolVarP(f.Addr.(*bool), f.Path, opt, boolDef, help)
case reflect.Slice:
if f.Type.Elem().Kind() == reflect.String {
if help == "" && !hide {
return errors.Errorf("Field is missing a help tag: %s", f.Path)
}
fr.flags.StringSliceVarP(f.Addr.(*[]string), f.Path, opt, nil, help)
} else {
return nil
}
default:
log.Debugf("Not registering flag for '%s' because it is a currently unsupported type: %s\n",
f.Path, f.Kind)
return nil
}
if hide {
fr.flags.MarkHidden(f.Path)
}
bindFlag(fr.viper, fr.flags, f.Path)
return nil
}
func (fr *flagRegistrar) getTag(f *Field, tagName string) string {
var key, val string
key = fmt.Sprintf("%s.%s", tagName, f.Path)
if fr.tags != nil {
val = fr.tags[key]
}
if val == "" {
val = f.Tag.Get(tagName)
}
return val
}
func (fr *flagRegistrar) getHideBooleanTag(f *Field) bool {
boolVal, err := strconv.ParseBool(f.Hide)
if err != nil {
return false
}
return boolVal
}
// CmdRunBegin is called at the beginning of each cobra run function
func CmdRunBegin(v *viper.Viper) {
// If -d or --debug, set debug logging level
if v.GetBool("debug") {
log.Level = log.LevelDebug
logging.SetLevel(logging.INFO, "bccsp")
logging.SetLevel(logging.INFO, "bccsp_p11")
logging.SetLevel(logging.INFO, "bccsp_sw")
}
}
// FlagString sets up a flag for a string, binding it to its name
func FlagString(v *viper.Viper, flags *pflag.FlagSet, name, short string, def string, desc string) {
flags.StringP(name, short, def, desc)
bindFlag(v, flags, name)
}
// common binding function
func bindFlag(v *viper.Viper, flags *pflag.FlagSet, name string) {
flag := flags.Lookup(name)
if flag == nil {
panic(fmt.Errorf("failed to lookup '%s'", name))
}
v.BindPFlag(name, flag)
}
// ViperUnmarshal is a work around for a bug in viper.Unmarshal
// This can be removed once https://github.com/spf13/viper/issues/327 is fixed
// and vendored.
func ViperUnmarshal(cfg interface{}, stringSliceFields []string, vp *viper.Viper) error {
decoderConfig := &mapstructure.DecoderConfig{
Metadata: nil,
Result: cfg,
WeaklyTypedInput: true,
DecodeHook: mapstructure.StringToTimeDurationHookFunc(),
}
decoder, err := mapstructure.NewDecoder(decoderConfig)
if err != nil {
return errors.Wrap(err, "Failed to create decoder")
}
settings := vp.AllSettings()
for _, field := range stringSliceFields {
var ok bool
path := strings.Split(field, ".")
m := settings
name := path[0]
// If it is a top level option check to see if nil before continuing
if _, ok = m[name]; !ok {
continue
}
if len(path) > 1 {
for _, field2 := range path[1:] {
m = m[name].(map[string]interface{})
name = field2
// Inspect nested options to see if nil before proceeding with loop
if _, ok = m[name]; !ok {
break
}
}
}
// Only do casting if path was valid
if ok {
m[name] = cast.ToStringSlice(m[name])
}
}
return decoder.Decode(settings)
}