Documentation ¶
Overview ¶
Package getopt (v2) provides traditional getopt processing for implementing commands that use traditional command lines. The standard Go flag package cannot be used to write a program that parses flags the way ls or ssh does, for example. Version 2 of this package has a simplified API.
See the github.com/pborman/options package for a simple structure based interface to this package.
USAGE ¶
Getopt supports functionality found in both the standard BSD getopt as well as (one of the many versions of) the GNU getopt_long. Being a Go package, this package makes common usage easy, but still enables more controlled usage if needed.
Typical usage:
// Declare flags and have getopt return pointers to the values. helpFlag := getopt.Bool('?', "display help") cmdFlag := getopt.StringLong("command", 'c', "default", "the command") // Declare flags against existing variables. var { fileName = "/the/default/path" timeout = time.Second * 5 verbose bool } func init() { getopt.Flag(&verbose, 'v', "be verbose") getopt.FlagLong(&fileName, "path", 0, "the path") getopt.FlagLong(&timeout, "timeout", 't', "some timeout") } func main() { // Parse the program arguments getopt.Parse() // Get the remaining positional parameters args := getopt.Args() ...
If you don't want the program to exit on error, use getopt.Getopt:
err := getopt.Getopt(nil) if err != nil { // code to handle error fmt.Fprintln(os.Stderr, err) }
FLAG SYNTAX ¶
Support is provided for both short (-f) and long (--flag) options. A single option may have both a short and a long name. Each option may be a flag or a value. A value takes an argument.
Declaring no long names causes this package to process arguments like the traditional BSD getopt.
Short flags may be combined into a single parameter. For example, "-a -b -c" may also be expressed "-abc". Long flags must stand on their own "--alpha --beta"
Values require an argument. For short options the argument may either be immediately following the short name or as the next argument. Only one short value may be combined with short flags in a single argument; the short value must be after all short flags. For example, if f is a flag and v is a value, then:
-vvalue (sets v to "value") -v value (sets v to "value") -fvvalue (sets f, and sets v to "value") -fv value (sets f, and sets v to "value") -vf value (set v to "f" and value is the first parameter)
For the long value option val:
--val value (sets val to "value") --val=value (sets val to "value") --valvalue (invalid option "valvalue")
Values with an optional value only set the value if the value is part of the same argument. In any event, the option count is increased and the option is marked as seen.
-v -f (sets v and f as being seen) -vvalue -f (sets v to "value" and sets f) --val -f (sets v and f as being seen) --val=value -f (sets v to "value" and sets f)
There is no convenience function defined for making the value optional. The SetOptional method must be called on the actual Option.
v := String("val", 'v', "", "the optional v") Lookup("v").SetOptional() var s string FlagLong(&s, "val", 'v', "the optional v).SetOptional()
Parsing continues until the first non-option or "--" is encountered.
The short name "-" can be used, but it either is specified as "-" or as part of a group of options, for example "-f-". If there are no long options specified then "--f" could also be used. If "-" is not declared as an option then the single "-" will also terminate the option processing but unlike "--", the "-" will be part of the remaining arguments.
ADVANCED USAGE ¶
Normally the parsing is performed by calling the Parse function. If it is important to see the order of the options then the Getopt function should be used. The standard Parse function does the equivalent of:
func Parse() { if err := getopt.Getopt(os.Args, nil); err != nil { fmt.Fprintln(os.Stderr, err) s.usage() os.Exit(1) }
When calling Getopt it is the responsibility of the caller to print any errors.
Normally the default option set, CommandLine, is used. Other option sets may be created with New.
After parsing, the sets Args will contain the non-option arguments. If an error is encountered then Args will begin with argument that caused the error.
It is valid to call a set's Parse a second time to amen flags or values. As an example:
var a = getopt.Bool('a', "", "The a flag") var b = getopt.Bool('b', "", "The a flag") var cmd = "" var opts = getopt.CommandLine opts.Parse(os.Args) if opts.NArgs() > 0 { cmd = opts.Arg(0) opts.Parse(opts.Args()) }
If called with set to { "prog", "-a", "cmd", "-b", "arg" } then both and and b would be set, cmd would be set to "cmd", and opts.Args() would return { "arg" }.
Unless an option type explicitly prohibits it, an option may appear more than once in the arguments. The last value provided to the option is the value.
MANDATORY OPTIONS ¶
An option marked as mandatory and not seen when parsing will cause an error to be reported such as: "program: --name is a mandatory option". An option is marked mandatory by using the Mandatory method:
getopt.FlagLong(&fileName, "path", 0, "the path").Mandatory()
Mandatory options have (required) appended to their help message:
--path=value the path (required)
MUTUALLY EXCLUSIVE OPTIONS ¶
Options can be marked as part of a mutually exclusive group. When two or more options in a mutually exclusive group are both seen while parsing then an error such as "program: options -a and -b are mutually exclusive" will be reported. Mutually exclusive groups are declared using the SetGroup method:
getopt.Flag(&a, 'a', "use method A").SetGroup("method") getopt.Flag(&a, 'b', "use method B").SetGroup("method")
A set can have multiple mutually exclusive groups. Mutually exclusive groups are identified with their group name in {}'s appeneded to their help message:
-a use method A {method} -b use method B {method}
BUILTIN TYPES ¶
The Flag and FlagLong functions support most standard Go types. For the list, see the description of FlagLong below for a list of supported types.
There are also helper routines to allow single line flag declarations. These types are: Bool, Counter, Duration, Enum, Int16, Int32, Int64, Int, List, Signed, String, Uint16, Uint32, Uint64, Uint, and Unsigned.
Each comes in a short and long flavor, e.g., Bool and BoolLong and include functions to set the flags on the standard command line or for a specific Set of flags.
Except for the Counter, Enum, Signed and Unsigned types, all of these types can be declared using Flag and FlagLong by passing in a pointer to the appropriate type.
DECLARING NEW FLAG TYPES ¶
A pointer to any type that implements the Value interface may be passed to Flag or FlagLong.
VALUEHELP ¶
All non-flag options are created with a "valuehelp" as the last parameter. Valuehelp should be 0, 1, or 2 strings. The first string, if provided, is the usage message for the option. If the second string, if provided, is the name to use for the value when displaying the usage. If not provided the term "value" is assumed.
The usage message for the option created with
StringLong("option", 'o', "defval", "a string of letters")
is
-o, -option=value StringLong("option", 'o', "defval", "a string of letters", "string")
is
-o, -option=string
Index ¶
- Constants
- Variables
- func AddOption(o Option)
- func Arg(n int) string
- func Args() []string
- func Bool(name rune, helpvalue ...string) *bool
- func BoolLong(name string, short rune, helpvalue ...string) *bool
- func Counter(name rune, helpvalue ...string) *int
- func CounterLong(name string, short rune, helpvalue ...string) *int
- func Duration(name rune, value time.Duration, helpvalue ...string) *time.Duration
- func DurationLong(name string, short rune, value time.Duration, helpvalue ...string) *time.Duration
- func Enum(name rune, values []string, value string, helpvalue ...string) *string
- func EnumLong(name string, short rune, values []string, value string, helpvalue ...string) *string
- func GetCount(name interface{}) int
- func GetValue(name interface{}) string
- func Getopt(fn func(Option) bool) error
- func Int(name rune, value int, helpvalue ...string) *int
- func Int16(name rune, value int16, helpvalue ...string) *int16
- func Int16Long(name string, short rune, value int16, helpvalue ...string) *int16
- func Int32(name rune, value int32, helpvalue ...string) *int32
- func Int32Long(name string, short rune, value int32, helpvalue ...string) *int32
- func Int64(name rune, value int64, helpvalue ...string) *int64
- func Int64Long(name string, short rune, value int64, helpvalue ...string) *int64
- func IntLong(name string, short rune, value int, helpvalue ...string) *int
- func IsSet(name interface{}) bool
- func List(name rune, helpvalue ...string) *[]string
- func ListLong(name string, short rune, helpvalue ...string) *[]string
- func NArgs() int
- func Parse()
- func ParseV2()
- func PrintUsage(w io.Writer)
- func RequiredGroup(group string)
- func Reset()
- func SetParameters(parameters string)
- func SetProgram(program string)
- func SetUsage(usage func())
- func Signed(name rune, value int64, l *SignedLimit, helpvalue ...string) *int64
- func SignedLong(name string, short rune, value int64, l *SignedLimit, helpvalue ...string) *int64
- func String(name rune, value string, helpvalue ...string) *string
- func StringLong(name string, short rune, value string, helpvalue ...string) *string
- func Uint(name rune, value uint, helpvalue ...string) *uint
- func Uint16(name rune, value uint16, helpvalue ...string) *uint16
- func Uint16Long(name string, short rune, value uint16, helpvalue ...string) *uint16
- func Uint32(name rune, value uint32, helpvalue ...string) *uint32
- func Uint32Long(name string, short rune, value uint32, helpvalue ...string) *uint32
- func Uint64(name rune, value uint64, helpvalue ...string) *uint64
- func Uint64Long(name string, short rune, value uint64, helpvalue ...string) *uint64
- func UintLong(name string, short rune, value uint, helpvalue ...string) *uint
- func Unsigned(name rune, value uint64, l *UnsignedLimit, helpvalue ...string) *uint64
- func UnsignedLong(name string, short rune, value uint64, l *UnsignedLimit, helpvalue ...string) *uint64
- func Usage()
- func Visit(fn func(Option))
- func VisitAll(fn func(Option))
- type Error
- type ErrorCode
- type Option
- type Set
- func (s *Set) AddOption(o Option)
- func (s *Set) Arg(n int) string
- func (s *Set) Args() []string
- func (s *Set) Bool(name rune, helpvalue ...string) *bool
- func (s *Set) BoolLong(name string, short rune, helpvalue ...string) *bool
- func (s *Set) Counter(name rune, helpvalue ...string) *int
- func (s *Set) CounterLong(name string, short rune, helpvalue ...string) *int
- func (s *Set) Duration(name rune, value time.Duration, helpvalue ...string) *time.Duration
- func (s *Set) DurationLong(name string, short rune, value time.Duration, helpvalue ...string) *time.Duration
- func (s *Set) Enum(name rune, values []string, value string, helpvalue ...string) *string
- func (s *Set) EnumLong(name string, short rune, values []string, value string, helpvalue ...string) *string
- func (s *Set) Flag(v interface{}, short rune, helpvalue ...string) Option
- func (s *Set) FlagLong(v interface{}, long string, short rune, helpvalue ...string) Option
- func (s *Set) GetCount(name interface{}) int
- func (s *Set) GetValue(name interface{}) string
- func (s *Set) Getopt(args []string, fn func(Option) bool) (err error)
- func (s *Set) Int(name rune, value int, helpvalue ...string) *int
- func (s *Set) Int16(name rune, value int16, helpvalue ...string) *int16
- func (s *Set) Int16Long(name string, short rune, value int16, helpvalue ...string) *int16
- func (s *Set) Int32(name rune, value int32, helpvalue ...string) *int32
- func (s *Set) Int32Long(name string, short rune, value int32, helpvalue ...string) *int32
- func (s *Set) Int64(name rune, value int64, helpvalue ...string) *int64
- func (s *Set) Int64Long(name string, short rune, value int64, helpvalue ...string) *int64
- func (s *Set) IntLong(name string, short rune, value int, helpvalue ...string) *int
- func (s *Set) IsSet(name interface{}) bool
- func (s *Set) List(name rune, helpvalue ...string) *[]string
- func (s *Set) ListLong(name string, short rune, helpvalue ...string) *[]string
- func (s *Set) Lookup(name interface{}) Option
- func (s *Set) NArgs() int
- func (s *Set) Parameters() string
- func (s *Set) Parse(args []string)
- func (s *Set) PrintOptions(w io.Writer)
- func (s *Set) PrintUsage(w io.Writer)
- func (s *Set) Program() string
- func (s *Set) RequiredGroup(group string)
- func (s *Set) Reset()
- func (s *Set) SetParameters(parameters string)
- func (s *Set) SetProgram(program string)
- func (s *Set) SetUsage(usage func())
- func (s *Set) Signed(name rune, value int64, l *SignedLimit, helpvalue ...string) *int64
- func (s *Set) SignedLong(name string, short rune, value int64, l *SignedLimit, helpvalue ...string) *int64
- func (s *Set) State() State
- func (s *Set) String(name rune, value string, helpvalue ...string) *string
- func (s *Set) StringLong(name string, short rune, value string, helpvalue ...string) *string
- func (s *Set) Uint(name rune, value uint, helpvalue ...string) *uint
- func (s *Set) Uint16(name rune, value uint16, helpvalue ...string) *uint16
- func (s *Set) Uint16Long(name string, short rune, value uint16, helpvalue ...string) *uint16
- func (s *Set) Uint32(name rune, value uint32, helpvalue ...string) *uint32
- func (s *Set) Uint32Long(name string, short rune, value uint32, helpvalue ...string) *uint32
- func (s *Set) Uint64(name rune, value uint64, helpvalue ...string) *uint64
- func (s *Set) Uint64Long(name string, short rune, value uint64, helpvalue ...string) *uint64
- func (s *Set) UintLong(name string, short rune, value uint, helpvalue ...string) *uint
- func (s *Set) Unsigned(name rune, value uint64, l *UnsignedLimit, helpvalue ...string) *uint64
- func (s *Set) UnsignedLong(name string, short rune, value uint64, l *UnsignedLimit, helpvalue ...string) *uint64
- func (s *Set) UsageLine() string
- func (s *Set) Visit(fn func(Option))
- func (s *Set) VisitAll(fn func(Option))
- type SignedLimit
- type State
- type UnsignedLimit
- type Value
Constants ¶
const ( NoError = ErrorCode(iota) UnknownOption // an invalid option was encountered MissingParameter // the options parameter is missing ExtraParameter // a value was set to a long flag Invalid // attempt to set an invalid value )
const ( InProgress = State(iota) // Getopt is still running Dash // Returned on "-" DashDash // Returned on "--" EndOfOptions // End of options reached EndOfArguments // No more arguments Terminated // Terminated by callback function Failure // Terminated due to error Unknown // Indicates internal error )
Variables ¶
var CommandLine = New()
The default set of command-line options.
var DisplayWidth = 80
DisplayWidth is used to determine where to split usage long lines.
var HelpColumn = 20
HelpColumn is the maximum column position that help strings start to display at. If the option usage is too long then the help string will be displayed on the next line. For example:
-a this is the a flag -u, --under=location the u flag's usage is quite long
Functions ¶
func AddOption ¶
func AddOption(o Option)
AddOption add the option o to set CommandLine if o is not already in set CommandLine.
func Arg ¶
Arg returns the n'th command-line argument. Arg(0) is the first remaining argument after options have been processed.
func Bool ¶
Bool creates a flag option that is a bool. Bools normally do not take a value however one can be assigned by using the long form of the option:
--option=true --o=false
The value is case insensitive and one of true, false, t, f, on, off, t and 0.
func Counter ¶
Counter creates a counting flag stored as an int. Each time the option is seen while parsing the value is incremented. The value of the counter may be explicitly set by using the long form:
--counter=5 --c=5
Further instances of the option will increment from the set value.
func DurationLong ¶
func Enum ¶
Enum creates an option that can only be set to one of the enumerated strings passed in values. Passing nil or an empty slice results in an option that will always fail. If not "", value is the default value of the enum. If value is not listed in values then Enum will produce an error on standard error and then exit the program with a status of 1.
func GetCount ¶
func GetCount(name interface{}) int
GetCount returns the number of times the Option associated with name has been seen while parsing the command line arguments. Name should either be a rune (the short name) or a string (the long name).
func GetValue ¶
func GetValue(name interface{}) string
GetValue returns the final value set to the command-line Option with name. If the option has not been seen while parsing s then the default value is returned. Name should either be a rune (the short name) or a string (the long name).
func Getopt ¶
Getops returns the result of calling Getop in the default option set with the command line arguments found in os.Args. The fn function, which may be nil, is passed to Getopt.
func IsSet ¶
func IsSet(name interface{}) bool
IsSet returns true if the Option associated with name was seen while parsing the command line arguments. Name should either be a rune (the short name) or a string (the long name).
func List ¶
List creates an option that returns a slice of strings. The parameters passed are converted from a comma separated value list into a slice. Subsequent occurrences append to the list.
func Parse ¶
func Parse()
Parse calls Parse in the default option set with the command line arguments found in os.Args.
func PrintUsage ¶
PrintUsage calls PrintUsage in the default option set.
func RequiredGroup ¶ added in v2.1.0
func RequiredGroup(group string)
RequiredGroup marks the group set with Option.SetGroup as required on the command line. At least one option in the group must be seen by parse. Calling RequiredGroup with a group name that has no options will cause parsing to always fail.
func Reset ¶
func Reset()
Reset resets all the command line options to the initial state so it appears none of them have been seen.
func SetParameters ¶
func SetParameters(parameters string)
SetParameters sets the parameters string for printing the command line usage. It defaults to "[parameters ...]"
func SetProgram ¶
func SetProgram(program string)
SetProgram sets the program name to program. Normally it is determined from the zeroth command line argument (see os.Args).
func SetUsage ¶
func SetUsage(usage func())
SetUsage sets the function used by Parse to display the commands usage on error. It defaults to calling PrintUsage(os.Stderr).
func Signed ¶
func Signed(name rune, value int64, l *SignedLimit, helpvalue ...string) *int64
Signed creates an option that is stored in an int64 and is constrained by the limits pointed to by l. The Max and Min values are only used if at least one of the values are not 0. If Base is 0, the base is implied by the string's prefix: base 16 for "0x", base 8 for "0", and base 10 otherwise.
func SignedLong ¶
func String ¶
String returns a value option that stores is value as a string. The initial value of the string is passed in value.
func StringLong ¶
func Uint16Long ¶
func Uint32Long ¶
func Uint64Long ¶
func Unsigned ¶
func Unsigned(name rune, value uint64, l *UnsignedLimit, helpvalue ...string) *uint64
Unsigned creates an option that is stored in a uint64 and is constrained by the limits pointed to by l. The Max and Min values are only used if at least one of the values are not 0. If Base is 0, the base is implied by the string's prefix: base 16 for "0x", base 8 for "0", and base 10 otherwise.
func UnsignedLong ¶
Types ¶
type Error ¶
type Error struct { ErrorCode // General reason of failure. Err error // The actual error. Parameter string // Parameter passed to option, if any Name string // Option that cause error, if any }
An Error is returned by Getopt when it encounters an error.
type Option ¶
type Option interface { // Name returns the name of the option. If the option has been seen // then the last way it was referenced (short or long) is returned // otherwise if there is a short name then this will be the short name // as a string, else it will be the long name. Name() string // ShortName always returns the short name of the option, or "" if there // is no short name. The name does not include the "-". ShortName() string // LongName always returns the long name of the option, or "" if there // is no long name. The name does not include the "--". LongName() string // IsFlag returns true if Option is a flag. IsFlag() bool // Seen returns true if the flag was seen. Seen() bool // Count returns the number of times the flag was seen. Count() int // String returns the last value the option was set to. String() string // Value returns the Value of the option. Value() Value // SetOptional makes the value optional. The option and value are // always a single argument. Either --option or --option=value. In // the former case the value of the option does not change but the Set() // will return true and the value returned by Count() is incremented. // The short form is either -o or -ovalue. SetOptional returns // the Option SetOptional() Option // SetFlag makes the value a flag. Flags are boolean values and // normally do not taken a value. They are set to true when seen. // If a value is passed in the long form then it must be on, case // insensitivinsensitive, one of "true", "false", "t", "f", "on", "off", "1", "0". // SetFlag returns the Option SetFlag() Option // Reset resets the state of the option so it appears it has not // yet been seen, including resetting the value of the option // to its original default state. Reset() // Mandataory sets the mandatory flag of the option. Parse will // fail if a mandatory option is missing. Mandatory() Option // SetGroup sets the option as part of a radio group. Parse will // fail if two options in the same group are seen. SetGroup(string) Option }
An Option can be either a Flag or a Value
type Set ¶
type Set struct {
// contains filtered or unexported fields
}
func (*Set) Arg ¶
Arg returns the n'th argument. Arg(0) is the first remaining argument after options have been processed.
func (*Set) CounterLong ¶
func (*Set) DurationLong ¶
func (*Set) FlagLong ¶
FlagLong returns an Option in Set s for setting v. If long is not "" then the option has a long name, and if short is not 0, the option has a short name. v must either be of type getopt.Value or a pointer to one of the supported builtin types:
bool, string, []string int, int8, int16, int32, int64 uint, uint8, uint16, uint32, uint64 float32, float64 time.Duration
FlagLong will panic if v is not a getopt.Value or one of the supported builtin types.
The default value of the flag is the value of v at the time FlagLong is called.
func (*Set) GetCount ¶
GetCount returns the number of times the Option associated with name has been seen while parsing s's arguments. Name should either be a rune (the short name) or a string (the long name).
func (*Set) GetValue ¶
GetValue returns the final value set to the Option in s associated with name. If the option has not been seen while parsing s then the default value is returned. Name should either be a rune (the short name) or a string (the long name).
func (*Set) Getopt ¶
Parse uses Getopt to parse args using the options set for s. The first element of args is used to assign the program for s if it is not yet set. Getop calls fn, if not nil, for each option parsed.
Getopt returns nil when all options have been processed (a non-option argument was encountered, "--" was encountered, or fn returned false).
On error getopt returns a reference to an InvalidOption (which implements the error interface).
func (*Set) IsSet ¶
IsSet returns true if the Option associated with name was seen while parsing s. Name should either be a rune (the short name) or a string (the long name).
func (*Set) Lookup ¶
Lookup returns the Option associated with name in s. Name should either be a rune (the short name) or a string (the long name).
func (*Set) Parameters ¶
Parameters returns the parameters set by SetParameters on s.
func (*Set) Parse ¶
Parse uses Getopt to parse args using the options set for s. The first element of args is used to assign the program for s if it is not yet set. On error, Parse displays the error message as well as a usage message on standard error and then exits the program.
func (*Set) PrintOptions ¶
PrintOptions prints the list of options in s to w.
func (*Set) PrintUsage ¶
PrintUsage prints the usage line and set of options of set S to w.
func (*Set) RequiredGroup ¶ added in v2.1.0
RequiredGroup marks the group set with Option.SetGroup as required. At least one option in the group must be seen by parse. Calling RequiredGroup with a group name that has no options will cause parsing to always fail.
func (*Set) Reset ¶
func (s *Set) Reset()
Reset resets all the options in s to the initial state so it appears none of them have been seen.
func (*Set) SetParameters ¶
SetParameters sets the parameters string for printing the s's usage. It defaults to "[parameters ...]"
func (*Set) SetProgram ¶
SetProgram sets s's program name to program. Normally it is determined from the zeroth argument passed to Getopt or Parse.
func (*Set) SetUsage ¶
func (s *Set) SetUsage(usage func())
SetUsage sets the function used by Parse to display usage on error. It defaults to calling f.PrintUsage(os.Stderr).
func (*Set) SignedLong ¶
func (*Set) State ¶
State returns the current state of the Set s. The state is normally the reason the most recent call to Getopt returned.
func (*Set) StringLong ¶
func (*Set) Uint16Long ¶
func (*Set) Uint32Long ¶
func (*Set) Uint64Long ¶
func (*Set) UnsignedLong ¶
func (*Set) UsageLine ¶
UsageLine returns the usage line for the set s. The set's program name and parameters, if any, are not included.
type SignedLimit ¶
type UnsignedLimit ¶
type Value ¶
type Value interface { // Set converts value into the appropriate type and assigns it to the // receiver value. Option details are provided via opt (such as the // flags name). // // Set is used to reset the value of an option to its default value // (which is stored in string form internally). Set(value string, opt Option) error // String returns the value of the flag as a string. String() string }
Value is the interface to the dynamic value stored in a flag. Flags of type Value are declared using the Flag and FlagLong functions.