-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathflags.go
More file actions
121 lines (96 loc) · 2.32 KB
/
flags.go
File metadata and controls
121 lines (96 loc) · 2.32 KB
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
package flags
import (
"flag"
"fmt"
)
// ResolverFunc represents a resolver for a primitive flag type.
// Used for implementing additional config mechanisms (see env/ and json/).
type ResolverFunc func(*FlagSet, string, interface{}, int) bool
// Value represents a config value
type Value struct {
name string
resolvers []ResolverFunc
}
// FlagSet represents flags container.
type FlagSet struct {
fs *flag.FlagSet
args []string
Values []interface{}
Config map[string]interface{}
}
// Set sets a flag value for flag at i index
func (fs *FlagSet) Set(i int, v interface{}, t interface{}) error {
if i > (len(fs.Values) - 1) {
return fmt.Errorf("no flag at index %d", i)
}
var err error
switch t.(type) {
case string:
val := (fs.Values[i]).(StringValue)
err = val.Set(v)
case int:
val := (fs.Values[i]).(IntValue)
err = val.Set(v)
case int64:
val := (fs.Values[i]).(Int64Value)
err = val.Set(v)
case uint:
val := (fs.Values[i]).(UintValue)
err = val.Set(v)
case uint64:
val := (fs.Values[i]).(Uint64Value)
err = val.Set(v)
case bool:
val := (fs.Values[i]).(BoolValue)
err = val.Set(v)
case float64:
val := (fs.Values[i]).(Float64Value)
err = val.Set(v)
default:
return fmt.Errorf("unsupported flag type")
}
return err
}
// FlagSetOption func mainly used for extending FlagSet configuration for
// different types of resolvers.
type FlagSetOption func(*FlagSet)
// Parse parses command line flags and runs all additional resolvers for
// each flag in sequence.
// If command line flag is set it takes precedence over all other resolvers
// which are skipped in that case.
func (fs *FlagSet) Parse(args []string, opts ...FlagSetOption) {
if fs.Config == nil {
fs.Config = make(map[string]interface{})
}
for _, opt := range opts {
opt(fs)
}
fs.args = args
if len(fs.Values) == 0 {
return
}
fs.fs.Parse(args[1:])
fs.parseVals()
}
func (fs *FlagSet) parseVals() {
fs.parseStringVals()
fs.parseIntVals()
fs.parseInt64Vals()
fs.parseUintVals()
fs.parseUint64Vals()
fs.parseBoolVals()
fs.parseFloat64Vals()
}
func (fs *FlagSet) initFlagSet() {
if fs.fs == nil {
fs.fs = flag.NewFlagSet("", flag.ExitOnError)
}
}
func (fs *FlagSet) hasArg(name string) bool {
for _, arg := range fs.args {
if arg == fmt.Sprintf("-%s", name) {
return true
}
}
return false
}