-
Notifications
You must be signed in to change notification settings - Fork 2
/
parser.go
259 lines (236 loc) · 5.53 KB
/
parser.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
package xflags
import (
"os"
)
// TODO: fuzz tests?
// argument to terminate parsing of all remaining arguments
const terminator = "--"
type argParser struct {
tokens []string
args []string
cmd *Command
isTerminated bool
flagsByName map[string]*Flag
subcommandsByName map[string]*Command
flagsSeen map[string]int
positionals []*Flag
}
func newArgParser(cmd *Command, tokens []string) *argParser {
tokens = normalize(tokens, cmd.WithTerminator)
c := &argParser{
tokens: tokens,
flagsByName: make(map[string]*Flag),
flagsSeen: make(map[string]int),
subcommandsByName: make(map[string]*Command),
}
c.setCommand(cmd)
return c
}
// setCommand descends the parser into a new subcommand.
func (c *argParser) setCommand(cmd *Command) {
// accumulate flags
c.cmd = cmd
c.positionals = make([]*Flag, 0)
for _, group := range cmd.FlagGroups {
for _, flag := range group.Flags {
if flag.Name != "" {
c.flagsByName["--"+flag.Name] = flag
}
if flag.ShortName != "" {
c.flagsByName["-"+flag.ShortName] = flag
}
if flag.Positional {
c.positionals = append(c.positionals, flag)
}
}
}
// reset subcommands
c.subcommandsByName = make(map[string]*Command)
for _, cmd := range cmd.Subcommands {
c.subcommandsByName[cmd.Name] = cmd
}
}
func (c *argParser) Parse() (cmd *Command, args []string, err error) {
for {
arg, ok := c.next()
if !ok {
break
}
if err = c.dispatch(arg); err != nil {
return
}
}
if err = c.parseEnvVars(); err != nil {
return
}
if err = c.checkNArgs(); err != nil {
return
}
return c.cmd, c.args, nil
}
func (c *argParser) parseEnvVars() error {
for _, flag := range c.flagsByName {
if flag.EnvVar == "" {
continue
}
n := c.flagsSeen[flag.name()]
if n > 0 {
continue
}
s, ok := os.LookupEnv(flag.EnvVar)
if !ok {
continue
}
c.observe(flag)
if err := c.setFlag(flag, s); err != nil {
return err
}
}
return nil
}
func (c *argParser) checkNArgs() error {
for _, group := range c.cmd.FlagGroups {
for _, flag := range group.Flags {
n := c.flagsSeen[flag.name()]
if flag.MinCount > 0 && n < flag.MinCount {
return newArgErr(c.cmd, flag, "", "missing argument: %s", flag)
}
if flag.MaxCount > 0 && n > flag.MaxCount {
return newArgErr(c.cmd, flag, "", "argument declared too many times: %s", flag)
}
}
}
return nil
}
func (c *argParser) peek() (token string, ok bool) {
if len(c.tokens) == 0 {
return
}
ok = true
token = c.tokens[0]
return
}
func (c *argParser) next() (token string, ok bool) {
token, ok = c.peek()
if ok {
c.tokens = c.tokens[1:]
}
return
}
func (c *argParser) observe(flag *Flag) int {
c.flagsSeen[flag.name()] += 1
return c.flagsSeen[flag.name()]
}
func (c *argParser) dispatch(token string) error {
if c.isTerminated {
if c.args == nil {
c.args = make([]string, 0, 1)
}
c.args = append(c.args, token)
return nil
}
if token == terminator && c.cmd.WithTerminator {
c.isTerminated = true
return nil
}
if token == "-h" || token == "--help" {
return &HelpError{Cmd: c.cmd}
}
if isPositional(token) {
return c.dispatchPositional(token)
}
return c.dispatchRegular(token)
}
func (c *argParser) dispatchPositional(token string) error {
// handle positional flag
if len(c.positionals) > 0 {
flag := c.positionals[0]
n := c.observe(flag)
if flag.MaxCount > 0 && n == flag.MaxCount {
// all done with this positional flag
c.positionals = c.positionals[1:]
}
return c.setFlag(flag, token)
}
// handle subcommand
if len(c.cmd.Subcommands) == 0 {
return newArgErr(c.cmd, nil, token, "unexpected positional argument: %s", token)
}
cmd, ok := c.subcommandsByName[token]
if !ok {
return newArgErr(c.cmd, nil, token, "unrecognized command: %s", token)
}
c.setCommand(cmd)
return nil
}
func (c *argParser) dispatchRegular(token string) error {
// regular flag
flag := c.flagsByName[token]
if flag == nil {
return newArgErr(c.cmd, nil, token, "unrecognized argument: %s", token)
}
c.observe(flag)
if isBoolValue(flag.Value) {
return c.setFlag(flag, "true")
}
// read the next arg as a value
value, ok := c.peek()
if !ok || !isPositional(value) {
return newArgErr(c.cmd, flag, token, "no value specified for flag: %s", token)
}
c.next() // consume the value
return c.setFlag(flag, value)
}
func (c *argParser) setFlag(flag *Flag, value string) error {
if err := flag.Set(value); err != nil {
return wrapArgErr(err, c.cmd, flag, value)
}
return nil
}
func isSingleDash(arg string) bool {
if len(arg) < 2 {
return false
}
return arg[0] == '-' && arg[1] != '-'
}
func isDoubleDash(arg string) bool {
if len(arg) < 3 {
return false
}
return arg[0] == '-' && arg[1] == '-'
}
func isPositional(arg string) bool {
return !isSingleDash(arg) && !isDoubleDash(arg)
}
// normalize splits any arguments that declare both a key and a value (E.g.
// --key=value, or -kV) into two distinct arguments.
func normalize(args []string, withTerminator bool) []string {
out := make([]string, 0, len(args))
for i, arg := range args {
if withTerminator && arg == terminator {
out = append(out, args[i:]...)
return out
}
if isSingleDash(arg) {
out = append(out, arg[:2])
arg = arg[2:]
if len(arg) > 0 {
if arg[0] == '=' {
arg = arg[1:]
}
} else {
continue
}
} else if isDoubleDash(arg) {
for i := 3; i < len(arg); i++ {
if arg[i] == '=' {
out = append(out, arg[:i])
arg = arg[i+1:]
break
}
}
}
out = append(out, arg)
}
return out
}