Documentation
¶
Overview ¶
Package getoptions - Go option parser inspired on the flexibility of Perl’s GetOpt::Long.
It will operate on any given slice of strings and return the remaining (non used) command line arguments. This allows to easily subcommand.
Usage ¶
The following is a basic example:
import "github.com/DavidGamba/go-getoptions" // As getoptions // Declare the GetOptions object opt := getoptions.New() // Use methods that return pointers bp := opt.Bool("bp", false) sp := opt.String("sp", "") ip := opt.Int("ip", 0) // Use methods by passing pointers var b bool var s string var i int opt.BoolVar(&b, "b", true, "alias", "alias2") // Aliases can be defined opt.StringVar(&s, "s", "") opt.IntVar(&i, "i", 456) // Parse cmdline arguments or any provided []string remaining, err := opt.Parse(os.Args[1:]) if *bp { // ... do something } if opt.Called("i") { // ... do something with i } // Use subcommands by operating on the remaining items // Requires `opt.SetRequireOrder()` before the initial `opt.Parse` call. opt2 := getoptions.New() // ... remaining2, err := opt.Parse(remaining)
Features ¶
• Allow passing options and non-options in any order.
• Support for `--long` options.
• Support for short (`-s`) options with flexible behaviour (see https://github.com/DavidGamba/go-getoptions#operation_modes for details):
- Normal (default)
- Bundling
- SingleDash
• Boolean, String, Int and Float64 type options.
• Multiple aliases for the same option. e.g. `help`, `man`.
• Negatable Boolean options. For example: `--verbose`, `--no-verbose` or `--noverbose`.
• Options with Array arguments. The same option can be used multiple times with different arguments. The list of arguments will be saved into an Array like structure inside the program.
• Options with array arguments and multiple entries.
• When using integer array options with multiple arguments, positive integer ranges are allowed. For example: `1..3` to indicate `1 2 3`.
• Options with key value arguments and multiple entries.
• Options with Key Value arguments. This allows the same option to be used multiple times with arguments of key value type. For example: `rpmbuild --define name=myrpm --define version=123`.
• Supports passing `--` to stop parsing arguments (everything after will be left in the `remaining []string`).
• Supports subcommands (stop parsing arguments when non option is passed).
• Supports command line options with '='. For example: You can use `--string=mystring` and `--string mystring`.
• Allows passing arguments to options that start with dash `-` when passed after equal. For example: `--string=--hello` and `--int=-123`.
• Options with optional arguments. If the default argument is not passed the default is set.
• Allows abbreviations when the provided option is not ambiguous.
• Called method indicates if the option was passed on the command line.
• Errors exposed as public variables to allow overriding them for internationalization.
• Multiple ways of managing unknown options:
- Fail on unknown (default).
- Warn on unknown.
- Pass through, allows for subcommands and can be combined with Require Order.
• Require order: Allows for subcommands. Stop parsing arguments when the first non-option is found. When mixed with Pass through, it also stops parsing arguments when the first unmatched option is found.
• Support for the lonesome dash "-". To indicate, for example, when to read input from STDIO.
• Incremental options. Allows the same option to be called multiple times to increment a counter.
• Supports case sensitive options. For example, you can use `v` to define `verbose` and `V` to define `Version`.
Panic ¶
The library will panic if it finds that the programmer (not end user):
• Defined the same alias twice.
• Defined wrong min and max values for SliceMulti methods.
Example ¶
// Declare the GetOptions object opt := getoptions.New() // Use methods that return pointers bp := opt.Bool("bp", false) sp := opt.String("sp", "") ip := opt.Int("ip", 0) // Use methods by passing pointers var b bool var s string var i int opt.BoolVar(&b, "b", true, "alias", "alias2") // Aliases can be defined opt.StringVar(&s, "s", "") opt.IntVar(&i, "i", 456) // Normally you would run Parse on `os.Args[1:]`: // remaining, err := opt.Parse(os.Args[1:]) remaining, err := opt.Parse([]string{ "--bp", "word1", // Non options can be mixed with options at any place "--sp", "strValue", // Values can be separated by space "--ip=123", // Or they can be passed after an equal `=` sign "word2", "--alias", // You can use any alias to call an option "--s=string", "word3", "--", "--not-parsed", // -- indicates end of parsing }) if err != nil { fmt.Printf("ERROR: %s\n", err) } // The remaining slice holds non-options and anything after -- fmt.Printf("remaining: %v\n", remaining) if *bp { fmt.Println("*bp is true") } // In the case of Bool and BoolVar, the value when called is the negated default if !b { fmt.Println("b is false") } // Called method tells you if an option was actually called or not if opt.Called("ip") { fmt.Printf("*ip is %d\n", *ip) } fmt.Printf("*sp is %s\n", *sp) fmt.Printf("s is %s\n", s) // When the option is not called, it will have the provided default if !opt.Called("i") { fmt.Printf("i is %d\n", i) }
Output: remaining: [word1 word2 word3 --not-parsed] *bp is true b is false *ip is 123 *sp is strValue s is string i is 456
Index ¶
- Variables
- type GetOpt
- func (gopt *GetOpt) Bool(name string, def bool, aliases ...string) *bool
- func (gopt *GetOpt) BoolVar(p *bool, name string, def bool, aliases ...string)
- func (gopt *GetOpt) Called(name string) bool
- func (gopt *GetOpt) Float64(name string, def float64, aliases ...string) *float64
- func (gopt *GetOpt) Float64Var(p *float64, name string, def float64, aliases ...string)
- func (gopt *GetOpt) Increment(name string, def int, aliases ...string) *int
- func (gopt *GetOpt) IncrementVar(p *int, name string, def int, aliases ...string)
- func (gopt *GetOpt) Int(name string, def int, aliases ...string) *int
- func (gopt *GetOpt) IntOptional(name string, def int, aliases ...string) *int
- func (gopt *GetOpt) IntSlice(name string, min, max int, aliases ...string) *[]int
- func (gopt *GetOpt) IntSliceVar(p *[]int, name string, min, max int, aliases ...string)
- func (gopt *GetOpt) IntVar(p *int, name string, def int, aliases ...string)
- func (gopt *GetOpt) IntVarOptional(p *int, name string, def int, aliases ...string)
- func (gopt *GetOpt) NBool(name string, def bool, aliases ...string) *bool
- func (gopt *GetOpt) NBoolVar(p *bool, name string, def bool, aliases ...string)
- func (gopt *GetOpt) Option(name string) interface{}
- func (gopt *GetOpt) Parse(args []string) ([]string, error)
- func (gopt *GetOpt) SetMapKeysToLower()
- func (gopt *GetOpt) SetMode(mode string)
- func (gopt *GetOpt) SetRequireOrder()
- func (gopt *GetOpt) SetUnknownMode(mode string)
- func (gopt *GetOpt) String(name, def string, aliases ...string) *string
- func (gopt *GetOpt) StringMap(name string, min, max int, aliases ...string) map[string]string
- func (gopt *GetOpt) StringOptional(name string, def string, aliases ...string) *string
- func (gopt *GetOpt) StringSlice(name string, min, max int, aliases ...string) *[]string
- func (gopt *GetOpt) StringSliceVar(p *[]string, name string, min, max int, aliases ...string)
- func (gopt *GetOpt) StringVar(p *string, name, def string, aliases ...string)
- func (gopt *GetOpt) StringVarOptional(p *string, name, def string, aliases ...string)
- func (gopt *GetOpt) Stringer() string
Examples ¶
Constants ¶
This section is empty.
Variables ¶
Debug Logger instance set to `ioutil.Discard` by default. Enable debug logging by setting: `Debug.SetOutput(os.Stderr)`.
var ErrorArgumentIsNotKeyValue = "Argument error for option '%s': Should be of type 'key=value'!"
ErrorArgumentIsNotKeyValue holds the text for Map type options where the argument is not of key=value type. It has a string placeholder '%s' for the name of the option missing the argument.
var ErrorArgumentWithDash = "Missing argument for option '%s'!\n" +
"If passing arguments that start with '-' use --option=-argument"
ErrorArgumentWithDash holds the text for missing argument error in cases where the next argument looks like an option (starts with '-'). It has a string placeholder '%s' for the name of the option missing the argument.
var ErrorConvertToFloat64 = "Argument error for option '%s': Can't convert string to float64: '%s'"
ErrorConvertToFloat64 holds the text for Float64 Coversion argument error. It has two string placeholders ('%s'). The first one for the name of the option with the wrong argument and the second one for the argument that could not be converted.
var ErrorConvertToInt = "Argument error for option '%s': Can't convert string to int: '%s'"
ErrorConvertToInt holds the text for Int Coversion argument error. It has two string placeholders ('%s'). The first one for the name of the option with the wrong argument and the second one for the argument that could not be converted.
var ErrorMissingArgument = "Missing argument for option '%s'!"
ErrorMissingArgument holds the text for missing argument error. It has a string placeholder '%s' for the name of the option missing the argument.
var MessageOnUnknown = "Unknown option '%s'"
MessageOnUnknown holds the text for the unknown option message. It has a string placeholder '%s' for the name of the option missing the argument.
Functions ¶
This section is empty.
Types ¶
type GetOpt ¶
type GetOpt struct { Writer io.Writer // io.Writer locations to write warnings to. Defaults to os.Stderr. // contains filtered or unexported fields }
GetOpt - main object.
func New ¶
func New() *GetOpt
New returns an empty object of type GetOpt. This is the starting point when using go-getoptions. For example:
opt := getoptions.New()
func (*GetOpt) Bool ¶
Bool - define a `bool` option and its aliases. It returnns a `*bool` pointing to the variable holding the result. If the option is found, the result will be the opposite of the provided default.
func (*GetOpt) BoolVar ¶
BoolVar - define a `bool` option and its aliases. The result will be available through the variable marked by the given pointer. If the option is found, the result will be the opposite of the provided default.
func (*GetOpt) Called ¶
Called - Indicates if the option was passed on the command line. If the `name` is an option that wasn't declared it will return false.
func (*GetOpt) Float64Var ¶
Float64Var - define an `float64` option and its aliases. The result will be available through the variable marked by the given pointer.
func (*GetOpt) Increment ¶
Increment - When called multiple times it increments the int counter defined by this option.
func (*GetOpt) IncrementVar ¶
IncrementVar - When called multiple times it increments the provided int.
func (*GetOpt) IntOptional ¶
IntOptional - define a `int` option and its aliases.
IntOptional will set the int to the provided default value when no value is given. For example, when called with `--intOpt 123`, the value is `123`. when called with `--intOpt` the value is the given default.
func (*GetOpt) IntSlice ¶ added in v0.11.0
IntSlice - define a `[]int` option and its aliases.
IntSlice will accept multiple calls to the same option and append them to the `[]int`. For example, when called with `--intRpt 1 --intRpt 2`, the value is `[]int{1, 2}`.
Addtionally, IntSlice will allow to define a min and max amount of arguments to be passed at once. For example, when min is 1 and max is 3 and called with `--strRpt 1 2 3`, the value is `[]int{1, 2, 3}`. It could also be called with `--strRpt 1 --strRpt 2 --strRpt 3` for the same result.
When min is bigger than 1, it is required to pass the amount of arguments defined by min at once. For example: with `min = 2`, you at least require `--strRpt 1 2 --strRpt 3`
Finally, possitive integer ranges are allowed. For example, Instead of writting: `csv --columns 1 2 3` or `csv --columns 1 --columns 2 --columns 3` The input could be: `csv --columns 1..3`.
func (*GetOpt) IntSliceVar ¶ added in v0.11.0
IntSliceVar - define a `[]int` option and its aliases.
IntSliceVar will accept multiple calls to the same option and append them to the `[]int`. For example, when called with `--intRpt 1 --intRpt 2`, the value is `[]int{1, 2}`.
Addtionally, IntSliceVar will allow to define a min and max amount of arguments to be passed at once. For example, when min is 1 and max is 3 and called with `--strRpt 1 2 3`, the value is `[]int{1, 2, 3}`. It could also be called with `--strRpt 1 --strRpt 2 --strRpt 3` for the same result.
When min is bigger than 1, it is required to pass the amount of arguments defined by min at once. For example: with `min = 2`, you at least require `--strRpt 1 2 --strRpt 3`
Finally, possitive integer ranges are allowed. For example, Instead of writting: `csv --columns 1 2 3` or `csv --columns 1 --columns 2 --columns 3` The input could be: `csv --columns 1..3`.
func (*GetOpt) IntVar ¶
IntVar - define an `int` option and its aliases. The result will be available through the variable marked by the given pointer.
func (*GetOpt) IntVarOptional ¶
IntVarOptional - define a `int` option and its aliases. The result will be available through the variable marked by the given pointer.
IntOptional will set the int to the provided default value when no value is given. For example, when called with `--intOpt 123`, the value is `123`. when called with `--intOpt` the value is the given default.
func (*GetOpt) NBool ¶
NBool - define a *Negatable* `bool` option and its aliases.
NBool automatically makes aliases with the prefix 'no' and 'no-' to the given name and aliases. If the option is found, when the argument is prefixed by 'no' (or by 'no-'), for example '--no-nflag', the value is set to the provided default. Otherwise, with a regular call, for example '--nflag', it is set to the opposite of the default.
func (*GetOpt) NBoolVar ¶
NBoolVar - define a *Negatable* `bool` option and its aliases. The result will be available through the variable marked by the given pointer.
NBoolVar automatically makes aliases with the prefix 'no' and 'no-' to the given name and aliases. If the option is found, when the argument is prefixed by 'no' (or by 'no-'), for example '--no-nflag', the value is set to the provided default. Otherwise, with a regular call, for example '--nflag', it is set to the opposite of the default.
func (*GetOpt) Option ¶
Option - Returns the value of the given option.
Type assertions are required in cases where the compiler can't determine the type by context. For example: `opt.Option("flag").(bool)`.
func (*GetOpt) Parse ¶
Parse - Call the parse method when done describing. It will operate on any given slice of strings and return the remaining (non used) command line arguments. This allows to easily subcommand.
Parsing style is controlled by the `Set` methods (SetMode, SetRequireOrder, etc).
// Declare the GetOptions object opt := getoptions.New() ... // Parse cmdline arguments or any provided []string remaining, err := opt.Parse(os.Args[1:])
func (*GetOpt) SetMapKeysToLower ¶ added in v0.11.0
func (gopt *GetOpt) SetMapKeysToLower()
SetMapKeysToLower - StringMap keys captured from StringMap are lower case. For example:
command --opt key=value
And:
command --opt KEY=value
Would both return `map[string]string{"key":"value"}`.
func (*GetOpt) SetMode ¶
SetMode - Sets the Operation Mode. The operation mode only affects options starting with a single dash '-'. The available operation modes are: normal, bundling or singleDash.
The following table shows the different operation modes given the string "-opt=arg".
.Operation Modes for string "-opt=arg" |=== |Mode |Description |normal |option: opt argument: arg |bundling |option: o argument: nil option: p argument: nil option: t argument: arg |singleDash |option: o argument: pt=arg |===
See https://github.com/DavidGamba/go-getoptions#operation_modes for more details.
func (*GetOpt) SetRequireOrder ¶
func (gopt *GetOpt) SetRequireOrder()
SetRequireOrder - Stop parsing options when a subcommand is passed. Put every remaining argument, including the subcommand, in the `remaining` slice.
A subcommand is assumed to be the first argument that is not an option or an argument to an option. When a subcommand is found, stop parsing arguments and let a subcommand handler handle the remaining arguments. For example:
command --opt arg subcommand --subopt subarg
In the example above, `--opt` is an option and `arg` is an argument to an option, making `subcommand` the first non option argument.
This method is useful when both the command and the subcommand have option handlers for the same option.
For example, with:
command --help
`--help` is handled by `command`, and with:
command subcommand --help
`--help` is not handled by `command` since there was a subcommand that caused the parsing to stop. In this case, the `remaining` slice will contain `['subcommand', '--help']` and that can be passed directly to a subcommand's option parser.
func (*GetOpt) SetUnknownMode ¶
SetUnknownMode - Determines how to behave when encountering an unknown option.
• 'fail' (default) will make 'Parse' return an error with the unknown option information.
• 'warn' will make 'Parse' print a user warning indicating there was an unknown option. The unknown option will be left in the remaining array.
• 'pass' will make 'Parse' ignore any unknown options and they will be passed onto the 'remaining' slice. This allows for subcommands.
func (*GetOpt) String ¶
String - define a `string` option and its aliases. If not called, the return value will be that of the given default `def`.
func (*GetOpt) StringMap ¶
StringMap - define a `map[string]string` option and its aliases.
StringMap will accept multiple calls of `key=value` type to the same option and add them to the `map[string]string` result. For example, when called with `--strMap k=v --strMap k2=v2`, the value is `map[string]string{"k":"v", "k2": "v2"}`.
Addtionally, StringMap will allow to define a min and max amount of arguments to be passed at once. For example, when min is 1 and max is 3 and called with `--strMap k=v k2=v2 k3=v3`, the value is `map[string]string{"k":"v", "k2": "v2", "k3": "v3"}`. It could also be called with `--strMap k=v --strMap k2=v2 --strMap k3=v3` for the same result.
When min is bigger than 1, it is required to pass the amount of arguments defined by min at once. For example: with `min = 2`, you at least require `--strMap k=v k2=v2 --strMap k3=v3`
func (*GetOpt) StringOptional ¶
StringOptional - define a `string` option and its aliases.
StringOptional will set the string to the provided default value when no value is given. For example, when called with `--strOpt value`, the value is `value`. when called with `--strOpt` the value is the given default.
func (*GetOpt) StringSlice ¶
StringSlice - define a `[]string` option and its aliases.
StringSlice will accept multiple calls to the same option and append them to the `[]string`. For example, when called with `--strRpt 1 --strRpt 2`, the value is `[]string{"1", "2"}`.
Addtionally, StringSlice will allow to define a min and max amount of arguments to be passed at once. For example, when min is 1 and max is 3 and called with `--strRpt 1 2 3`, the value is `[]string{"1", "2", "3"}`. It could also be called with `--strRpt 1 --strRpt 2 --strRpt 3` for the same result.
When min is bigger than 1, it is required to pass the amount of arguments defined by min at once. For example: with `min = 2`, you at least require `--strRpt 1 2 --strRpt 3`
func (*GetOpt) StringSliceVar ¶ added in v0.11.0
StringSliceVar - define a `[]string` option and its aliases.
StringSliceVar will accept multiple calls to the same option and append them to the `[]string`. For example, when called with `--strRpt 1 --strRpt 2`, the value is `[]string{"1", "2"}`.
Addtionally, StringSliceVar will allow to define a min and max amount of arguments to be passed at once. For example, when min is 1 and max is 3 and called with `--strRpt 1 2 3`, the value is `[]string{"1", "2", "3"}`. It could also be called with `--strRpt 1 --strRpt 2 --strRpt 3` for the same result.
When min is bigger than 1, it is required to pass the amount of arguments defined by min at once. For example: with `min = 2`, you at least require `--strRpt 1 2 --strRpt 3`
func (*GetOpt) StringVar ¶
StringVar - define a `string` option and its aliases. The result will be available through the variable marked by the given pointer. If not called, the return value will be that of the given default `def`.
func (*GetOpt) StringVarOptional ¶
StringVarOptional - define a `string` option and its aliases. The result will be available through the variable marked by the given pointer.
StringVarOptional will set the string to the provided default value when no value is given. For example, when called with `--strOpt value`, the value is `value`. when called with `--strOpt` the value is the given default.