-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathparser.go
More file actions
335 lines (296 loc) · 10.8 KB
/
parser.go
File metadata and controls
335 lines (296 loc) · 10.8 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
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
package flaggy
import (
"errors"
"fmt"
"os"
"strconv"
"strings"
"text/template"
)
// Parser represents the set of flags and subcommands we are expecting
// from our input arguments. Parser is the top level struct responsible for
// parsing an entire set of subcommands and flags.
type Parser struct {
Subcommand
Version string // the optional version of the parser.
ShowHelpWithHFlag bool // display help when -h or --help passed
ShowVersionWithVersionFlag bool // display the version when --version passed
ShowHelpOnUnexpected bool // display help when an unexpected flag or subcommand is passed
TrailingArguments []string // everything after a -- is placed here
HelpTemplate *template.Template // template for Help output
trailingArgumentsExtracted bool // indicates that trailing args have been parsed and should not be appended again
parsed bool // indicates this parser has parsed
subcommandContext *Subcommand // points to the most specific subcommand being used
initialSubcommandContext *Subcommand // points to the initial help context prior to parsing
ShowCompletion bool // indicates that bash and zsh completion output is possible
SortFlags bool // when true, help output flags are sorted alphabetically
SortFlagsReverse bool // when true with SortFlags, sort order is reversed (Z..A)
}
// supportedCompletionShells lists every shell that can receive generated completion output.
var supportedCompletionShells = []string{"bash", "zsh", "fish", "powershell", "nushell"}
// completionShellList joins the supported completion shell names into a space separated string.
func completionShellList() string {
return strings.Join(supportedCompletionShells, " ")
}
// isSupportedCompletionShell reports whether the provided shell is eligible for generated completions.
func isSupportedCompletionShell(shell string) bool {
for _, supported := range supportedCompletionShells {
if shell == supported {
return true
}
}
return false
}
// TrailingSubcommand returns the last and most specific subcommand invoked.
func (p *Parser) TrailingSubcommand() *Subcommand {
return p.subcommandContext
}
// NewParser creates a new ArgumentParser ready to parse inputs
func NewParser(name string) *Parser {
// this can not be done inline because of struct embedding
p := &Parser{}
p.Name = name
p.Version = defaultVersion
p.ShowHelpOnUnexpected = true
p.ShowHelpWithHFlag = true
p.ShowVersionWithVersionFlag = true
p.ShowCompletion = true
p.SortFlags = false
p.SortFlagsReverse = false
p.SetHelpTemplate(DefaultHelpTemplate)
initialContext := &Subcommand{}
p.subcommandContext = initialContext
p.initialSubcommandContext = initialContext
return p
}
// isTopLevelHelpContext returns true when help output should be shown for the top
// level parser instead of a specific subcommand.
func (p *Parser) isTopLevelHelpContext() bool {
if p.subcommandContext == nil {
return true
}
if p.subcommandContext == &p.Subcommand {
return true
}
if p.initialSubcommandContext != nil && p.subcommandContext == p.initialSubcommandContext {
return true
}
return false
}
// SortFlagsByLongName enables alphabetical sorting by long flag name
// (case-insensitive) for help output on this parser.
func (p *Parser) SortFlagsByLongName() {
p.SortFlags = true
p.SortFlagsReverse = false
}
// SortFlagsByLongNameReversed enables reverse alphabetical sorting by
// long flag name (case-insensitive) for help output on this parser.
func (p *Parser) SortFlagsByLongNameReversed() {
p.SortFlags = true
p.SortFlagsReverse = true
}
// ParseArgs parses as if the passed args were the os.Args, but without the
// binary at the 0 position in the array. An error is returned if there
// is a low level issue converting flags to their proper type. No error
// is returned for invalid arguments or missing require subcommands.
func (p *Parser) ParseArgs(args []string) error {
if p.parsed {
return errors.New("Parser.Parse() called twice on parser with name: " + " " + p.Name + " " + p.ShortName)
}
p.parsed = true
// Handle shell completion before any parsing to avoid unknown-argument exits.
if p.ShowCompletion {
if len(args) >= 1 && strings.EqualFold(args[0], "completion") {
// no shell provided
if len(args) < 2 {
fmt.Fprintf(os.Stderr, "Please specify a shell for completion. Supported shells: %s\n", completionShellList())
exitOrPanic(2)
}
shell := strings.ToLower(args[1])
if isSupportedCompletionShell(shell) {
p.Completion(shell)
exitOrPanic(0)
}
fmt.Fprintf(os.Stderr, "Unsupported shell specified for completion: %s\nSupported shells: %s\n", args[1], completionShellList())
exitOrPanic(2)
}
}
debugPrint("Kicking off parsing with args:", args)
err := p.parse(p, args)
if err != nil {
return err
}
// if we are set to exit on unexpected args, look for those here
if p.ShowHelpOnUnexpected {
parsedValues := p.findAllParsedValues()
debugPrint("parsedValues:", parsedValues)
argsNotParsed := findArgsNotInParsedValues(args, parsedValues)
if len(argsNotParsed) > 0 {
// flatten out unused args for our error message
var argsNotParsedFlat string
for _, a := range argsNotParsed {
argsNotParsedFlat = argsNotParsedFlat + " " + a
}
p.ShowHelpAndExit("Unknown arguments supplied: " + argsNotParsedFlat)
}
}
return nil
}
// Completion takes in a shell type and outputs the completion script for
// that shell.
func (p *Parser) Completion(completionType string) {
switch strings.ToLower(completionType) {
case "bash":
fmt.Print(GenerateBashCompletion(p))
case "zsh":
fmt.Print(GenerateZshCompletion(p))
case "fish":
fmt.Print(GenerateFishCompletion(p))
case "powershell":
fmt.Print(GeneratePowerShellCompletion(p))
case "nushell":
fmt.Print(GenerateNushellCompletion(p))
default:
fmt.Fprintf(os.Stderr, "Unsupported shell specified for completion: %s\nSupported shells: %s\n", completionType, completionShellList())
}
}
// findArgsNotInParsedValues finds arguments not used in parsed values. The
// incoming args should be in the order supplied by the user and should not
// include the invoked binary, which is normally the first thing in os.Args.
func findArgsNotInParsedValues(args []string, parsedValues []parsedValue) []string {
// DebugMode = true
// defer func() {
// DebugMode = false
// }()
var argsNotUsed []string
var skipNext bool
for i := 0; i < len(args); i++ {
a := args[i]
// if the final argument (--) is seen, then we stop checking because all
// further values are trailing arguments.
if determineArgType(a) == argIsFinal {
return argsNotUsed
}
// allow for skipping the next arg when needed
if skipNext {
skipNext = false
continue
}
// Determine token type and normalized key/value
arg := parseFlagToName(a)
isFlagToken := strings.HasPrefix(a, "-")
// skip args that start with 'test.' because they are injected with go test
debugPrint("flagsNotParsed: checking arg for test prefix:", arg)
if strings.HasPrefix(arg, "test.") {
debugPrint("skipping test. prefixed arg has test prefix:", arg)
continue
}
debugPrint("flagsNotParsed: flag is not a test. flag:", arg)
// indicates that we found this arg used in one of the parsed values. Used
// to indicate which values should be added to argsNotUsed.
var foundArgUsed bool
// For flag tokens, only allow non-positional (flag) matches.
if isFlagToken {
for _, pv := range parsedValues {
debugPrint(pv.Key + "==" + arg + " || (" + strconv.FormatBool(pv.IsPositional) + " && " + pv.Value + " == " + arg + ")")
if !pv.IsPositional && pv.Key == arg {
debugPrint("Found matching parsed flag for " + pv.Key)
foundArgUsed = true
if pv.ConsumesNext {
skipNext = true
} else if i+1 < len(args) && pv.Value == args[i+1] {
skipNext = true
}
break
}
}
if foundArgUsed {
continue
}
}
// For non-flag tokens, prefer positional matches first.
if !isFlagToken {
for _, pv := range parsedValues {
debugPrint(pv.Key + "==" + arg + " || (" + strconv.FormatBool(pv.IsPositional) + " && " + pv.Value + " == " + arg + ")")
if pv.IsPositional && pv.Value == arg {
debugPrint("Found matching parsed positional for " + pv.Value)
foundArgUsed = true
break
}
}
if foundArgUsed {
continue
}
// Fallback for non-flag tokens: allow matching a non-positional flag by bare name.
for _, pv := range parsedValues {
debugPrint(pv.Key + "==" + arg + " || (" + strconv.FormatBool(pv.IsPositional) + " && " + pv.Value + " == " + arg + ")")
if !pv.IsPositional && pv.Key == arg {
debugPrint("Found matching parsed flag for " + pv.Key)
foundArgUsed = true
if pv.ConsumesNext {
skipNext = true
} else if i+1 < len(args) && pv.Value == args[i+1] {
skipNext = true
}
break
}
}
if foundArgUsed {
continue
}
}
// if the arg was not used in any parsed values, then we add it to the slice
// of arguments not used
if !foundArgUsed {
argsNotUsed = append(argsNotUsed, arg)
}
}
return argsNotUsed
}
// ShowVersionAndExit shows the version of this parser
func (p *Parser) ShowVersionAndExit() {
fmt.Println("Version:", p.Version)
exitOrPanic(0)
}
// SetHelpTemplate sets the go template this parser will use when rendering
// Help.
func (p *Parser) SetHelpTemplate(tmpl string) error {
var err error
p.HelpTemplate = template.New(helpFlagLongName)
p.HelpTemplate, err = p.HelpTemplate.Parse(tmpl)
if err != nil {
return err
}
return nil
}
// Parse calculates all flags and subcommands
func (p *Parser) Parse() error {
return p.ParseArgs(os.Args[1:])
}
// ShowHelp shows Help without an error message
func (p *Parser) ShowHelp() {
debugPrint("showing help for", p.subcommandContext.Name)
p.ShowHelpWithMessage("")
}
// ShowHelpAndExit shows parser help and exits with status code 2
func (p *Parser) ShowHelpAndExit(message string) {
p.ShowHelpWithMessage(message)
exitOrPanic(2)
}
// ShowHelpWithMessage shows the Help for this parser with an optional string error
// message as a header. The supplied subcommand will be the context of Help
// displayed to the user.
func (p *Parser) ShowHelpWithMessage(message string) {
// create a new Help values template and extract values into it
help := Help{}
help.ExtractValues(p, message)
err := p.HelpTemplate.Execute(os.Stderr, help)
if err != nil {
fmt.Fprintln(os.Stderr, "Error rendering Help template:", err)
}
}
// DisableShowVersionWithVersion disables the showing of version information
// with --version. It is enabled by default.
func (p *Parser) DisableShowVersionWithVersion() {
p.ShowVersionWithVersionFlag = false
}