Debian Codegraph @

v2/getopt.go

raw symbols SCIP
1 // Copyright 2017 Google Inc. 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 getopt (v2) provides traditional getopt processing for implementing
6 // commands that use traditional command lines. The standard Go flag package
7 // cannot be used to write a program that parses flags the way ls or ssh does,
8 // for example. Version 2 of this package has a simplified API.
9 //
10 // See the github.com/pborman/options package for a simple structure based
11 // interface to this package.
12 //
13 // USAGE
14 //
15 // Getopt supports functionality found in both the standard BSD getopt as well
16 // as (one of the many versions of) the GNU getopt_long. Being a Go package,
17 // this package makes common usage easy, but still enables more controlled usage
18 // if needed.
19 //
20 // Typical usage:
21 //
22 // // Declare flags and have getopt return pointers to the values.
23 // helpFlag := getopt.Bool('?', "display help")
24 // cmdFlag := getopt.StringLong("command", 'c', "default", "the command")
25 //
26 // // Declare flags against existing variables.
27 // var {
28 // fileName = "/the/default/path"
29 // timeout = time.Second * 5
30 // verbose bool
31 // }
32 // func init() {
33 // getopt.Flag(&verbose, 'v', "be verbose")
34 // getopt.FlagLong(&fileName, "path", 0, "the path")
35 // getopt.FlagLong(&timeout, "timeout", 't', "some timeout")
36 // }
37 //
38 // func main() {
39 // // Parse the program arguments
40 // getopt.Parse()
41 // // Get the remaining positional parameters
42 // args := getopt.Args()
43 // ...
44 //
45 // If you don't want the program to exit on error, use getopt.Getopt:
46 //
47 // err := getopt.Getopt(nil)
48 // if err != nil {
49 // // code to handle error
50 // fmt.Fprintln(os.Stderr, err)
51 // }
52 //
53 // FLAG SYNTAX
54 //
55 // Support is provided for both short (-f) and long (--flag) options. A single
56 // option may have both a short and a long name. Each option may be a flag or a
57 // value. A value takes an argument.
58 //
59 // Declaring no long names causes this package to process arguments like the
60 // traditional BSD getopt.
61 //
62 // Short flags may be combined into a single parameter. For example, "-a -b -c"
63 // may also be expressed "-abc". Long flags must stand on their own "--alpha
64 // --beta"
65 //
66 // Values require an argument. For short options the argument may either be
67 // immediately following the short name or as the next argument. Only one short
68 // value may be combined with short flags in a single argument; the short value
69 // must be after all short flags. For example, if f is a flag and v is a value,
70 // then:
71 //
72 // -vvalue (sets v to "value")
73 // -v value (sets v to "value")
74 // -fvvalue (sets f, and sets v to "value")
75 // -fv value (sets f, and sets v to "value")
76 // -vf value (set v to "f" and value is the first parameter)
77 //
78 // For the long value option val:
79 //
80 // --val value (sets val to "value")
81 // --val=value (sets val to "value")
82 // --valvalue (invalid option "valvalue")
83 //
84 // Values with an optional value only set the value if the value is part of the
85 // same argument. In any event, the option count is increased and the option is
86 // marked as seen.
87 //
88 // -v -f (sets v and f as being seen)
89 // -vvalue -f (sets v to "value" and sets f)
90 // --val -f (sets v and f as being seen)
91 // --val=value -f (sets v to "value" and sets f)
92 //
93 // There is no convenience function defined for making the value optional. The
94 // SetOptional method must be called on the actual Option.
95 //
96 // v := String("val", 'v', "", "the optional v")
97 // Lookup("v").SetOptional()
98 //
99 // var s string
100 // FlagLong(&s, "val", 'v', "the optional v).SetOptional()
101 //
102 // Parsing continues until the first non-option or "--" is encountered.
103 //
104 // The short name "-" can be used, but it either is specified as "-" or as part
105 // of a group of options, for example "-f-". If there are no long options
106 // specified then "--f" could also be used. If "-" is not declared as an option
107 // then the single "-" will also terminate the option processing but unlike
108 // "--", the "-" will be part of the remaining arguments.
109 //
110 // ADVANCED USAGE
111 //
112 // Normally the parsing is performed by calling the Parse function. If it is
113 // important to see the order of the options then the Getopt function should be
114 // used. The standard Parse function does the equivalent of:
115 //
116 // func Parse() {
117 // if err := getopt.Getopt(os.Args, nil); err != nil {
118 // fmt.Fprintln(os.Stderr, err)
119 // s.usage()
120 // os.Exit(1)
121 // }
122 //
123 // When calling Getopt it is the responsibility of the caller to print any
124 // errors.
125 //
126 // Normally the default option set, CommandLine, is used. Other option sets may
127 // be created with New.
128 //
129 // After parsing, the sets Args will contain the non-option arguments. If an
130 // error is encountered then Args will begin with argument that caused the
131 // error.
132 //
133 // It is valid to call a set's Parse a second time to amen flags or values. As
134 // an example:
135 //
136 // var a = getopt.Bool('a', "", "The a flag")
137 // var b = getopt.Bool('b', "", "The a flag")
138 // var cmd = ""
139 //
140 // var opts = getopt.CommandLine
141 //
142 // opts.Parse(os.Args)
143 // if opts.NArgs() > 0 {
144 // cmd = opts.Arg(0)
145 // opts.Parse(opts.Args())
146 // }
147 //
148 // If called with set to { "prog", "-a", "cmd", "-b", "arg" } then both and and
149 // b would be set, cmd would be set to "cmd", and opts.Args() would return {
150 // "arg" }.
151 //
152 // Unless an option type explicitly prohibits it, an option may appear more than
153 // once in the arguments. The last value provided to the option is the value.
154 //
155 // MANDATORY OPTIONS
156 //
157 // An option marked as mandatory and not seen when parsing will cause an error
158 // to be reported such as: "program: --name is a mandatory option". An option
159 // is marked mandatory by using the Mandatory method:
160 //
161 // getopt.FlagLong(&fileName, "path", 0, "the path").Mandatory()
162 //
163 // Mandatory options have (required) appended to their help message:
164 //
165 // --path=value the path (required)
166 //
167 // MUTUALLY EXCLUSIVE OPTIONS
168 //
169 // Options can be marked as part of a mutually exclusive group. When two or
170 // more options in a mutually exclusive group are both seen while parsing then
171 // an error such as "program: options -a and -b are mutually exclusive" will be
172 // reported. Mutually exclusive groups are declared using the SetGroup method:
173 //
174 // getopt.Flag(&a, 'a', "use method A").SetGroup("method")
175 // getopt.Flag(&a, 'b', "use method B").SetGroup("method")
176 //
177 // A set can have multiple mutually exclusive groups. Mutually exclusive groups
178 // are identified with their group name in {}'s appended to their help message:
179 //
180 // -a use method A {method}
181 // -b use method B {method}
182 //
183 // BUILTIN TYPES
184 //
185 // The Flag and FlagLong functions support most standard Go types. For the
186 // list, see the description of FlagLong below for a list of supported types.
187 //
188 // There are also helper routines to allow single line flag declarations. These
189 // types are: Bool, Counter, Duration, Enum, Int16, Int32, Int64, Int, List,
190 // Signed, String, Uint16, Uint32, Uint64, Uint, and Unsigned.
191 //
192 // Each comes in a short and long flavor, e.g., Bool and BoolLong and include
193 // functions to set the flags on the standard command line or for a specific Set
194 // of flags.
195 //
196 // Except for the Counter, Enum, Signed and Unsigned types, all of these types
197 // can be declared using Flag and FlagLong by passing in a pointer to the
198 // appropriate type.
199 //
200 // DECLARING NEW FLAG TYPES
201 //
202 // A pointer to any type that implements the Value interface may be passed to
203 // Flag or FlagLong.
204 //
205 // VALUEHELP
206 //
207 // All non-flag options are created with a "valuehelp" as the last parameter.
208 // Valuehelp should be 0, 1, or 2 strings. The first string, if provided, is
209 // the usage message for the option. If the second string, if provided, is the
210 // name to use for the value when displaying the usage. If not provided the
211 // term "value" is assumed.
212 //
213 // The usage message for the option created with
214 //
215 // StringLong("option", 'o', "defval", "a string of letters")
216 //
217 // is
218 //
219 // -o, -option=value
220 //
221 // StringLong("option", 'o', "defval", "a string of letters", "string")
222 //
223 // is
224 //
225 // -o, -option=string
226 package getopt
227
228 import (
229 "fmt"
230 "io"
231 "os"
232 "path"
233 "sort"
234 "strings"
235 "time"
236 )
237
238 // stderr allows tests to capture output to standard error.
239 var stderr io.Writer = os.Stderr
240
241 // exit allows tests to capture an os.Exit call
242 var exit = os.Exit
243
244 // DisplayWidth is used to determine where to split usage long lines.
245 var DisplayWidth = 80
246
247 // HelpColumn is the maximum column position that help strings start to display
248 // at. If the option usage is too long then the help string will be displayed
249 // on the next line. For example:
250 //
251 // -a this is the a flag
252 // -u, --under=location
253 // the u flag's usage is quite long
254 var HelpColumn = 20
255
256 // PrintUsage prints the usage line and set of options of set S to w.
257 func (s *Set) PrintUsage(w io.Writer) {
258 parts := make([]string, 2, 4)
259 parts[0] = "Usage:"
260 parts[1] = s.program
261 if usage := s.UsageLine(); usage != "" {
262 parts = append(parts, usage)
263 }
264 if s.parameters != "" {
265 parts = append(parts, s.parameters)
266 }
267 fmt.Fprintln(w, strings.Join(parts, " "))
268 s.PrintOptions(w)
269 }
270
271 // UsageLine returns the usage line for the set s. The set's program name and
272 // parameters, if any, are not included.
273 func (s *Set) UsageLine() string {
274 sort.Sort(s.options)
275 flags := ""
276
277 // Build up the list of short flag names and also compute
278 // how to display the option in the longer help listing.
279 // We also keep track of the longest option usage string
280 // that is no more than HelpColumn-3 bytes (at which point
281 // we use two lines to display the help). The three
282 // is for the leading space and the two spaces before the
283 // help string.
284 for _, opt := range s.options {
285 if opt.name == "" {
286 opt.name = "value"
287 }
288 if opt.uname == "" {
289 opt.uname = opt.usageName()
290 }
291 if opt.flag && opt.short != 0 && opt.short != '-' {
292 flags += string(opt.short)
293 }
294 }
295
296 var opts []string
297
298 // The short option - is special
299 if s.shortOptions['-'] != nil {
300 opts = append(opts, "-")
301 }
302
303 // If we have a bundle of flags, add them to the list
304 if flags != "" {
305 opts = append(opts, "-"+flags)
306 }
307
308 // Now append all the long options and options that require
309 // values.
310 for _, opt := range s.options {
311 if opt.flag {
312 if opt.short != 0 {
313 continue
314 }
315 flags = "--" + opt.long
316 } else if opt.short != 0 {
317 flags = "-" + string(opt.short) + " " + opt.name
318 } else {
319 flags = "--" + string(opt.long) + " " + opt.name
320 }
321 opts = append(opts, flags)
322 }
323 flags = strings.Join(opts, "] [")
324 if flags != "" {
325 flags = "[" + flags + "]"
326 }
327 return flags
328 }
329
330 // PrintOptions prints the list of options in s to w.
331 func (s *Set) PrintOptions(w io.Writer) {
332 sort.Sort(s.options)
333 max := 4
334 for _, opt := range s.options {
335 if opt.name == "" {
336 opt.name = "value"
337 }
338 if opt.uname == "" {
339 opt.uname = opt.usageName()
340 }
341 if max < len(opt.uname) && len(opt.uname) <= HelpColumn-3 {
342 max = len(opt.uname)
343 }
344 }
345 // Now print one or more usage lines per option.
346 for _, opt := range s.options {
347 if opt.uname != "" {
348 opt.help = strings.TrimSpace(opt.help)
349 if len(opt.help) == 0 && !opt.mandatory && opt.group == "" {
350 fmt.Fprintf(w, " %s\n", opt.uname)
351 continue
352 }
353 helpMsg := opt.help
354
355 // If the default value is the known zero value
356 // then don't display it.
357 def := opt.defval
358 switch genericValue(opt.value).(type) {
359 case *bool:
360 if def == "false" {
361 def = ""
362 }
363 case *int, *int8, *int16, *int32, *int64,
364 *uint, *uint8, *uint16, *uint32, *uint64,
365 *float32, *float64:
366 if def == "0" {
367 def = ""
368 }
369 case *time.Duration:
370 if def == "0s" {
371 def = ""
372 }
373 default:
374 if opt.flag && def == "false" {
375 def = ""
376 }
377 }
378 if def != "" {
379 helpMsg += " [" + def + "]"
380 }
381 if opt.group != "" {
382 helpMsg += " {" + opt.group + "}"
383 }
384 if opt.mandatory {
385 helpMsg += " (required)"
386 }
387
388 help := strings.Split(helpMsg, "\n")
389 // If they did not put in newlines then we will insert
390 // them to keep the help messages from wrapping.
391 if len(help) == 1 {
392 help = breakup(help[0], DisplayWidth-HelpColumn)
393 }
394 if len(opt.uname) <= max {
395 fmt.Fprintf(w, " %-*s %s\n", max, opt.uname, help[0])
396 help = help[1:]
397 } else {
398 fmt.Fprintf(w, " %s\n", opt.uname)
399 }
400 for _, s := range help {
401 fmt.Fprintf(w, " %-*s %s\n", max, " ", s)
402 }
403 }
404 }
405 }
406
407 // breakup breaks s up into strings no longer than max bytes.
408 func breakup(s string, max int) []string {
409 var a []string
410
411 for {
412 // strip leading spaces
413 for len(s) > 0 && s[0] == ' ' {
414 s = s[1:]
415 }
416 // If the option is no longer than the max just return it
417 if len(s) <= max {
418 if len(s) != 0 {
419 a = append(a, s)
420 }
421 return a
422 }
423 x := max
424 for s[x] != ' ' {
425 // the first word is too long?!
426 if x == 0 {
427 x = max
428 for x < len(s) && s[x] != ' ' {
429 x++
430 }
431 if x == len(s) {
432 x--
433 }
434 break
435 }
436 x--
437 }
438 for s[x] == ' ' {
439 x--
440 }
441 a = append(a, s[:x+1])
442 s = s[x+1:]
443 }
444 }
445
446 // Parse uses Getopt to parse args using the options set for s. The first
447 // element of args is used to assign the program for s if it is not yet set. On
448 // error, Parse displays the error message as well as a usage message on
449 // standard error and then exits the program.
450 func (s *Set) Parse(args []string) {
451 if err := s.Getopt(args, nil); err != nil {
452 fmt.Fprintln(stderr, err)
453 s.usage()
454 exit(1)
455 }
456 }
457
458 // Parse uses Getopt to parse args using the options set for s. The first
459 // element of args is used to assign the program for s if it is not yet set.
460 // Getop calls fn, if not nil, for each option parsed.
461 //
462 // Getopt returns nil when all options have been processed (a non-option
463 // argument was encountered, "--" was encountered, or fn returned false).
464 //
465 // On error getopt returns a reference to an InvalidOption (which implements the
466 // error interface).
467 func (s *Set) Getopt(args []string, fn func(Option) bool) (err error) {
468 s.setState(InProgress)
469 defer func() {
470 if s.State() == InProgress {
471 switch {
472 case err != nil:
473 s.setState(Failure)
474 case len(s.args) == 0:
475 s.setState(EndOfArguments)
476 default:
477 s.setState(Unknown)
478 }
479 }
480 }()
481
482 defer func() {
483 if err == nil {
484 err = s.checkOptions()
485 }
486 }()
487 if fn == nil {
488 fn = func(Option) bool { return true }
489 }
490 if len(args) == 0 {
491 return nil
492 }
493
494 if s.program == "" {
495 s.program = path.Base(args[0])
496 }
497 args = args[1:]
498 Parsing:
499 for len(args) > 0 {
500 arg := args[0]
501 s.args = args
502 args = args[1:]
503
504 // end of options?
505 if arg == "" || arg[0] != '-' {
506 s.setState(EndOfOptions)
507 return nil
508 }
509
510 if arg == "-" {
511 goto ShortParsing
512 }
513
514 // explicitly request end of options?
515 if arg == "--" {
516 s.args = args
517 s.setState(DashDash)
518 return nil
519 }
520
521 // Long option processing
522 if len(s.longOptions) > 0 && arg[1] == '-' {
523 e := strings.IndexRune(arg, '=')
524 var value string
525 if e > 0 {
526 value = arg[e+1:]
527 arg = arg[:e]
528 }
529 opt := s.longOptions[arg[2:]]
530 // If we are processing long options then --f is -f
531 // if f is not defined as a long option.
532 // This lets you say --f=false
533 if opt == nil && len(arg[2:]) == 1 {
534 opt = s.shortOptions[rune(arg[2])]
535 }
536 if opt == nil {
537 return unknownOption(arg[2:])
538 }
539 opt.isLong = true
540 // If we require an option and did not have an =
541 // then use the next argument as an option.
542 if !opt.flag && e < 0 && !opt.optional {
543 if len(args) == 0 {
544 return missingArg(opt)
545 }
546 value = args[0]
547 args = args[1:]
548 }
549 opt.count++
550
551 if err := opt.value.Set(value, opt); err != nil {
552 return setError(opt, value, err)
553 }
554
555 if !fn(opt) {
556 s.setState(Terminated)
557 return nil
558 }
559 continue Parsing
560 }
561
562 // Short option processing
563 arg = arg[1:] // strip -
564 ShortParsing:
565 for i, c := range arg {
566 opt := s.shortOptions[c]
567 if opt == nil {
568 // In traditional getopt, if - is not registered
569 // as an option, a lone - is treated as
570 // if there were a -- in front of it.
571 if arg == "-" {
572 s.setState(Dash)
573 return nil
574 }
575 return unknownOption(c)
576 }
577 opt.isLong = false
578 opt.count++
579 var value string
580 if !opt.flag {
581 value = arg[1+i:]
582 if value == "" && !opt.optional {
583 if len(args) == 0 {
584 return missingArg(opt)
585 }
586 value = args[0]
587 args = args[1:]
588 }
589 }
590 if err := opt.value.Set(value, opt); err != nil {
591 return setError(opt, value, err)
592 }
593 if !fn(opt) {
594 s.setState(Terminated)
595 return nil
596 }
597 if !opt.flag {
598 continue Parsing
599 }
600 }
601 }
602 s.args = []string{}
603 return nil
604 }
605
606 func (s *Set) checkOptions() error {
607 groups := map[string]Option{}
608 for _, opt := range s.options {
609 if !opt.Seen() {
610 if opt.mandatory {
611 return fmt.Errorf("option %s is mandatory", opt.Name())
612 }
613 continue
614 }
615 if opt.group == "" {
616 continue
617 }
618 if opt2 := groups[opt.group]; opt2 != nil {
619 return fmt.Errorf("options %s and %s are mutually exclusive", opt2.Name(), opt.Name())
620 }
621 groups[opt.group] = opt
622 }
623 for _, group := range s.requiredGroups {
624 if groups[group] != nil {
625 continue
626 }
627 var flags []string
628 for _, opt := range s.options {
629 if opt.group == group {
630 flags = append(flags, opt.Name())
631 }
632 }
633 return fmt.Errorf("exactly one of the following options must be specified: %s", strings.Join(flags, ", "))
634 }
635 return nil
636 }