Documentation ¶
Overview ¶
Package goopt provides support for command-line processing.
It supports 3 types of flags:
Single - a flag which expects a value Chained - flag which expects a delimited value representing elements in a list (and is evaluated as a list) Standalone - a boolean flag which by default takes no value (defaults to true) but may accept a value which evaluates to true or false
Additionally, commands and sub-commands (Command) are supported. Commands can be nested to represent sub-commands. Unlike the official go.Flag package commands and sub-commands may be placed before, after or mixed in with flags.
Index ¶
- Variables
- func BindFlagToCmdLine[T Bindable](s *CmdLineOption, data *T, flag string, argument *Argument) error
- func CustomBindFlagToCmdLine[T any](s *CmdLineOption, data *T, proc ValueSetFunc, flag string, argument *Argument) error
- type Argument
- type Bindable
- type ClearConfig
- type CmdLineOption
- func (s *CmdLineOption) AcceptPattern(flag string, val PatternValue) error
- func (s *CmdLineOption) AcceptPatterns(flag string, acceptVal []PatternValue) error
- func (s *CmdLineOption) AddCommand(cmdArg *Command) error
- func (s *CmdLineOption) AddFlag(flag string, argument *Argument) error
- func (s *CmdLineOption) AddFlagPostValidationFilter(flag string, proc FilterFunc) error
- func (s *CmdLineOption) AddFlagPreValidationFilter(flag string, proc FilterFunc) error
- func (s *CmdLineOption) BindFlag(data any, flag string, argument *Argument) error
- func (s *CmdLineOption) Clear(config ClearConfig)
- func (s *CmdLineOption) ClearAll()
- func (s *CmdLineOption) CustomBindFlag(data any, proc ValueSetFunc, flag string, argument *Argument) error
- func (s *CmdLineOption) DependsOnFlag(flag, dependsOn string) error
- func (s *CmdLineOption) DependsOnFlagValue(flag, dependsOn, ofValue string) error
- func (s *CmdLineOption) DescribeFlag(flag, description string) error
- func (s *CmdLineOption) ExecuteCommands() int
- func (s *CmdLineOption) Get(flag string) (string, bool)
- func (s *CmdLineOption) GetAcceptPatterns(flag string) ([]LiterateRegex, error)
- func (s *CmdLineOption) GetArgument(flag string) (*Argument, error)
- func (s *CmdLineOption) GetBool(flag string) (bool, error)
- func (s *CmdLineOption) GetCommandExecutionError(commandName string) error
- func (s *CmdLineOption) GetCommandValue(path string) (string, error)
- func (s *CmdLineOption) GetCommandValues() []PathValue
- func (s *CmdLineOption) GetConsistencyWarnings() []string
- func (s *CmdLineOption) GetDescription(flag string) string
- func (s *CmdLineOption) GetErrorCount() int
- func (s *CmdLineOption) GetErrors() []error
- func (s *CmdLineOption) GetFloat(flag string, bitSize int) (float64, error)
- func (s *CmdLineOption) GetInt(flag string, bitSize int) (int64, error)
- func (s *CmdLineOption) GetList(flag string) ([]string, error)
- func (s *CmdLineOption) GetOptions() []KeyValue
- func (s *CmdLineOption) GetOrDefault(flag string, defaultValue string) string
- func (s *CmdLineOption) GetPositionalArgCount() int
- func (s *CmdLineOption) GetPositionalArgs() []PositionalArgument
- func (s *CmdLineOption) GetPostValidationFilter(flag string) (FilterFunc, error)
- func (s *CmdLineOption) GetPreValidationFilter(flag string) (FilterFunc, error)
- func (s *CmdLineOption) GetShortFlag(flag string) (string, error)
- func (s *CmdLineOption) GetWarnings() []string
- func (s *CmdLineOption) HasAcceptedValues(flag string) bool
- func (s *CmdLineOption) HasCommand(path string) bool
- func (s *CmdLineOption) HasFlag(flag string) bool
- func (s *CmdLineOption) HasPositionalArgs() bool
- func (s *CmdLineOption) HasPostValidationFilter(flag string) bool
- func (s *CmdLineOption) HasPreValidationFilter(flag string) bool
- func (s *CmdLineOption) Parse(args []string) bool
- func (s *CmdLineOption) ParseString(argString string) bool
- func (s *CmdLineOption) ParseStringWithDefaults(defaults map[string]string, argString string) bool
- func (s *CmdLineOption) ParseWithDefaults(defaults map[string]string, args []string) bool
- func (s *CmdLineOption) PrintCommands(writer io.Writer)
- func (s *CmdLineOption) PrintCommandsUsing(writer io.Writer, config *PrettyPrintConfig)
- func (s *CmdLineOption) PrintFlags(writer io.Writer)
- func (s *CmdLineOption) PrintUsage(writer io.Writer)
- func (s *CmdLineOption) Remove(flag string) bool
- func (s *CmdLineOption) SetArgumentPrefixes(prefixes []rune) error
- func (s *CmdLineOption) SetFlag(flag, value string)
- func (s *CmdLineOption) SetListDelimiterFunc(delimiterFunc ListDelimiterFunc) error
- func (s *CmdLineOption) SetPosix(posixCompatible bool) bool
- type Command
- type CommandFunc
- type ConfigureArgumentFunc
- func SetRequired(required bool) ConfigureArgumentFunc
- func SetRequiredIf(requiredIf RequiredIfFunc) ConfigureArgumentFunc
- func SetSecure(secure bool) ConfigureArgumentFunc
- func SetSecurePrompt(prompt string) ConfigureArgumentFunc
- func WithAcceptedValues(values []PatternValue) ConfigureArgumentFunc
- func WithDefaultValue(defaultValue string) ConfigureArgumentFunc
- func WithDependentFlags(dependencies []string) ConfigureArgumentFunc
- func WithDependentValueFlags(dependencies, values []string) ConfigureArgumentFunc
- func WithDescription(description string) ConfigureArgumentFunc
- func WithPostValidationFilter(filter FilterFunc) ConfigureArgumentFunc
- func WithPreValidationFilter(filter FilterFunc) ConfigureArgumentFunc
- func WithShortFlag(shortFlag string) ConfigureArgumentFunc
- func WithType(typeof OptionType) ConfigureArgumentFunc
- type ConfigureCmdLineFunc
- func WithArgumentPrefixes(prefixes []rune) ConfigureCmdLineFunc
- func WithBindFlag[T Bindable](flag string, bindVar *T, argument *Argument) ConfigureCmdLineFunc
- func WithCommand(command *Command) ConfigureCmdLineFunc
- func WithCustomBindFlag[T any](flag string, bindVar *T, proc ValueSetFunc, argument *Argument) ConfigureCmdLineFunc
- func WithFlag(flag string, argument *Argument) ConfigureCmdLineFunc
- func WithListDelimiterFunc(delimiterFunc ListDelimiterFunc) ConfigureCmdLineFunc
- func WithPosix(usePosix bool) ConfigureCmdLineFunc
- type ConfigureCommandFunc
- func SetCommandRequired(required bool) ConfigureCommandFunc
- func WithCallback(callback CommandFunc) ConfigureCommandFunc
- func WithCommandDefault(defaultValue string) ConfigureCommandFunc
- func WithCommandDescription(description string) ConfigureCommandFunc
- func WithName(name string) ConfigureCommandFunc
- func WithSubcommands(subcommands ...*Command) ConfigureCommandFunc
- type FilterFunc
- type KeyValue
- type ListDelimiterFunc
- type LiterateRegex
- type OptionType
- type PathValue
- type PatternValue
- type PositionalArgument
- type PrettyPrintConfig
- type RequiredIfFunc
- type Secure
- type ValueSetFunc
Constants ¶
This section is empty.
Variables ¶
var ( ErrUnsupportedTypeConversion = errors.New("unsupported type conversion") ErrCommandNotFound = errors.New("command not found") ErrFlagNotFound = errors.New("flag not found") ErrPosixIncompatible = errors.New("posix incompatible") ErrValidationFailed = errors.New("validation failed") )
Functions ¶
func BindFlagToCmdLine ¶ added in v0.5.3
func BindFlagToCmdLine[T Bindable](s *CmdLineOption, data *T, flag string, argument *Argument) error
BindFlagToCmdLine is a helper function to allow passing generics to the CmdLineOption.BindFlag method
func CustomBindFlagToCmdLine ¶ added in v0.5.3
func CustomBindFlagToCmdLine[T any](s *CmdLineOption, data *T, proc ValueSetFunc, flag string, argument *Argument) error
CustomBindFlagToCmdLine is a helper function to allow passing generics to the CmdLineOption.CustomBindFlag method
Types ¶
type Argument ¶
type Argument struct { Description string TypeOf OptionType Required bool RequiredIf RequiredIfFunc PreFilter FilterFunc PostFilter FilterFunc AcceptedValues []LiterateRegex DependsOn []string OfValue []string Secure Secure Short string DefaultValue string }
Argument defines a command-line Flag
func NewArg ¶
func NewArg(configs ...ConfigureArgumentFunc) *Argument
NewArg convenience initialization method to fluently configure flags
func NewArgument ¶
func NewArgument(shortFlag string, description string, typeOf OptionType, required bool, secure Secure, defaultValue string) *Argument
NewArgument convenience initialization method to describe Flags. Does not support fluent configuration. Use NewArg to configure Argument fluently.
type Bindable ¶ added in v0.5.3
type Bindable interface { ~string | int8 | int16 | int32 | int64 | ~int | uint8 | uint16 | uint32 | uint64 | ~uint | float32 | float64 | bool | time.Time | []string | []int8 | []int16 | []int32 | []int64 | ~[]int | []uint8 | []uint16 | []uint32 | []uint64 | ~[]uint | []float32 | []float64 | []bool | []time.Time }
type ClearConfig ¶
type ClearConfig struct { // KeepOptions: keep key/value options seen on command line KeepOptions bool // KeepErrors: keep errors generated during previous Parse KeepErrors bool // KeepAcceptedValues: keep value guards KeepAcceptedValues bool // KeepFilters: Keep filters set during previous configuration KeepFilters bool // KeepCommands: keep key/value commands seen on command line KeepCommands bool // KeepPositional: keep positional arguments seen on command line // a positional argument is defined as anything passed on the command-line // which was not processed as either a flag, a flag value, a command // or a command value KeepPositional bool }
ClearConfig allows to selectively clear a set of CmdLineOption configuration data
type CmdLineOption ¶
type CmdLineOption struct {
// contains filtered or unexported fields
}
CmdLineOption opaque struct used in all Flag/Command manipulation
func NewCmdLine ¶
func NewCmdLine(configs ...ConfigureCmdLineFunc) (*CmdLineOption, error)
NewCmdLine allows fluent initialization of CmdLineOption. The caller should always test for error on return because CmdLineOption will be nil when an error occurs during initialization.
Examples of fluent configuration:
cmdLine, err := NewCmdLine( WithFlag("flagWithValue", NewArg( WithShortFlag("fw"), WithType(Single), WithDescription("this flag requires a value"), WithDependentFlags([]string{"flagA", "flagB"}), SetRequired(true))), WithFlag("flagA", NewArg( WithShortFlag("fa"), WithType(Standalone))), WithFlag("flagB", NewArg( WithShortFlag("fb"), WithDescription("This is flag B - flagWithValue depends on it"), WithDefaultValue("db"), WithType(Single))), WithFlag("flagC", NewArg( WithShortFlag("fc"), WithDescription("this is flag C - it's a chained flag which can return a list"), WithType(Chained))))
func NewCmdLineOption ¶
func NewCmdLineOption() *CmdLineOption
NewCmdLineOption convenience initialization method. Does not support fluent configuration. Use NewCmdLine to configure CmdLineOption fluently.
func (*CmdLineOption) AcceptPattern ¶ added in v0.0.8
func (s *CmdLineOption) AcceptPattern(flag string, val PatternValue) error
AcceptPattern is used to define an acceptable value for a Flag. The 'pattern' argument is compiled to a regular expression and the description argument is used to provide a human-readable description of the pattern. Returns an error if the regular expression cannot be compiled or if the Flag does not support values (Standalone). Example:
a Flag which accepts only whole numbers could be defined as: AcceptPattern("times", PatternValue{Pattern: `^[\d]+`, Description: "Please supply a whole number"}).
func (*CmdLineOption) AcceptPatterns ¶ added in v0.0.8
func (s *CmdLineOption) AcceptPatterns(flag string, acceptVal []PatternValue) error
AcceptPatterns same as PatternValue but acts on a list of patterns and descriptions. When specified, the patterns defined in AcceptPatterns represent a set of values, of which one must be supplied on the command-line. The patterns are evaluated on Parse, if no command-line options match one of the PatternValue, Parse returns false.
func (*CmdLineOption) AddCommand ¶
func (s *CmdLineOption) AddCommand(cmdArg *Command) error
AddCommand used to define a Command/sub-command chain Unlike a flag which starts with a '-' or '/' a Command represents a verb or action
func (*CmdLineOption) AddFlag ¶
func (s *CmdLineOption) AddFlag(flag string, argument *Argument) error
AddFlag used to define a Flag - a Flag represents a command line option as a "long" and optional "short" form which is prefixed by '-', '--' or '/'.
func (*CmdLineOption) AddFlagPostValidationFilter ¶ added in v0.0.7
func (s *CmdLineOption) AddFlagPostValidationFilter(flag string, proc FilterFunc) error
AddFlagPostValidationFilter adds a filter (user-defined transform/evaluate function) which is called on the Flag value during Parse *after* AcceptedValues are checked
func (*CmdLineOption) AddFlagPreValidationFilter ¶ added in v0.0.7
func (s *CmdLineOption) AddFlagPreValidationFilter(flag string, proc FilterFunc) error
AddFlagPreValidationFilter adds a filter (user-defined transform/evaluate function) which is called on the Flag value during Parse *before* AcceptedValues are checked
func (*CmdLineOption) BindFlag ¶
func (s *CmdLineOption) BindFlag(data any, flag string, argument *Argument) error
BindFlag is used to bind a *pointer* to string, int, uint, bool, float or time.Time scalar or slice variable with a Flag which is set when Parse is invoked. An error is returned if data cannot be bound - for compile-time safety use BindFlagToCmdLine instead
func (*CmdLineOption) Clear ¶
func (s *CmdLineOption) Clear(config ClearConfig)
Clear can be used to selectively clear sensitive options or when re-defining options on the fly.
func (*CmdLineOption) ClearAll ¶
func (s *CmdLineOption) ClearAll()
ClearAll clears all parsed options and commands as well as filters and acceptedValues (guards). Configured flags and registered commands are not cleared. Use this when parsing a command line repetitively.
func (*CmdLineOption) CustomBindFlag ¶
func (s *CmdLineOption) CustomBindFlag(data any, proc ValueSetFunc, flag string, argument *Argument) error
CustomBindFlag works like BindFlag but expects a ValueSetFunc callback which is called when a Flag is evaluated on Parse. When the Flag is seen on the command like the ValueSetFunc is called with the user-supplied value. Allows binding complex structures not supported by BindFlag
func (*CmdLineOption) DependsOnFlag ¶
func (s *CmdLineOption) DependsOnFlag(flag, dependsOn string) error
DependsOnFlag same as DependsOnFlagValue but does not specify that the Flag it depends on must have a particular value to be valid.
func (*CmdLineOption) DependsOnFlagValue ¶
func (s *CmdLineOption) DependsOnFlagValue(flag, dependsOn, ofValue string) error
DependsOnFlagValue is used to describe flag dependencies. For example, a '--modify' flag could be specified to depend on a '--group' Flag with a value of 'users'. If the '--group' Flag is not specified with a value of 'users' on the command line a warning will be set during Parse.
func (*CmdLineOption) DescribeFlag ¶
func (s *CmdLineOption) DescribeFlag(flag, description string) error
DescribeFlag is used to provide a description of a Flag
func (*CmdLineOption) ExecuteCommands ¶
func (s *CmdLineOption) ExecuteCommands() int
ExecuteCommands command callbacks are placed on a FIFO queue during parsing until ExecuteCommands is called. Returns the count of errors encountered during execution.
func (*CmdLineOption) Get ¶
func (s *CmdLineOption) Get(flag string) (string, bool)
Get returns a combination of a Flag's value as string and true if found. Returns an empty string and false otherwise
func (*CmdLineOption) GetAcceptPatterns ¶ added in v0.0.8
func (s *CmdLineOption) GetAcceptPatterns(flag string) ([]LiterateRegex, error)
GetAcceptPatterns takes a flag string and returns an error if the flag does not exist, a slice of LiterateRegex otherwise
func (*CmdLineOption) GetArgument ¶ added in v0.0.8
func (s *CmdLineOption) GetArgument(flag string) (*Argument, error)
GetArgument returns the Argument corresponding to the long or short flag or an error when not found
func (*CmdLineOption) GetBool ¶
func (s *CmdLineOption) GetBool(flag string) (bool, error)
GetBool attempts to convert the string value of a Flag to boolean.
func (*CmdLineOption) GetCommandExecutionError ¶
func (s *CmdLineOption) GetCommandExecutionError(commandName string) error
GetCommandExecutionError returns the error which occurred during execution of a command callback after ExecuteCommands has been called. Returns nil on no error. Returns a CommandNotFound error when no callback is associated with commandName
func (*CmdLineOption) GetCommandValue ¶
func (s *CmdLineOption) GetCommandValue(path string) (string, error)
GetCommandValue returns the value of a command path if found. Example:
in the structure Command{Name : "Test", Subcommands: []Command{{Name: "User"}}} the path to User would be expressed as "Test User"
func (*CmdLineOption) GetCommandValues ¶
func (s *CmdLineOption) GetCommandValues() []PathValue
GetCommandValues returns the list of all commands seen on command-line
func (*CmdLineOption) GetConsistencyWarnings ¶
func (s *CmdLineOption) GetConsistencyWarnings() []string
GetConsistencyWarnings is a helper function which provides information about eventual option consistency warnings. It is intended for users of the library rather than for end-users
func (*CmdLineOption) GetDescription ¶
func (s *CmdLineOption) GetDescription(flag string) string
GetDescription retrieves a Flag's description as set by DescribeFlag
func (*CmdLineOption) GetErrorCount ¶
func (s *CmdLineOption) GetErrorCount() int
GetErrorCount is greater than zero when errors were encountered during Parse.
func (*CmdLineOption) GetErrors ¶
func (s *CmdLineOption) GetErrors() []error
GetErrors returns a list of the errors encountered during Parse
func (*CmdLineOption) GetFloat ¶
func (s *CmdLineOption) GetFloat(flag string, bitSize int) (float64, error)
GetFloat attempts to convert the string value of a Flag to a float64
func (*CmdLineOption) GetInt ¶
func (s *CmdLineOption) GetInt(flag string, bitSize int) (int64, error)
GetInt attempts to convert the string value of a Flag to an int64.
func (*CmdLineOption) GetList ¶
func (s *CmdLineOption) GetList(flag string) ([]string, error)
GetList attempts to split the string value of a Chained Flag to a string slice by default the value is split on '|', ',' or ' ' delimiters
func (*CmdLineOption) GetOptions ¶
func (s *CmdLineOption) GetOptions() []KeyValue
GetOptions returns a slice of KeyValue pairs which have been supplied on the command-line.
func (*CmdLineOption) GetOrDefault ¶
func (s *CmdLineOption) GetOrDefault(flag string, defaultValue string) string
GetOrDefault returns the value of a defined Flag or defaultValue if no value is set
func (*CmdLineOption) GetPositionalArgCount ¶
func (s *CmdLineOption) GetPositionalArgCount() int
GetPositionalArgCount TODO explain
func (*CmdLineOption) GetPositionalArgs ¶
func (s *CmdLineOption) GetPositionalArgs() []PositionalArgument
GetPositionalArgs TODO explain
func (*CmdLineOption) GetPostValidationFilter ¶ added in v0.0.7
func (s *CmdLineOption) GetPostValidationFilter(flag string) (FilterFunc, error)
GetPostValidationFilter retrieve Flag transform/evaluate function which is called on Parse after checking for acceptable values
func (*CmdLineOption) GetPreValidationFilter ¶ added in v0.0.7
func (s *CmdLineOption) GetPreValidationFilter(flag string) (FilterFunc, error)
GetPreValidationFilter retrieve Flag transform/evaluate function which is called on Parse before checking for acceptable values
func (*CmdLineOption) GetShortFlag ¶
func (s *CmdLineOption) GetShortFlag(flag string) (string, error)
GetShortFlag maps a long flag to its equivalent short flag. Short flags are concise alternatives to their verbose counterparts.
The function returns the corresponding short flag if it exists. If not, it returns an error indicating that no short flag is defined for the provided long flag.
Params: flag (string): The long flag for which the function should retrieve the corresponding short flag.
Returns: string: The short flag variant if it exists. error: An error if no short flag is defined for the provided long flag, or if any other error occurs.
func (*CmdLineOption) GetWarnings ¶
func (s *CmdLineOption) GetWarnings() []string
GetWarnings returns a string slice of all warnings (non-fatal errors) - a warning is set when optional dependencies are not met - for instance, specifying the value of a Flag which relies on a missing argument
func (*CmdLineOption) HasAcceptedValues ¶
func (s *CmdLineOption) HasAcceptedValues(flag string) bool
HasAcceptedValues returns true when a Flag defines a set of valid values it will accept
func (*CmdLineOption) HasCommand ¶
func (s *CmdLineOption) HasCommand(path string) bool
HasCommand return true when the name has been seen on the command line.
func (*CmdLineOption) HasFlag ¶
func (s *CmdLineOption) HasFlag(flag string) bool
HasFlag returns true when the Flag has been seen on the command line.
func (*CmdLineOption) HasPositionalArgs ¶
func (s *CmdLineOption) HasPositionalArgs() bool
HasPositionalArgs TODO explain
func (*CmdLineOption) HasPostValidationFilter ¶ added in v0.0.7
func (s *CmdLineOption) HasPostValidationFilter(flag string) bool
HasPostValidationFilter returns true when an option has a transform/evaluate function which is called on Parse after checking for acceptable values
func (*CmdLineOption) HasPreValidationFilter ¶ added in v0.0.7
func (s *CmdLineOption) HasPreValidationFilter(flag string) bool
HasPreValidationFilter returns true when an option has a transform/evaluate function which is called on Parse before checking for acceptable values
func (*CmdLineOption) Parse ¶
func (s *CmdLineOption) Parse(args []string) bool
Parse this function should be called on os.Args (or a user-defined array of arguments). Returns true when user command line arguments match the defined Flag and Command rules
func (*CmdLineOption) ParseString ¶
func (s *CmdLineOption) ParseString(argString string) bool
ParseString calls Parse
func (*CmdLineOption) ParseStringWithDefaults ¶
func (s *CmdLineOption) ParseStringWithDefaults(defaults map[string]string, argString string) bool
ParseStringWithDefaults calls Parse supplementing missing arguments in argString with default values from defaults
func (*CmdLineOption) ParseWithDefaults ¶
func (s *CmdLineOption) ParseWithDefaults(defaults map[string]string, args []string) bool
ParseWithDefaults calls Parse supplementing missing arguments in args array with default values from defaults
func (*CmdLineOption) PrintCommands ¶
func (s *CmdLineOption) PrintCommands(writer io.Writer)
PrintCommands writes the list of accepted Command structs to io.Writer.
func (*CmdLineOption) PrintCommandsUsing ¶
func (s *CmdLineOption) PrintCommandsUsing(writer io.Writer, config *PrettyPrintConfig)
PrintCommandsUsing writes the list of accepted Command structs to io.Writer using PrettyPrintConfig. PrettyPrintConfig.NewCommandPrefix precedes the start of a new command PrettyPrintConfig.DefaultPrefix precedes sub-commands by default PrettyPrintConfig.TerminalPrefix precedes terminal, i.e. Command structs which don't have sub-commands PrettyPrintConfig.LevelBindPrefix is used for indentation. The indentation is repeated for each Level under the
command root. The Command root is at Level 0.
func (*CmdLineOption) PrintFlags ¶
func (s *CmdLineOption) PrintFlags(writer io.Writer)
PrintFlags pretty prints accepted command-line switches to io.Writer
func (*CmdLineOption) PrintUsage ¶
func (s *CmdLineOption) PrintUsage(writer io.Writer)
PrintUsage pretty prints accepted Flags and Commands to io.Writer.
func (*CmdLineOption) Remove ¶
func (s *CmdLineOption) Remove(flag string) bool
Remove used to remove a defined-flag at runtime - returns false if the Flag was not found and true on removal.
func (*CmdLineOption) SetArgumentPrefixes ¶
func (s *CmdLineOption) SetArgumentPrefixes(prefixes []rune) error
func (*CmdLineOption) SetFlag ¶
func (s *CmdLineOption) SetFlag(flag, value string)
SetFlag is used to re-define a Flag or define a new Flag at runtime. This can be sometimes useful for dynamic evaluation of combinations of options and values which can't be expressed statically. For instance, when the user should supply these during a program's execution but after command-line options have been parsed.
func (*CmdLineOption) SetListDelimiterFunc ¶
func (s *CmdLineOption) SetListDelimiterFunc(delimiterFunc ListDelimiterFunc) error
SetListDelimiterFunc TODO explain
func (*CmdLineOption) SetPosix ¶
func (s *CmdLineOption) SetPosix(posixCompatible bool) bool
type Command ¶
type Command struct { Name string Subcommands []Command Callback CommandFunc Description string DefaultValue string Required bool // contains filtered or unexported fields }
Command defines commands and sub-commands
func NewCommand ¶
func NewCommand(configs ...ConfigureCommandFunc) *Command
NewCommand creates and returns a new Command object. This function takes variadic `ConfigureCommandFunc` functions to customize the created command.
type CommandFunc ¶
type CommandFunc func(cmdLine *CmdLineOption, command *Command, value string) error
CommandFunc callback - optionally specified as part of the Command structure gets called when matched on Parse()
type ConfigureArgumentFunc ¶
ConfigureArgumentFunc is used to enable a fluent interface when defining arguments
func SetRequired ¶
func SetRequired(required bool) ConfigureArgumentFunc
SetRequired when true, the flag must be supplied on the command-line
func SetRequiredIf ¶ added in v0.0.3
func SetRequiredIf(requiredIf RequiredIfFunc) ConfigureArgumentFunc
SetRequiredIf allows to set a function to evaluate if a flag is required
func SetSecure ¶
func SetSecure(secure bool) ConfigureArgumentFunc
func SetSecurePrompt ¶
func SetSecurePrompt(prompt string) ConfigureArgumentFunc
func WithAcceptedValues ¶ added in v0.0.8
func WithAcceptedValues(values []PatternValue) ConfigureArgumentFunc
func WithDefaultValue ¶
func WithDefaultValue(defaultValue string) ConfigureArgumentFunc
func WithDependentFlags ¶
func WithDependentFlags(dependencies []string) ConfigureArgumentFunc
WithDependentFlags accepts an array of string denoting flags on which an argument depends. Results in a warning being emitted in GetWarnings() when the dependent flags are not specified on the command-line.
func WithDependentValueFlags ¶
func WithDependentValueFlags(dependencies, values []string) ConfigureArgumentFunc
WithDependentValueFlags accepts an array of string denoting flags and flag values on which an argument depends. Results in a warning being emitted in GetWarnings() when the dependent flags are not specified on the command-line. For example - to specify a dependency on flagA with values 'b' or 'c':
WithDependentValueFlags([]string{"flagA", "flagA"}, []string{"b", "c"})
func WithDescription ¶
func WithDescription(description string) ConfigureArgumentFunc
WithDescription the description will be used in usage output presented to the user
func WithPostValidationFilter ¶ added in v0.0.7
func WithPostValidationFilter(filter FilterFunc) ConfigureArgumentFunc
func WithPreValidationFilter ¶ added in v0.0.7
func WithPreValidationFilter(filter FilterFunc) ConfigureArgumentFunc
func WithShortFlag ¶
func WithShortFlag(shortFlag string) ConfigureArgumentFunc
WithShortFlag represents the short form of a flag. Since by default and design, no max length is enforced, the "short" flag can be looked at as an alternative to using the long name. I use it as a moniker. The short flag can be used in all methods which take a flag argument. By default, there is no support for "POSIX/GNU-like" chaining of boolean flags such as :
-vvvv
Instead of specifying a flag 4 times, the "goopt" way would be specifying `-v 4`.
If POSIX/GNU compatibility is desired use the SetPosix or WithPosix functions on CmdLineOption (not implemented yet).
func WithType ¶
func WithType(typeof OptionType) ConfigureArgumentFunc
WithType - one of three types:
- Single - a flag which expects a value
- Chained - a flag which expects a delimited value representing elements in a list (and is evaluated as a list)
- Standalone - a boolean flag which by default takes no value (defaults to true) but may accept a value which evaluates to true or false
type ConfigureCmdLineFunc ¶
type ConfigureCmdLineFunc func(cmdLine *CmdLineOption, err *error)
ConfigureCmdLineFunc is used to enable a fluent interface when defining options
func WithArgumentPrefixes ¶
func WithArgumentPrefixes(prefixes []rune) ConfigureCmdLineFunc
WithArgumentPrefixes allows providing custom flag prefixes (defaults to '-', '---', and '/').
func WithBindFlag ¶
func WithBindFlag[T Bindable](flag string, bindVar *T, argument *Argument) ConfigureCmdLineFunc
WithBindFlag is a fluent wrapper to BindFlag which is used to bind a pointer to a variable with a flag. If `bindVar` is not a pointer, an error is returned The following variable types are supported:
- *string
- *int, *int8, *int16, *int32, *int64
- *uint, *uint8, *uint16, *uint32, *uint64
- *float32, *float64
- *time.Time
- *bool For other types use WithCustomBindFlag (fluent wrapper around CustomBindFlag) or CustomBindFlag
func WithCommand ¶
func WithCommand(command *Command) ConfigureCmdLineFunc
WithCommand is a fluent wrapper for AddCommand. A Command represents a verb followed by optional sub-commands. A sub-command is a Command which is stored in a Command's []Subcommands field. A command which has no children is a terminating command which can receive values supplied by the user on the command line. Like flags, commands are evaluated on Parse. See the Command struct for more details.
func WithCustomBindFlag ¶
func WithCustomBindFlag[T any](flag string, bindVar *T, proc ValueSetFunc, argument *Argument) ConfigureCmdLineFunc
WithCustomBindFlag is a fluent wrapper for CustomBindFlag which receives parsed value via the ValueSetFunc callback On Parse the callback is called with the following arguments:
- the bound flag name as string
- the command-line value as string
- the custom struct or variable which was bound. The bound structure is passed as reflect.Value
func WithFlag ¶
func WithFlag(flag string, argument *Argument) ConfigureCmdLineFunc
WithFlag is a fluent wrapper for AddFlag which is used to define a flag. A flag represents a command line option as a "long" and optional "short" form which is prefixed by '-', '--' or '/'.
func WithListDelimiterFunc ¶
func WithListDelimiterFunc(delimiterFunc ListDelimiterFunc) ConfigureCmdLineFunc
WithListDelimiterFunc allows providing a custom function for splitting Chained command-line argument values into lists.
func WithPosix ¶
func WithPosix(usePosix bool) ConfigureCmdLineFunc
WithPosix for switching on Posix/GNU-like flag compatibility - not implemented yet
type ConfigureCommandFunc ¶
type ConfigureCommandFunc func(command *Command)
ConfigureCommandFunc is used to enable a fluent interface when defining commands
func SetCommandRequired ¶
func SetCommandRequired(required bool) ConfigureCommandFunc
SetCommandRequired function is used to set the command as required or optional. If a command is set as required and not provided by the user, an error is generated.
func WithCallback ¶
func WithCallback(callback CommandFunc) ConfigureCommandFunc
WithCallback sets the callback function for the command. This function is run when the command gets executed.
func WithCommandDefault ¶
func WithCommandDefault(defaultValue string) ConfigureCommandFunc
func WithCommandDescription ¶
func WithCommandDescription(description string) ConfigureCommandFunc
WithCommandDescription sets the description for the command. This description helps users to understand what the command does.
func WithName ¶
func WithName(name string) ConfigureCommandFunc
WithName sets the name for the command. The name is used to identify the command and invoke it from the command line.
func WithSubcommands ¶
func WithSubcommands(subcommands ...*Command) ConfigureCommandFunc
type FilterFunc ¶ added in v0.0.6
FilterFunc used to "filter" (change/evaluate) flag values - see AddFilter/GetPreValidationFilter/HasPreValidationFilter
type ListDelimiterFunc ¶
ListDelimiterFunc signature to match when supplying a user-defined function to check for the runes which form list delimiters. Defaults to ',' || r == '|' || r == ' '.
type LiterateRegex ¶
type LiterateRegex struct {
// contains filtered or unexported fields
}
LiterateRegex used to provide human descriptions of regular expression
func (*LiterateRegex) Describe ¶
func (r *LiterateRegex) Describe() string
Describe a LiterateRegex (regular expression with a human-readable explanation of the pattern)
type OptionType ¶
type OptionType int
OptionType used to define Flag types (such as Standalone, Single, Chained)
const ( // Single denotes a Flag accepting a string value Single OptionType = 0 // Chained denotes a Flag accepting a string value which should be evaluated as a list (split on ' ', '|' and ',') Chained OptionType = 1 // Standalone denotes a boolean Flag (does not accept a value) Standalone OptionType = 2 )
type PathValue ¶
PathValue denotes Path/value Command pairs where the Path represents the keys of all Command / sub-command at which a value is stored Example:
in the structure Command{Name : "Test", Subcommands: []Command{{Name: "User"}}} the Path to User would consist of "Test User"
type PatternValue ¶ added in v0.0.8
type PositionalArgument ¶
PositionalArgument describes command-line arguments which were not matched as flags, flag values, command or command values.
type PrettyPrintConfig ¶
type PrettyPrintConfig struct { // NewCommandPrefix precedes the start of a new command NewCommandPrefix string // DefaultPrefix precedes sub-commands by default DefaultPrefix string // TerminalPrefix precedes terminal, i.e. Command structs which don't have sub-commands TerminalPrefix string // LevelBindPrefix is used for indentation. The indentation is repeated for each Level under the // command root. The Command root is at Level 0. Each sub-command increases root Level by 1. LevelBindPrefix string }
PrettyPrintConfig is used to print the list of accepted commands as a tree in PrintCommandsUsing and PrintCommands
type RequiredIfFunc ¶ added in v0.0.3
type RequiredIfFunc func(cmdLine *CmdLineOption, optionName string) (bool, string)
RequiredIfFunc used to specify if an option is required when a particular Command or Flag is specified
type Secure ¶
Secure set to Secure to true to solicit non-echoed user input from stdin. If Prompt is empty a "password :" prompt will be displayed. Set to the desired value to override.
type ValueSetFunc ¶
type ValueSetFunc func(flag, value string, customStruct interface{})
ValueSetFunc callback - optionally specified as part of the Argument structure to 'bind' variables to a Flag Used to set the value of a Flag to a custom structure.