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.
See https://github.com/DavidGamba/go-getoptions for extra documentation details.
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
• `Called()` method indicates if the option was passed on the command line.
• Multiple aliases for the same option. e.g. `help`, `man`.
• `CalledAs()` method indicates what alias was used to call the option on the command line.
• Simple synopsis and option list automated help.
• Boolean, String, Int and Float64 type options.
• 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. For example: `color --rgb 10 20 30 --next-option`
• 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 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. For example: You can call `--int 123` which yields `123` or `--int` which yields the given default.
• Allows abbreviations when the provided option is not ambiguous. For example: An option called `build` can be called with `--b`, `--bu`, `--bui`, `--buil` and `--build` as long as there is no ambiguity. In the case of ambiguity, the shortest non ambiguous combination is required.
• 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`.
• Support indicating if an option is required and allows overriding default error message.
• Errors exposed as public variables to allow overriding them for internationalization.
• Supports subcommands (stop parsing arguments when non option is passed).
• 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.
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 ¶
package main import ( "fmt" "io" "log" "os" "github.com/DavidGamba/go-getoptions" ) var logger = log.New(io.Discard, "DEBUG: ", log.LstdFlags) func main() { // Declare the variables you want your options to update var debug bool var greetCount int var list map[string]string // Declare the GetOptions object opt := getoptions.New() // Options definition opt.Bool("help", false, opt.Alias("h", "?")) // Aliases can be defined opt.BoolVar(&debug, "debug", false) opt.IntVar(&greetCount, "greet", 0, opt.Required(), opt.Description("Number of times to greet."), // Set the automated help description opt.ArgName("number"), // Change the help synopsis arg from the default <int> to <number> ) opt.StringMapVar(&list, "list", 1, 99, opt.Description("Greeting list by language."), opt.ArgName("lang=msg"), // Change the help synopsis arg from <key=value> to <lang=msg> ) // // Parse cmdline arguments os.Args[1:] remaining, err := opt.Parse([]string{"-g", "2", "-l", "en='Hello World'", "es='Hola Mundo'"}) // Handle help before handling user errors if opt.Called("help") { fmt.Fprint(os.Stderr, opt.Help()) os.Exit(1) } // Handle user errors if err != nil { fmt.Fprintf(os.Stderr, "ERROR: %s\n\n", err) fmt.Fprint(os.Stderr, opt.Help(getoptions.HelpSynopsis)) os.Exit(1) } // Use the passed command line options... Enjoy! if debug { logger.SetOutput(os.Stderr) } logger.Printf("Unhandled CLI args: %v\n", remaining) // Use the int variable for i := 0; i < greetCount; i++ { fmt.Println("Hello World, from go-getoptions!") } // Use the map[string]string variable if len(list) > 0 { fmt.Printf("Greeting List:\n") for k, v := range list { fmt.Printf("\t%s=%s\n", k, v) } } }
Output: Hello World, from go-getoptions! Hello World, from go-getoptions! Greeting List: en='Hello World' es='Hola Mundo'
Index ¶
- Variables
- func InterruptContext() (ctx context.Context, cancel context.CancelFunc, done chan struct{})
- type CommandFn
- type GetOpt
- func (gopt *GetOpt) Alias(alias ...string) ModifyFn
- func (gopt *GetOpt) ArgName(name string) ModifyFn
- func (gopt *GetOpt) Bool(name string, def bool, fns ...ModifyFn) *bool
- func (gopt *GetOpt) BoolVar(p *bool, name string, def bool, fns ...ModifyFn)
- func (gopt *GetOpt) Called(name string) bool
- func (gopt *GetOpt) CalledAs(name string) string
- func (gopt *GetOpt) CustomCompletion(list ...string) *GetOpt
- func (gopt *GetOpt) Description(msg string) ModifyFn
- func (gopt *GetOpt) Dispatch(ctx context.Context, remaining []string) error
- func (gopt *GetOpt) Float64(name string, def float64, fns ...ModifyFn) *float64
- func (gopt *GetOpt) Float64Optional(name string, def float64, fns ...ModifyFn) *float64
- func (gopt *GetOpt) Float64Slice(name string, min, max int, fns ...ModifyFn) *[]float64
- func (gopt *GetOpt) Float64SliceVar(p *[]float64, name string, min, max int, fns ...ModifyFn)
- func (gopt *GetOpt) Float64Var(p *float64, name string, def float64, fns ...ModifyFn)
- func (gopt *GetOpt) Float64VarOptional(p *float64, name string, def float64, fns ...ModifyFn)
- func (gopt *GetOpt) GetEnv(name string) ModifyFn
- func (gopt *GetOpt) GetRequiredArg(args []string, sections ...HelpSection) (string, []string, error)
- func (gopt *GetOpt) GetRequiredArgFloat64(args []string, sections ...HelpSection) (float64, []string, error)
- func (gopt *GetOpt) GetRequiredArgInt(args []string, sections ...HelpSection) (int, []string, error)
- func (gopt *GetOpt) Help(sections ...HelpSection) string
- func (gopt *GetOpt) HelpCommand(name string, fns ...ModifyFn)
- func (gopt *GetOpt) HelpSynopsisArg(arg, description string) *GetOpt
- func (gopt *GetOpt) Increment(name string, def int, fns ...ModifyFn) *int
- func (gopt *GetOpt) IncrementVar(p *int, name string, def int, fns ...ModifyFn)
- func (gopt *GetOpt) Int(name string, def int, fns ...ModifyFn) *int
- func (gopt *GetOpt) IntOptional(name string, def int, fns ...ModifyFn) *int
- func (gopt *GetOpt) IntSlice(name string, min, max int, fns ...ModifyFn) *[]int
- func (gopt *GetOpt) IntSliceVar(p *[]int, name string, min, max int, fns ...ModifyFn)
- func (gopt *GetOpt) IntVar(p *int, name string, def int, fns ...ModifyFn)
- func (gopt *GetOpt) IntVarOptional(p *int, name string, def int, fns ...ModifyFn)
- func (gopt *GetOpt) NewCommand(name string, description string) *GetOpt
- func (gopt *GetOpt) Parse(args []string) ([]string, error)
- func (gopt *GetOpt) Required(msg ...string) ModifyFn
- func (gopt *GetOpt) Self(name string, description string) *GetOpt
- func (gopt *GetOpt) SetCalled(called bool) ModifyFn
- func (gopt *GetOpt) SetCommandFn(fn CommandFn) *GetOpt
- func (gopt *GetOpt) SetMapKeysToLower() *GetOpt
- func (gopt *GetOpt) SetMode(mode Mode) *GetOpt
- func (gopt *GetOpt) SetRequireOrder() *GetOpt
- func (gopt *GetOpt) SetUnknownMode(mode UnknownMode) *GetOpt
- func (gopt *GetOpt) SetValue(name string, value ...string) error
- func (gopt *GetOpt) String(name, def string, fns ...ModifyFn) *string
- func (gopt *GetOpt) StringMap(name string, min, max int, fns ...ModifyFn) map[string]string
- func (gopt *GetOpt) StringMapVar(m *map[string]string, name string, min, max int, fns ...ModifyFn)
- func (gopt *GetOpt) StringOptional(name, def string, fns ...ModifyFn) *string
- func (gopt *GetOpt) StringSlice(name string, min, max int, fns ...ModifyFn) *[]string
- func (gopt *GetOpt) StringSliceVar(p *[]string, name string, min, max int, fns ...ModifyFn)
- func (gopt *GetOpt) StringVar(p *string, name, def string, fns ...ModifyFn)
- func (gopt *GetOpt) StringVarOptional(p *string, name, def string, fns ...ModifyFn)
- func (gopt *GetOpt) SuggestedValues(values ...string) ModifyFn
- func (gopt *GetOpt) UnsetOptions() *GetOpt
- func (gopt *GetOpt) ValidValues(values ...string) ModifyFn
- func (gopt *GetOpt) Value(name string) interface{}
- type HelpSection
- type Mode
- type ModifyFn
- type UnknownMode
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrorHelpCalled = fmt.Errorf("help called")
ErrorHelpCalled - Indicates the help has been handled.
var ErrorNotFound = fmt.Errorf("not found")
ErrorNotFound - Generic not found error
var ErrorParsing = errors.New("")
ErrorParsing - Indicates that there was an error with cli args parsing
Logger instance set to `io.Discard` by default. Enable debug logging by setting: `Logger.SetOutput(os.Stderr)`.
var Writer io.Writer = os.Stderr // io.Writer to write warnings to. Defaults to os.Stderr.
Functions ¶
func InterruptContext ¶ added in v0.25.0
func InterruptContext() (ctx context.Context, cancel context.CancelFunc, done chan struct{})
InterruptContext - Creates a top level context that listens to os.Interrupt, syscall.SIGHUP and syscall.SIGTERM and calls the CancelFunc if the signals are triggered. When the listener finishes its work, it sends a message to the done channel.
Use:
func main() { ... ctx, cancel, done := getoptions.InterruptContext() defer func() { cancel(); <-done }()
NOTE: InterruptContext is a method to reuse gopt.Writer
Types ¶
type GetOpt ¶
type GetOpt struct {
// 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) Alias ¶ added in v0.12.0
Alias - Adds aliases to an option.
Example ¶
opt := getoptions.New() opt.Bool("help", false, opt.Alias("?")) _, _ = opt.Parse([]string{"-?"}) if opt.Called("help") { fmt.Println("help called") } if opt.CalledAs("help") == "?" { fmt.Println("help called as ?") }
Output: help called help called as ?
func (*GetOpt) ArgName ¶ added in v0.13.0
ArgName - Add an argument name to an option for use in automated help. For example, by default a string option will have a default synopsis as follows:
--host <string>
If ArgName("hostname") is used, the synopsis will read:
--host <hostname>
Example ¶
opt := getoptions.New() opt.Bool("help", false, opt.Alias("?")) opt.String("host-default", "") opt.String("host-custom", "", opt.ArgName("hostname")) _, _ = opt.Parse([]string{"-?"}) if opt.Called("help") { fmt.Println(opt.Help()) }
Output: SYNOPSIS: go-getoptions.test [--help|-?] [--host-custom <hostname>] [--host-default <string>] [<args>] OPTIONS: --help|-? (default: false) --host-custom <hostname> (default: "") --host-default <string> (default: "")
func (*GetOpt) Bool ¶
Bool - define a `bool` option and its aliases. It returns a `*bool` pointing to the variable holding the result. If the option is found, the result will be the opposite of the provided default.
Example ¶
opt := getoptions.New() opt.Bool("help", false, opt.Alias("?")) _, _ = opt.Parse([]string{"-?"}) if opt.Called("help") { fmt.Println(opt.Help()) }
Output: SYNOPSIS: go-getoptions.test [--help|-?] [<args>] OPTIONS: --help|-? (default: false)
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.
Example ¶
var help bool opt := getoptions.New() opt.BoolVar(&help, "help", false, opt.Alias("?")) _, _ = opt.Parse([]string{"-?"}) if help { fmt.Println(opt.Help()) }
Output: SYNOPSIS: go-getoptions.test [--help|-?] [<args>] OPTIONS: --help|-? (default: false)
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.
Example ¶
opt := getoptions.New() opt.Bool("help", false, opt.Alias("?")) _, _ = opt.Parse([]string{"-?"}) if opt.Called("help") { fmt.Println("help called") } if opt.CalledAs("help") == "?" { fmt.Println("help called as ?") }
Output: help called help called as ?
func (*GetOpt) CalledAs ¶ added in v0.13.0
CalledAs - Returns the alias used to call the option. Empty string otherwise.
If the `name` is an option that wasn't declared it will return an empty string.
For options that can be called multiple times, the last alias used is returned.
Example ¶
opt := getoptions.New() opt.Bool("help", false, opt.Alias("?")) _, _ = opt.Parse([]string{"-?"}) if opt.Called("help") { fmt.Println("help called") } if opt.CalledAs("help") == "?" { fmt.Println("help called as ?") }
Output: help called help called as ?
func (*GetOpt) CustomCompletion ¶ added in v0.14.0
CustomCompletion - Add a custom completion list.
func (*GetOpt) Description ¶ added in v0.13.0
Description - Add a description to an option for use in automated help.
Example ¶
opt := getoptions.New() opt.Bool("help", false, opt.Alias("?"), opt.Description("Show help.")) opt.String("hostname", "golang.org", opt.ArgName("host|IP"), opt.Description("Hostname to use.")) opt.String("user", "", opt.ArgName("user_id"), opt.Required(), opt.Description("User to login as.")) opt.HelpSynopsisArg("[<filename>]", "File with hostnames.") _, _ = opt.Parse([]string{"-?"}) if opt.Called("help") { fmt.Println(opt.Help()) }
Output: SYNOPSIS: go-getoptions.test --user <user_id> [--help|-?] [--hostname <host|IP>] [<filename>] ARGUMENTS: [<filename>] File with hostnames. REQUIRED PARAMETERS: --user <user_id> User to login as. OPTIONS: --help|-? Show help. (default: false) --hostname <host|IP> Hostname to use. (default: "golang.org")
func (*GetOpt) Dispatch ¶ added in v0.15.0
Dispatch - Handles calling commands and subcommands after the call to Parse.
Example ¶
runFn := func(ctx context.Context, opt *getoptions.GetOpt, args []string) error { fmt.Println("a, b, c, d") return nil } opt := getoptions.New() opt.NewCommand("list", "list stuff").SetCommandFn(runFn) opt.HelpCommand("help", opt.Alias("?")) remaining, err := opt.Parse([]string{"list"}) // <- argv set to call command if err != nil { fmt.Fprintf(os.Stderr, "ERROR: %s\n", err) os.Exit(1) } getoptions.Writer = os.Stdout // Print help to stdout instead of stderr for test purpose err = opt.Dispatch(context.Background(), remaining) if err != nil { if errors.Is(err, getoptions.ErrorHelpCalled) { os.Exit(1) } fmt.Fprintf(os.Stderr, "ERROR: %s\n", err) if errors.Is(err, getoptions.ErrorParsing) { fmt.Fprintf(os.Stderr, "\n"+opt.Help()) } os.Exit(1) }
Output: a, b, c, d
Example (BHelp) ¶
runFn := func(ctx context.Context, opt *getoptions.GetOpt, args []string) error { return nil } opt := getoptions.New() opt.Bool("debug", false) opt.NewCommand("list", "list stuff").SetCommandFn(runFn) opt.HelpCommand("help", opt.Alias("?"), opt.Description("Show this help")) remaining, err := opt.Parse([]string{"help"}) // <- argv set to call help if err != nil { fmt.Fprintf(os.Stderr, "ERROR: %s\n", err) os.Exit(1) } getoptions.Writer = os.Stdout // Print help to stdout instead of stderr for test purpose err = opt.Dispatch(context.Background(), remaining) if err != nil { if !errors.Is(err, getoptions.ErrorHelpCalled) { fmt.Fprintf(os.Stderr, "ERROR: %s\n", err) os.Exit(1) } }
Output: SYNOPSIS: go-getoptions.test [--debug] [--help|-?] <command> [<args>] COMMANDS: list list stuff OPTIONS: --debug (default: false) --help|-? Show this help (default: false) Use 'go-getoptions.test help <command>' for extra details.
Example (CCommandHelp) ¶
runFn := func(ctx context.Context, opt *getoptions.GetOpt, args []string) error { return nil } opt := getoptions.New() opt.Bool("debug", false) list := opt.NewCommand("list", "list stuff").SetCommandFn(runFn) list.Bool("list-opt", false) opt.HelpCommand("help", opt.Alias("?")) remaining, err := opt.Parse([]string{"help", "list"}) // <- argv set to call command help if err != nil { fmt.Fprintf(os.Stderr, "ERROR: %s\n", err) os.Exit(1) } getoptions.Writer = os.Stdout // Print help to stdout instead of stderr for test purpose err = opt.Dispatch(context.Background(), remaining) if err != nil { if !errors.Is(err, getoptions.ErrorHelpCalled) { fmt.Fprintf(os.Stderr, "ERROR: %s\n", err) os.Exit(1) } }
Output: NAME: go-getoptions.test list - list stuff SYNOPSIS: go-getoptions.test list [--debug] [--help|-?] [--list-opt] [<args>] OPTIONS: --debug (default: false) --help|-? (default: false) --list-opt (default: false)
func (*GetOpt) Float64Optional ¶ added in v0.23.0
Float64Optional - define an `float64` option and its aliases.
func (*GetOpt) Float64Slice ¶ added in v0.25.0
func (*GetOpt) Float64SliceVar ¶ added in v0.25.0
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) Float64VarOptional ¶ added in v0.23.0
Float64VarOptional - define an `float64` option and its aliases. The result will be available through the variable marked by the given pointer.
func (*GetOpt) GetEnv ¶ added in v0.18.0
GetEnv - Will read an environment variable if set. Precedence higher to lower: CLI option, environment variable, option default.
Currently, only `opt.Bool`, `opt.BoolVar`, `opt.String`, and `opt.StringVar` are supported.
When an environment variable that matches the variable from opt.GetEnv is set, opt.GetEnv will set opt.Called(name) to true and will set opt.CalledAs(name) to the name of the environment variable used. In other words, when an option is required (opt.Required is set) opt.GetEnv satisfies that requirement.
When using `opt.GetEnv` with `opt.Bool` or `opt.BoolVar`, only the words "true" or "false" are valid. They can be provided in any casing, for example: "true", "True" or "TRUE".
NOTE: Non supported option types behave with a No-Op when `opt.GetEnv` is defined.
Example ¶
os.Setenv("_AWS_PROFILE", "production") var profile string opt := getoptions.New() opt.StringVar(&profile, "profile", "default", opt.GetEnv("_AWS_PROFILE")) _, _ = opt.Parse([]string{}) fmt.Println(profile) os.Unsetenv("_AWS_PROFILE")
Output: production
func (*GetOpt) GetRequiredArg ¶ added in v0.30.0
func (gopt *GetOpt) GetRequiredArg(args []string, sections ...HelpSection) (string, []string, error)
GetRequiredArg - Get the next argument from the args list and error if it doesn't exist. By default the error will include the HelpSynopsis section but it can be overriden with the list of sections or getoptions.HelpNone.
If the arguments have been named with `opt.HelpSynopsisArg` then the error will include the argument name.
func (*GetOpt) GetRequiredArgFloat64 ¶ added in v0.30.0
func (gopt *GetOpt) GetRequiredArgFloat64(args []string, sections ...HelpSection) (float64, []string, error)
Same as GetRequiredArg but converts the argument to a float64.
func (*GetOpt) GetRequiredArgInt ¶ added in v0.30.0
func (gopt *GetOpt) GetRequiredArgInt(args []string, sections ...HelpSection) (int, []string, error)
Same as GetRequiredArg but converts the argument to an int.
func (*GetOpt) Help ¶ added in v0.13.0
func (gopt *GetOpt) Help(sections ...HelpSection) string
Help - Default help string that is composed of all available sections.
func (*GetOpt) HelpCommand ¶ added in v0.15.0
HelpCommand - Declares a help command and a help option. Additionally, it allows to define aliases to the help option.
For example:
opt.HelpCommand("help", opt.Description("show this help"), opt.Alias("?"))
NOTE: Define after all other commands have been defined.
func (*GetOpt) HelpSynopsisArg ¶ added in v0.27.0
HelpSynopsisArg - Defines the help synopsis args description. Defaults to: [<args>]
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}`.
Additionally, 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, positive integer ranges are allowed. For example, Instead of writing: `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}`.
Additionally, 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, positive integer ranges are allowed. For example, Instead of writing: `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) NewCommand ¶ added in v0.17.0
NewCommand - Returns a new GetOpt object representing a new command.
NOTE: commands must be declared after all options are declared.
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) Required ¶ added in v0.12.0
Required - Automatically return an error if the option is not called. Optionally provide a custom error message, a default error message will be used otherwise.
func (*GetOpt) Self ¶ added in v0.14.0
Self - Set a custom name and description that will show in the automated help. If name is an empty string, it will only use the description and use the name as the executable name.
func (*GetOpt) SetCalled ¶ added in v0.29.0
SetCalled - Mark the option as called using the option name. Useful when adding options to a CommandFn call from a wrapper function.
func (*GetOpt) SetCommandFn ¶ added in v0.15.0
SetCommandFn - Defines the command entry point function.
func (*GetOpt) SetMapKeysToLower ¶ added in v0.11.0
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 ¶
SetRequireOrder - Stop parsing options when an unknown entry is found. Put every remaining argument, including the unknown entry, in the `remaining` slice.
This is helpful when doing wrappers to other tools and you want to pass all options and arguments to that wrapper without relying on '--'.
An unknown entry is assumed to be the first argument that is not a known 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:
program --opt arg unknown-command --subopt subarg
In the example above, `--opt` is an option and `arg` is an argument to an option, making `unknown-command` the first non option argument.
This method is useful when both the program and the unknown-command have option handlers for the same option.
For example, with:
program --help
`--help` is handled by `program`, and with:
program unknown-command --help
`--help` is not handled by `program` since there was a unknown-command that caused the parsing to stop. In this case, the `remaining` slice will contain `['unknown-command', '--help']` and that can be send to the wrapper handling code.
NOTE: In cases when the wrapper is written as a command use `opt.UnsetOptions` instead.
func (*GetOpt) SetUnknownMode ¶
func (gopt *GetOpt) SetUnknownMode(mode UnknownMode) *GetOpt
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. TODO: Add aliases
func (*GetOpt) SetValue ¶ added in v0.30.0
SetValue - Set the value of the given option using strings as an argument.
Examples:
opt.SetValue("bool") // boolean - sets to opposite of default opt.SetValue("int", "123") // int err := opt.SetValue("float64", "x") // error because "x" is not a valid float64 opt.SetValue("slice", "a", "b", "c") // []string opt.SetValue("slice", "d", "e", "f") // Can be called multiple times for options that allow it opt.SetValue("map", "hello=world", "hola=mundo") // map[string]string
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"}`.
Additionally, 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) StringMapVar ¶ added in v0.14.0
StringMapVar - define a `map[string]string` option and its aliases.
StringMapVar 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"}`.
Additionally, StringMapVar 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"}`.
Additionally, 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"}`.
Additionally, 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.
func (*GetOpt) SuggestedValues ¶ added in v0.30.0
SuggestedValues - adds a list of suggestions to the autocompletion for the option.
func (*GetOpt) UnsetOptions ¶ added in v0.25.0
UnsetOptions - Unsets inherited options from parent program and parent commands. This is useful when writing wrappers around other commands.
NOTE: Use in combination with `opt.SetUnknownMode(getoptions.Pass)`
func (*GetOpt) ValidValues ¶ added in v0.25.0
ValidValues - adds a list of enforced valid values for the option. These are also added to the autocompletion engine.
type HelpSection ¶ added in v0.14.0
type HelpSection int
HelpSection - Indicates what portion of the help to return.
const ( HelpNone HelpSection = iota HelpName HelpSynopsis HelpCommandList HelpOptionList HelpCommandInfo )
Help Output Types
type UnknownMode ¶ added in v0.14.0
type UnknownMode int
UnknownMode - Unknown option mode
const ( Fail UnknownMode = iota Warn Pass )
Unknown option modes - Action taken when an unknown option is encountered.
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
Package dag - Lightweight Directed Acyclic Graph (DAG) Build System.
|
Package dag - Lightweight Directed Acyclic Graph (DAG) Build System. |
docs
|
|
examples
|
|
internal
|
|
completion
Package completion - provides a Tree structure that can be used to define a program's completions.
|
Package completion - provides a Tree structure that can be used to define a program's completions. |
help
Package help - internal help handling code.
|
Package help - internal help handling code. |
option
Package option - internal option struct and methods.
|
Package option - internal option struct and methods. |
sliceiterator
Package sliceiterator - builds an iterator from a slice to allow peaking for the next value.
|
Package sliceiterator - builds an iterator from a slice to allow peaking for the next value. |
Package text - User facing strings.
|
Package text - User facing strings. |