-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoptions.go
398 lines (345 loc) · 8.7 KB
/
options.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package args
import (
"bytes"
"errors"
"fmt"
"os/user"
"path/filepath"
"reflect"
"sort"
"strings"
"github.com/spf13/cast"
)
type Value interface {
ToString(...int) string
GetValue() interface{}
GetRule() *Rule
Seen() bool
}
type Options struct {
log StdLogger
parser *ArgParser
values map[string]Value
}
type RawValue struct {
Value interface{}
Rule *Rule
}
func (self *RawValue) ToString(indent ...int) string {
return fmt.Sprintf("%v", self.Value)
}
func (self *RawValue) GetValue() interface{} {
return self.Value
}
func (self *RawValue) GetRule() *Rule {
return self.Rule
}
func (self *RawValue) Seen() bool {
if self.Rule.Flags&Seen != 0 {
return true
}
return false
}
func (self *ArgParser) NewOptions() *Options {
return &Options{
values: make(map[string]Value),
log: self.log,
parser: self,
}
}
func (self *ArgParser) NewOptionsFromMap(values map[string]interface{}) *Options {
options := self.NewOptions()
for key, value := range values {
// If the value is a map of interfaces
obj, ok := value.(map[string]interface{})
if ok {
// Convert them to options
options.SetWithOptions(key, self.NewOptionsFromMap(obj))
} else {
// Else set the value
options.Set(key, value)
}
}
return options
}
func (self *Options) GetOpts() *Options {
return self.parser.GetOpts()
}
func (self *Options) GetValue() interface{} {
return self
}
func (self *Options) GetRule() *Rule {
return nil
}
func (self *Options) ToString(indented ...int) string {
var buffer bytes.Buffer
indent := 2
if len(indented) != 0 {
indent = indented[0]
}
buffer.WriteString("{\n")
pad := strings.Repeat(" ", indent)
// Sort the values so testing is consistent
var keys []string
for key := range self.values {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
buffer.WriteString(fmt.Sprintf("%s'%s' = %s\n", pad, key, self.values[key].ToString(indent+2)))
}
buffer.WriteString(pad[2:] + "}")
return buffer.String()
}
func (self *Options) Group(key string) *Options {
// "" is not a valid group
if key == "" {
return self
}
group, ok := self.values[key]
// If group doesn't exist; always create it
if !ok {
group = self.parser.NewOptions()
self.values[key] = group
}
// If user called Group() on this value, it *should* be an
// *Option, map[string]string or map[string]interface{}
options := self.ToOption(group.GetValue())
if options == nil {
self.log.Printf("Attempted to call Group(%s) on non *Option or map[string]interface type %s",
key, reflect.TypeOf(group.GetValue()))
// Do this so we don't panic if we can't cast this group
options = self.parser.NewOptions()
}
return options
}
// Given an interface of map[string]string or map[string]string
// or *Option return an *Options with the same content.
// return nil if un-successful
func (self *Options) ToOption(from interface{}) *Options {
if options, ok := from.(*Options); ok {
return options
}
if stringMap, ok := from.(map[string]string); ok {
result := make(map[string]interface{})
for key, value := range stringMap {
result[key] = value
}
return self.parser.NewOptionsFromMap(result)
}
if interfaceMap, ok := from.(map[string]interface{}); ok {
return self.parser.NewOptionsFromMap(interfaceMap)
}
return nil
}
func (self *Options) ToMap() map[string]interface{} {
result := make(map[string]interface{})
for key, value := range self.values {
// If the value is an *Option
options, ok := value.(*Options)
if ok {
result[key] = options.ToMap()
} else {
result[key] = value.GetValue()
}
}
return result
}
func (self *Options) Keys() []string {
keys := make([]string, 0, len(self.values))
for key := range self.values {
keys = append(keys, key)
}
return keys
}
func (self *Options) Del(key string) *Options {
delete(self.values, key)
return self
}
func (self *Options) SetWithOptions(key string, value *Options) *Options {
self.values[key] = value
return self
}
// Just like Set() but also record the matching rule flags
func (self *Options) SetWithRule(key string, value interface{}, rule *Rule) *Options {
self.values[key] = &RawValue{value, rule}
return self
}
// Set an option with a key and value
func (self *Options) Set(key string, value interface{}) *Options {
return self.SetWithRule(key, value, nil)
}
// Return true if any of the values in this Option object were seen on the command line
func (self *Options) Seen() bool {
for _, opt := range self.values {
if opt.Seen() {
return true
}
}
return false
}
/*
Return true if none of the options where seen on the command line
opts, _ := parser.Parse(nil)
if opts.NoArgs() {
fmt.Printf("No arguments provided")
os.Exit(-1)
}
*/
func (self *Options) NoArgs() bool {
return !self.Seen()
}
func (self *Options) Int(key string) int {
value, err := cast.ToIntE(self.Interface(key))
if err != nil {
self.log.Printf("%s for key '%s'", err.Error(), key)
}
return value
}
func (self *Options) String(key string) string {
value, err := cast.ToStringE(self.Interface(key))
if err != nil {
self.log.Printf("%s for key '%s'", err.Error(), key)
}
return value
}
// Assumes the option is a string path and performs tilde '~' expansion if necessary
func (self *Options) FilePath(key string) string {
path, err := cast.ToStringE(self.Interface(key))
if err != nil {
self.log.Printf("%s for key '%s'", err.Error(), key)
}
if len(path) == 0 || path[0] != '~' {
return path
}
usr, err := user.Current()
if err != nil {
self.log.Printf("'%s': while determining user for '%s' expansion: %s", key, path, err)
return path
}
return filepath.Join(usr.HomeDir, path[1:])
}
func (self *Options) Bool(key string) bool {
value, err := cast.ToBoolE(self.Interface(key))
if err != nil {
self.log.Printf("%s for key '%s'", err.Error(), key)
}
return value
}
func (self *Options) StringSlice(key string) []string {
value, err := cast.ToStringSliceE(self.Interface(key))
if err != nil {
self.log.Printf("%s for key '%s'", err.Error(), key)
}
return value
}
func (self *Options) StringMap(key string) map[string]string {
group := self.Group(key)
result := make(map[string]string)
for _, key := range group.Keys() {
result[key] = group.String(key)
}
return result
}
func (self *Options) KeySlice(key string) []string {
return self.Group(key).Keys()
}
// Returns true if the argument value is set.
// Use IsDefault(), IsEnv(), IsArg() to determine how the parser set the value
func (self *Options) IsSet(key string) bool {
if opt, ok := self.values[key]; ok {
rule := opt.GetRule()
if rule == nil {
return false
}
return !(rule.Flags&NoValue != 0)
}
return false
}
// Returns true if this argument is set via the environment
func (self *Options) IsEnv(key string) bool {
if opt, ok := self.values[key]; ok {
rule := opt.GetRule()
if rule == nil {
return false
}
return (rule.Flags&EnvValue != 0)
}
return false
}
// Returns true if this argument is set via the command line
func (self *Options) IsArg(key string) bool {
if opt, ok := self.values[key]; ok {
rule := opt.GetRule()
if rule == nil {
return false
}
return (rule.Flags&Seen != 0)
}
return false
}
// Returns true if this argument is set via the default value
func (self *Options) IsDefault(key string) bool {
if opt, ok := self.values[key]; ok {
rule := opt.GetRule()
if rule == nil {
return false
}
return (rule.Flags&DefaultValue != 0)
}
return false
}
// Returns true if this argument was set via the command line or was set by an environment variable
func (self *Options) WasSeen(key string) bool {
if opt, ok := self.values[key]; ok {
rule := opt.GetRule()
if rule == nil {
return false
}
return (rule.Flags&Seen != 0) || (rule.Flags&EnvValue != 0)
}
return false
}
// Returns true only if all of the keys given have values set
func (self *Options) Required(keys []string) error {
for _, key := range keys {
if !self.IsSet(key) {
return errors.New(key)
}
}
return nil
}
func (self *Options) HasKey(key string) bool {
_, ok := self.values[key]
return ok
}
func (self *Options) Get(key string) interface{} {
if opt, ok := self.values[key]; ok {
return opt.GetValue()
}
return nil
}
func (self *Options) InspectOpt(key string) Value {
if opt, ok := self.values[key]; ok {
return opt
}
return nil
}
func (self *Options) Interface(key string) interface{} {
if opt, ok := self.values[key]; ok {
return opt.GetValue()
}
return nil
}
func (self *Options) FromChangeEvent(event *ChangeEvent) *Options {
if event.Deleted {
self.Group(event.Group).Del(event.KeyName)
} else {
self.Group(event.Group).Set(event.KeyName, string(event.Value))
}
return self
}
// TODO: Add these getters
/*Float64(key string) : float64
Time(key string) : time.Time
Duration(key string) : time.Duration*/