Debian Codegraph @

parser.go

raw symbols SCIP
1 // Copyright 2012 Jesse van den Kieboom. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package flags
6
7 import (
8 "bytes"
9 "fmt"
10 "io"
11 "os"
12 "path"
13 "sort"
14 "strings"
15 "unicode/utf8"
16 )
17
18 // A Parser provides command line option parsing. It can contain several
19 // option groups each with their own set of options.
20 type Parser struct {
21 Commander
22
23 // The option groups available to the parser
24 Groups []*Group
25 GroupsMap map[string]*Group
26
27 // The parser application name
28 ApplicationName string
29
30 // The application short description
31 Description string
32
33 // The usage (e.g. [OPTIONS] <filename>)
34 Usage string
35
36 Options Options
37
38 currentCommand *Group
39 currentCommandString []string
40 }
41
42 // Parser options
43 type Options uint
44
45 const (
46 // No options
47 None Options = 0
48
49 // Add a default Help Options group to the parser containing -h and
50 // --help options. When either -h or --help is specified on the command
51 // line, a pretty formatted help message will be printed to os.Stderr.
52 // The parser will return ErrHelp.
53 HelpFlag = 1 << iota
54
55 // Pass all arguments after a double dash, --, as remaining command line
56 // arguments (i.e. they will not be parsed for flags)
57 PassDoubleDash
58
59 // Ignore any unknown options and pass them as remaining command line
60 // arguments
61 IgnoreUnknown
62
63 // Print any errors which occured during parsing to os.Stderr
64 PrintErrors
65
66 // Pass all arguments after the first non option. This is equivalent
67 // to strict POSIX processing
68 PassAfterNonOption
69
70 // A convenient default set of options
71 Default = HelpFlag | PrintErrors | PassDoubleDash
72 )
73
74 // Parse is a convenience function to parse command line options with default
75 // settings. The provided data is a pointer to a struct representing the
76 // default option group (named "Application Options"). For more control, use
77 // flags.NewParser.
78 func Parse(data interface{}) ([]string, error) {
79 return NewParser(data, Default).Parse()
80 }
81
82 // ParseArgs is a convenience function to parse command line options with default
83 // settings. The provided data is a pointer to a struct representing the
84 // default option group (named "Application Options"). The args argument is
85 // the list of command line arguments to parse. If you just want to parse the
86 // default program command line arguments (i.e. os.Args), then use flags.Parse
87 // instead. For more control, use flags.NewParser.
88 func ParseArgs(data interface{}, args []string) ([]string, error) {
89 return NewParser(data, Default).ParseArgs(args)
90 }
91
92 // ParseIni is a convenience function to parse command line options with default
93 // settings from an ini file. The provided data is a pointer to a struct
94 // representing the default option group (named "Application Options"). For
95 // more control, use flags.NewParser.
96 func ParseIni(filename string, data interface{}) error {
97 return NewParser(data, Default).ParseIniFile(filename)
98 }
99
100 // NewParser creates a new parser. It uses os.Args[0] as the application
101 // name and then calls Parser.NewNamedParser (see Parser.NewNamedParser for
102 // more details). The provided data is a pointer to a struct representing the
103 // default option group (named "Application Options"), or nil if the default
104 // group should not be added. The options parameter specifies a set of options
105 // for the parser.
106 func NewParser(data interface{}, options Options) *Parser {
107 if data == nil {
108 return NewNamedParser(path.Base(os.Args[0]), options)
109 }
110
111 return NewNamedParser(path.Base(os.Args[0]), options, NewGroup("Application Options", data))
112 }
113
114 // NewNamedParser creates a new parser. The appname is used to display the
115 // executable name in the builtin help message. An initial set of option groups
116 // can be specified when constructing a parser, but you can also add additional
117 // option groups later (see Parser.AddGroup).
118 func NewNamedParser(appname string, options Options, groups ...*Group) *Parser {
119 ret := &Parser{
120 Commander: Commander{
121 Commands: make(map[string]*Group),
122 },
123
124 ApplicationName: appname,
125 Groups: groups,
126 GroupsMap: make(map[string]*Group),
127 Options: options,
128 Usage: "[OPTIONS]",
129 }
130
131 ret.EachGroup(func(index int, grp *Group) {
132 ret.GroupsMap[strings.ToLower(grp.Name)] = grp
133 })
134
135 return ret
136 }
137
138 // AddGroup adds a new group to the parser with the given name and data. The
139 // data needs to be a pointer to a struct from which the fields indicate which
140 // options are in the group.
141 func (p *Parser) AddGroup(name string, data interface{}) *Parser {
142 group := NewGroup(name, data)
143
144 p.Groups = append(p.Groups, group)
145
146 group.each(0, func(index int, grp *Group) {
147 p.GroupsMap[strings.ToLower(group.Name)] = grp
148 })
149
150 return p
151 }
152
153 // AddCommand adds a new command to the parser with the given name and data. The
154 // data needs to be a pointer to a struct from which the fields indicate which
155 // options are in the command.
156 func (p *Parser) AddCommand(command string, description string, longDescription string, data interface{}) *Parser {
157 p.AddGroup(description, data)
158
159 group := p.Groups[len(p.Groups)-1]
160 group.IsCommand = true
161 group.LongDescription = longDescription
162
163 p.Commands[command] = group
164
165 return p
166 }
167
168 // Parse parses the command line arguments from os.Args using Parser.ParseArgs.
169 // For more detailed information see ParseArgs.
170 func (p *Parser) Parse() ([]string, error) {
171 return p.ParseArgs(os.Args[1:])
172 }
173
174 // ParseIniFile parses flags from an ini formatted file. See ParseIni for more
175 // information on the ini file foramt. The returned errors can be of the type
176 // flags.Error or flags.IniError.
177 func (p *Parser) ParseIniFile(filename string) error {
178 p.storeDefaults()
179
180 ini, err := readIniFromFile(filename)
181
182 if err != nil {
183 return err
184 }
185
186 return p.parseIni(ini)
187 }
188
189 func (p *Parser) EachGroup(cb func(int, *Group)) {
190 if p.currentCommand != nil {
191 p.currentCommand.each(0, cb)
192 } else {
193 p.eachTopLevelGroup(cb)
194 }
195 }
196
197 // ParseIni parses flags from an ini format. You can use ParseIniFile as a
198 // convenience function to parse from a filename instead of a general
199 // io.Reader.
200 //
201 // The format of the ini file is as follows:
202 //
203 // [Option group name]
204 // option = value
205 //
206 // Each section in the ini file represents an option group in the flags parser.
207 // The default flags parser option group (i.e. when using flags.Parse) is
208 // named 'Application Options'. The ini option name is matched in the following
209 // order:
210 //
211 // 1. Compared to the ini-name tag on the option struct field (if present)
212 // 2. Compared to the struct field name
213 // 3. Compared to the option long name (if present)
214 // 4. Compared to the option short name (if present)
215 //
216 // The returned errors can be of the type flags.Error or
217 // flags.IniError.
218 func (p *Parser) ParseIni(reader io.Reader) error {
219 p.storeDefaults()
220
221 ini, err := readIni(reader, "")
222
223 if err != nil {
224 return err
225 }
226
227 return p.parseIni(ini)
228 }
229
230 // WriteIniToFile writes the flags as ini format into a file. See WriteIni
231 // for more information. The returned error occurs when the specified file
232 // could not be opened for writing.
233 func (p *Parser) WriteIniToFile(filename string, options IniOptions) error {
234 file, err := os.Create(filename)
235
236 if err != nil {
237 return err
238 }
239
240 defer file.Close()
241 p.WriteIni(file, options)
242
243 return nil
244 }
245
246 // WriteIni writes the current values of all the flags to an ini format.
247 // See ParseIni for more information on the ini file format. You typically
248 // call this only after settings have been parsed since the default values of each
249 // option are stored just before parsing the flags (this is only relevant when
250 // IniIncludeDefaults is _not_ set in options).
251 func (p *Parser) WriteIni(writer io.Writer, options IniOptions) {
252 writeIni(p, writer, options)
253 }
254
255 func (p *Parser) levenshtein(s string, t string) int {
256 if len(s) == 0 {
257 return len(t)
258 }
259
260 if len(t) == 0 {
261 return len(s)
262 }
263
264 var l1, l2, l3 int
265
266 if len(s) == 1 {
267 l1 = len(t) + 1
268 } else {
269 l1 = p.levenshtein(s[1:len(s)-1], t) + 1
270 }
271
272 if len(t) == 1 {
273 l2 = len(s) + 1
274 } else {
275 l2 = p.levenshtein(t[1:len(t)-1], s) + 1
276 }
277
278 l3 = p.levenshtein(s[1:len(s)], t[1:len(t)])
279
280 if s[0] != t[0] {
281 l3 += 1
282 }
283
284 if l2 < l1 {
285 l1 = l2
286 }
287
288 if l1 < l3 {
289 return l1
290 }
291
292 return l3
293 }
294
295 func (p *Parser) closest(cmd string, commands []string) (string, int) {
296 if len(commands) == 0 {
297 return "", 0
298 }
299
300 mincmd := -1
301 mindist := -1
302
303 for i, c := range commands {
304 l := p.levenshtein(cmd, c)
305
306 if mincmd < 0 || l < mindist {
307 mindist = l
308 mincmd = i
309 }
310 }
311
312 return commands[mincmd], mindist
313 }
314
315 // ParseArgs parses the command line arguments according to the option groups that
316 // were added to the parser. On successful parsing of the arguments, the
317 // remaining, non-option, arguments (if any) are returned. The returned error
318 // indicates a parsing error and can be used with PrintError to display
319 // contextual information on where the error occurred exactly.
320 //
321 // When the common help group has been added (AddHelp) and either -h or --help
322 // was specified in the command line arguments, a help message will be
323 // automatically printed. Furthermore, the special error type ErrHelp is returned.
324 // It is up to the caller to exit the program if so desired.
325 func (p *Parser) ParseArgs(args []string) ([]string, error) {
326 ret := make([]string, 0, len(args))
327 i := 0
328
329 p.storeDefaults()
330
331 if (p.Options & HelpFlag) != None {
332 var showHelp = func() error {
333 var b bytes.Buffer
334 p.WriteHelp(&b)
335 return newError(ErrHelp, b.String())
336 }
337
338 // Windows CLI applications typically use /? for help while
339 // POSIX typically uses -h and --help. Get a help group
340 // appropriate to the OS.
341 helpgrp := newHelpGroup(showHelp)
342
343 // Append the help group to toplevel
344 p.Groups = append([]*Group{helpgrp}, p.Groups...)
345
346 // Also append the help group to every command
347 p.Commander.EachCommand(func(command string, grp *Group) {
348 grp.EmbeddedGroups = append([]*Group{helpgrp}, grp.EmbeddedGroups...)
349 })
350
351 p.Options &^= HelpFlag
352 }
353
354 required := make(map[*Option]struct{})
355 commands := make(map[string]*Group)
356
357 for command, subgroup := range p.Commands {
358 commands[command] = subgroup
359 }
360
361 // Mark required arguments in a map
362 for _, group := range p.Groups {
363 for _, option := range group.Options {
364 if option.Required {
365 required[option] = struct{}{}
366 }
367 }
368
369 // Initial set of commands
370 for command, subgroup := range group.Commands {
371 commands[command] = subgroup
372 }
373 }
374
375 for i < len(args) {
376 arg := args[i]
377 i++
378
379 // When PassDoubleDash is set and we encounter a --, then
380 // simply append all the rest as arguments and break out
381 if (p.Options&PassDoubleDash) != None && arg == "--" {
382 ret = append(ret, args[i:]...)
383 break
384 }
385
386 // If the argument is not an option then
387 // 1) Check for subcommand
388 // 2) Append it to the rest if subcommand is not found
389 if !argumentIsOption(arg) {
390 if cmdgroup := commands[arg]; cmdgroup != nil {
391 // Set current 'root' group
392 p.currentCommand = cmdgroup
393
394 p.currentCommandString = append(p.currentCommandString,
395 arg)
396
397 commands = cmdgroup.Commands
398 } else {
399 if (p.Options & PassAfterNonOption) != None {
400 ret = append(ret, args[(i-1):]...)
401 break
402 } else {
403 ret = append(ret, arg)
404 }
405 }
406
407 continue
408 }
409
410 var err error
411 var option *Option
412
413 optname, argument := splitOption(arg)
414 optname, islong := stripOptionPrefix(optname)
415 if islong {
416 err, i, option = p.parseLong(args, optname, argument, i)
417 } else {
418 for j, c := range optname {
419 clen := utf8.RuneLen(c)
420 islast := (j+clen == len(optname))
421
422 if !islast && argument == nil {
423 rr := optname[j+clen:]
424 next, _ := utf8.DecodeRuneInString(rr)
425 info, _ := p.getShort(c)
426
427 if info != nil && info.canArgument() {
428 if snext, _ := p.getShort(next); snext == nil {
429 // Consider the next stuff as an argument
430 argument = &rr
431 islast = true
432 }
433 }
434 }
435
436 err, i, option = p.parseShort(args, c, islast, argument, i)
437
438 if err != nil || islast {
439 break
440 }
441 }
442 }
443
444 if err != nil {
445 ignoreUnknown := (p.Options & IgnoreUnknown) != None
446
447 parseErr, ok := err.(*Error)
448 if !ok {
449 parseErr = newError(ErrUnknown, err.Error())
450 }
451
452 if ignoreUnknown {
453 ret = append(ret, arg)
454 }
455
456 if !(parseErr.Type == ErrUnknownFlag && ignoreUnknown) {
457 if (p.Options & PrintErrors) != None {
458 if parseErr.Type == ErrHelp {
459 fmt.Fprintln(os.Stderr, err)
460 } else {
461 fmt.Fprintf(os.Stderr, "Flags error: %s\n", err.Error())
462 }
463 }
464
465 return nil, wrapError(err)
466 }
467 } else {
468 delete(required, option)
469 }
470 }
471
472 if len(required) > 0 {
473 names := make([]string, 0, len(required))
474
475 for k, _ := range required {
476 names = append(names, "`"+k.String()+"'")
477 }
478
479 var msg string
480
481 if len(names) == 1 {
482 msg = fmt.Sprintf("the required flag %s was not specified", names[0])
483 } else {
484 msg = fmt.Sprintf("the required flags %s and %s were not specified",
485 strings.Join(names[:len(names)-1], ", "), names[len(names)-1])
486 }
487
488 err := newError(ErrRequired, msg)
489
490 if (p.Options & PrintErrors) != None {
491 fmt.Fprintln(os.Stderr, err)
492 }
493
494 return nil, err
495 }
496
497 if p.currentCommand != nil {
498 // Execute group
499 cmd, ok := p.currentCommand.data.(Command)
500
501 if ok {
502 err := cmd.Execute(ret)
503
504 if err != nil && (p.Options&PrintErrors) != None {
505 fmt.Fprintln(os.Stderr, err)
506 }
507
508 return nil, err
509 }
510 } else if len(commands) != 0 {
511 cmdnames := make([]string, 0, len(commands))
512
513 for k, _ := range commands {
514 cmdnames = append(cmdnames, k)
515 }
516
517 sort.Strings(cmdnames)
518 var msg string
519
520 if len(ret) != 0 {
521 c, l := p.closest(ret[0], cmdnames)
522 msg = fmt.Sprintf("Unknown command `%s'", ret[0])
523
524 if float32(l)/float32(len(c)) < 0.5 {
525 msg = fmt.Sprintf("%s, did you mean `%s'?", msg, c)
526 } else {
527 msg = fmt.Sprintf("%s. Please specify one command of: %s",
528 msg,
529 strings.Join(cmdnames, ", "))
530 }
531 } else {
532 msg = fmt.Sprintf("Please specify one command of: %s", strings.Join(cmdnames, ", "))
533 }
534
535 err := newError(ErrRequired, msg)
536
537 if (p.Options & PrintErrors) != None {
538 fmt.Fprintln(os.Stderr, msg)
539 }
540
541 return nil, err
542 }
543
544 return ret, nil
545 }