Documentation
¶
Overview ¶
Package goopt provides support for command-line processing.
It supports 4 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 File - a flag which expects a file path
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 ¶
- Constants
- Variables
- func BindFlagToCmdLine[T Bindable](s *Parser, data *T, flag string, argument *Argument, commandPath ...string) errordeprecated
- func BindFlagToParser[T Bindable](s *Parser, data *T, flag string, argument *Argument, commandPath ...string) error
- func CustomBindFlagToCmdLine[T any](s *Parser, data *T, proc ValueSetFunc, flag string, argument *Argument, ...) errordeprecated
- func CustomBindFlagToParser[T any](s *Parser, data *T, proc ValueSetFunc, flag string, argument *Argument, ...) error
- type Argument
- type Bindable
- type ClearConfig
- type CmdLineOptiondeprecated
- type Command
- type CommandFunc
- type CompletionData
- 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 []types.PatternValue) ConfigureArgumentFunc
- func WithDefaultValue(defaultValue string) ConfigureArgumentFunc
- func WithDependencyMap(dependencies map[string][]string) ConfigureArgumentFunc
- func WithDependentFlags(dependencies []string) ConfigureArgumentFunc
- func WithDependentValueFlags(dependencies, values []string) ConfigureArgumentFuncdeprecated
- func WithDescription(description string) ConfigureArgumentFunc
- func WithPosition(idx int) ConfigureArgumentFunc
- func WithPostValidationFilter(filter FilterFunc) ConfigureArgumentFunc
- func WithPreValidationFilter(filter FilterFunc) ConfigureArgumentFunc
- func WithShortFlag(shortFlag string) ConfigureArgumentFunc
- func WithType(typeof types.OptionType) ConfigureArgumentFunc
- type ConfigureCmdLineFunc
- func WithArgumentPrefixes(prefixes []rune) ConfigureCmdLineFunc
- func WithBindFlag[T Bindable](flag string, bindVar *T, argument *Argument, commandPath ...string) ConfigureCmdLineFunc
- func WithCommand(command *Command) ConfigureCmdLineFunc
- func WithCommandNameConverter(converter NameConversionFunc) ConfigureCmdLineFunc
- func WithCustomBindFlag[T any](flag string, bindVar *T, proc ValueSetFunc, argument *Argument, ...) ConfigureCmdLineFunc
- func WithEnvNameConverter(converter NameConversionFunc) ConfigureCmdLineFunc
- func WithExecOnParse(value bool) ConfigureCmdLineFunc
- func WithFlag(flag string, argument *Argument) ConfigureCmdLineFunc
- func WithFlagNameConverter(converter NameConversionFunc) ConfigureCmdLineFunc
- func WithListDelimiterFunc(delimiterFunc types.ListDelimiterFunc) ConfigureCmdLineFunc
- func WithPosix(usePosix bool) ConfigureCmdLineFunc
- type ConfigureCommandFunc
- func WithCallback(callback CommandFunc) ConfigureCommandFunc
- func WithCommandDescription(description string) ConfigureCommandFunc
- func WithName(name string) ConfigureCommandFunc
- func WithOverwriteSubcommands(subcommands ...*Command) ConfigureCommandFunc
- func WithSubcommands(subcommands ...*Command) ConfigureCommandFunc
- type FilterFunc
- type FlagInfo
- type NameConversionFunc
- type Parser
- func NewCmdLine(configs ...ConfigureCmdLineFunc) (*Parser, error)deprecated
- func NewCmdLineFromStruct[T any](structWithTags *T, config ...ConfigureCmdLineFunc) (*Parser, error)deprecated
- func NewCmdLineFromStructWithLevel[T any](structWithTags *T, maxDepth int, config ...ConfigureCmdLineFunc) (*Parser, error)deprecated
- func NewCmdLineOption() *Parserdeprecated
- func NewParser() *Parser
- func NewParserFromInterface(i interface{}, config ...ConfigureCmdLineFunc) (*Parser, error)
- func NewParserFromStruct[T any](structWithTags *T, config ...ConfigureCmdLineFunc) (*Parser, error)
- func NewParserFromStructWithLevel[T any](structWithTags *T, maxDepth int, config ...ConfigureCmdLineFunc) (*Parser, error)
- func NewParserWith(configs ...ConfigureCmdLineFunc) (*Parser, error)
- func (p *Parser) AcceptPattern(flag string, val types.PatternValue, commandPath ...string) error
- func (p *Parser) AcceptPatterns(flag string, acceptVal []types.PatternValue, commandPath ...string) error
- func (p *Parser) AddCommand(cmd *Command) error
- func (p *Parser) AddDependency(flag, dependsOn string, commandPath ...string) error
- func (p *Parser) AddDependencyValue(flag, dependsOn string, allowedValues []string, commandPath ...string) error
- func (p *Parser) AddFlag(flag string, argument *Argument, commandPath ...string) error
- func (p *Parser) AddFlagPostValidationFilter(flag string, proc FilterFunc, commandPath ...string) error
- func (p *Parser) AddFlagPreValidationFilter(flag string, proc FilterFunc, commandPath ...string) error
- func (p *Parser) BindFlag(bindPtr interface{}, flag string, argument *Argument, commandPath ...string) error
- func (p *Parser) Clear(config ClearConfig)
- func (p *Parser) ClearAll()
- func (p *Parser) CustomBindFlag(data any, proc ValueSetFunc, flag string, argument *Argument, ...) error
- func (p *Parser) DependsOnFlag(flag, dependsOn string, commandPath ...string) error
- func (p *Parser) DependsOnFlagValue(flag, dependsOn, ofValue string, commandPath ...string) error
- func (p *Parser) DescribeFlag(flag, description string, commandPath ...string) error
- func (p *Parser) ExecuteCommand() error
- func (p *Parser) ExecuteCommands() int
- func (p *Parser) GenerateCompletion(shell, programName string) string
- func (p *Parser) Get(flag string, commandPath ...string) (string, bool)
- func (p *Parser) GetAcceptPatterns(flag string, commandPath ...string) ([]types.PatternValue, error)
- func (p *Parser) GetArgument(flag string, commandPath ...string) (*Argument, error)
- func (p *Parser) GetBool(flag string, commandPath ...string) (bool, error)
- func (p *Parser) GetCommandExecutionError(commandName string) error
- func (p *Parser) GetCommandExecutionErrors() []types.KeyValue[string, error]
- func (p *Parser) GetCommands() []string
- func (p *Parser) GetCompletionData() completion.CompletionData
- func (p *Parser) GetConsistencyWarnings() []stringdeprecated
- func (p *Parser) GetDescription(flag string, commandPath ...string) string
- func (p *Parser) GetErrorCount() int
- func (p *Parser) GetErrors() []error
- func (p *Parser) GetFloat(flag string, bitSize int, commandPath ...string) (float64, error)
- func (p *Parser) GetInt(flag string, bitSize int, commandPath ...string) (int64, error)
- func (p *Parser) GetList(flag string, commandPath ...string) ([]string, error)
- func (p *Parser) GetMaxDependencyDepth() int
- func (p *Parser) GetOptions() []types.KeyValue[string, string]
- func (p *Parser) GetOrDefault(flag string, defaultValue string, commandPath ...string) string
- func (p *Parser) GetPositionalArgCount() int
- func (p *Parser) GetPositionalArgs() []PositionalArgument
- func (p *Parser) GetPostValidationFilter(flag string, commandPath ...string) (FilterFunc, error)
- func (p *Parser) GetPreValidationFilter(flag string, commandPath ...string) (FilterFunc, error)
- func (p *Parser) GetShortFlag(flag string, commandPath ...string) (string, error)
- func (p *Parser) GetStderr() io.Writer
- func (p *Parser) GetStdout() io.Writer
- func (p *Parser) GetTerminalReader() util.TerminalReader
- func (p *Parser) GetWarnings() []string
- func (p *Parser) HasAcceptedValues(flag string, commandPath ...string) bool
- func (p *Parser) HasCommand(path string) bool
- func (p *Parser) HasFlag(flag string, commandPath ...string) bool
- func (p *Parser) HasPositionalArgs() bool
- func (p *Parser) HasPostValidationFilter(flag string, commandPath ...string) bool
- func (p *Parser) HasPreValidationFilter(flag string, commandPath ...string) bool
- func (p *Parser) HasRawFlag(flag string) bool
- func (p *Parser) Parse(args []string) bool
- func (p *Parser) ParseString(argString string) bool
- func (p *Parser) ParseStringWithDefaults(defaults map[string]string, argString string) bool
- func (p *Parser) ParseWithDefaults(defaults map[string]string, args []string) bool
- func (p *Parser) PrintCommandSpecificFlags(writer io.Writer, commandPath string, level int, config *PrettyPrintConfig)
- func (p *Parser) PrintCommands(writer io.Writer)
- func (p *Parser) PrintCommandsUsing(writer io.Writer, config *PrettyPrintConfig)
- func (p *Parser) PrintCommandsWithFlags(writer io.Writer, config *PrettyPrintConfig)
- func (p *Parser) PrintFlags(writer io.Writer)
- func (p *Parser) PrintGlobalFlags(writer io.Writer)
- func (p *Parser) PrintPositionalArgs(writer io.Writer)
- func (p *Parser) PrintUsage(writer io.Writer)
- func (p *Parser) PrintUsageWithGroups(writer io.Writer)
- func (p *Parser) Remove(flag string, commandPath ...string) bool
- func (p *Parser) RemoveDependency(flag, dependsOn string, commandPath ...string) error
- func (p *Parser) SetArgument(flag string, paths []string, configs ...ConfigureArgumentFunc) error
- func (p *Parser) SetArgumentPrefixes(prefixes []rune) error
- func (p *Parser) SetCommand(commandPath string, configs ...ConfigureCommandFunc) error
- func (p *Parser) SetCommandNameConverter(converter NameConversionFunc) NameConversionFunc
- func (p *Parser) SetEnvNameConverter(converter NameConversionFunc) NameConversionFunc
- func (p *Parser) SetExecOnParse(value bool)
- func (p *Parser) SetFlag(flag, value string, commandPath ...string) error
- func (p *Parser) SetFlagNameConverter(converter NameConversionFunc) NameConversionFunc
- func (p *Parser) SetListDelimiterFunc(delimiterFunc types.ListDelimiterFunc) error
- func (p *Parser) SetMaxDependencyDepth(depth int)
- func (p *Parser) SetPosix(posixCompatible bool) bool
- func (p *Parser) SetStderr(w io.Writer) io.Writer
- func (p *Parser) SetStdout(w io.Writer) io.Writer
- func (p *Parser) SetTerminalReader(t util.TerminalReader) util.TerminalReader
- type PositionalArgument
- type PrettyPrintConfig
- type RequiredIfFunc
- type ValueSetFunc
Constants ¶
const DefaultMaxDependencyDepth = 10
DefaultMaxDependencyDepth is the default maximum depth for flag dependencies
const (
ExecDir = "${EXEC_DIR}"
)
const (
FmtErrorWithString = "%w: %s"
)
Variables ¶
var ( // ToKebabCase converts a string to kebab case "my-command-name" ToKebabCase = func(s string) string { return strcase.ToKebab(s) } // ToSnakeCase converts a string to snake case "my_command_name" ToSnakeCase = func(s string) string { return strcase.ToSnake(s) } // ToScreamingSnake converts a string to screaming snake case "MY_COMMAND_NAME" ToScreamingSnake = func(s string) string { return strcase.ToScreamingSnake(s) } // ToLowerCamel converts a string to lower camel case "myCommandName" ToLowerCamel = func(s string) string { return strcase.ToLowerCamel(s) } // ToLowerCase converts a string to lower case "mycommandname" ToLowerCase = func(s string) string { return strings.ToLower(s) } DefaultCommandNameConverter = ToLowerCase DefaultFlagNameConverter = ToLowerCamel )
Built-in conversion strategies
Functions ¶
func BindFlagToCmdLine
deprecated
added in
v0.5.3
func BindFlagToParser ¶ added in v1.7.0
func BindFlagToParser[T Bindable](s *Parser, data *T, flag string, argument *Argument, commandPath ...string) error
BindFlagToParser is a helper function to allow passing generics to the Parser.BindFlag method
func CustomBindFlagToCmdLine
deprecated
added in
v0.5.3
func CustomBindFlagToParser ¶ added in v1.7.0
func CustomBindFlagToParser[T any](s *Parser, data *T, proc ValueSetFunc, flag string, argument *Argument, commandPath ...string) error
CustomBindFlagToParser is a helper function to allow passing generics to the Parser.CustomBindFlag method
Types ¶
type Argument ¶
type Argument struct { Description string TypeOf types.OptionType Required bool RequiredIf RequiredIfFunc PreFilter FilterFunc PostFilter FilterFunc AcceptedValues []types.PatternValue DependsOn []string // Deprecated: use DependencyMap instead - will be removed in v2.0.0 OfValue []string // Deprecated: use DependencyMap instead - will be removed in v2.0.0 DependencyMap map[string][]string Secure types.Secure Short string DefaultValue string Capacity int // For slices, the capacity of the slice, ignored for other types Position *int }
Argument defines a command-line Flag
func NewArg ¶
func NewArg(configs ...ConfigureArgumentFunc) *Argument
NewArg convenience initialization method to configure flags
func NewArgument ¶
func NewArgument(shortFlag string, description string, typeOf types.OptionType, required bool, secure types.Secure, defaultValue string) *Argument
NewArgument convenience initialization method to describe Flags. Alternatively, Use NewArg to configure Argument using option functions.
func (*Argument) Set ¶ added in v1.4.1
func (a *Argument) Set(configs ...ConfigureArgumentFunc) error
Set configures the Argument instance with the provided ConfigureArgumentFunc(s), and returns an error if a configuration results in an error.
Usage example:
arg := &Argument{} err := arg.Set( WithDescription("example argument"), WithType(Standalone), SetRequired(true), ) if err != nil { // handle error }
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 | time.Duration | []string | []int8 | []int16 | []int32 | []int64 | ~[]int | []uint8 | []uint16 | []uint32 | []uint64 | ~[]uint | []float32 | []float64 | []bool | []time.Time | []time.Duration }
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
deprecated
type CmdLineOption = Parser
CmdLineOption is an alias for Parser.
Deprecated: Use Parser instead. This type will be removed in v2.0.0.
type Command ¶
type Command struct { Name string Subcommands []Command Callback CommandFunc Description string // 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.
func (*Command) IsTopLevel ¶ added in v1.8.8
IsTopLevel returns whether this is a top-level command
func (*Command) Set ¶ added in v1.5.2
func (c *Command) Set(configs ...ConfigureCommandFunc)
Set is a helper config function that allows setting multiple configuration functions on a command.
type CommandFunc ¶
CommandFunc callback - optionally specified as part of the Command structure gets called when matched on Parse()
type CompletionData ¶ added in v1.8.0
type CompletionData struct { Commands []string // Available commands Flags []string // Global flags CommandFlags map[string][]string // Flags per command Descriptions map[string]string // Descriptions for commands/flags FlagValues map[string][]CompletionData // Values for flags CommandDescriptions map[string]string // Descriptions specific to commands }
CompletionData is used to store information for command line completion
type ConfigureArgumentFunc ¶
ConfigureArgumentFunc is used when defining Flag 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
SetSecure sets the secure flag to true or false
func SetSecurePrompt ¶
func SetSecurePrompt(prompt string) ConfigureArgumentFunc
SetSecurePrompt sets the prompt for the secure flag
func WithAcceptedValues ¶ added in v0.0.8
func WithAcceptedValues(values []types.PatternValue) ConfigureArgumentFunc
WithAcceptedValues sets the accepted values for the argument. The values can be either literal strings or regular expressions. Each value can optionally have a description that will be shown in help text.
func WithDefaultValue ¶
func WithDefaultValue(defaultValue string) ConfigureArgumentFunc
WithDefaultValue sets the default value for the argument
func WithDependencyMap ¶ added in v1.8.3
func WithDependencyMap(dependencies map[string][]string) ConfigureArgumentFunc
WithDependencyMap specifies flag dependencies using a map of flag names to accepted values
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.
func WithDependentValueFlags
deprecated
func WithDependentValueFlags(dependencies, values []string) ConfigureArgumentFunc
WithDependentValueFlags specifies flag dependencies with their accepted values
Deprecated: Use WithDependencyMap instead
func WithDescription ¶
func WithDescription(description string) ConfigureArgumentFunc
WithDescription the description will be used in usage output presented to the user
func WithPosition ¶ added in v1.9.0
func WithPosition(idx int) ConfigureArgumentFunc
WithPosition sets a position requirement for the argument
func WithPostValidationFilter ¶ added in v0.0.7
func WithPostValidationFilter(filter FilterFunc) ConfigureArgumentFunc
WithPostValidationFilter sets the post-validation filter for the argument
func WithPreValidationFilter ¶ added in v0.0.7
func WithPreValidationFilter(filter FilterFunc) ConfigureArgumentFunc
WithPreValidationFilter sets the pre-validation filter for the argument
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 types.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
- File - a flag which expects a valid file path whose content is the value
type ConfigureCmdLineFunc ¶
ConfigureCmdLineFunc is used when defining CommandLineOption 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, commandPath ...string) ConfigureCmdLineFunc
WithBindFlag is a 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 (wrapper around CustomBindFlag) or CustomBindFlag
func WithCommand ¶
func WithCommand(command *Command) ConfigureCmdLineFunc
WithCommand is a 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 WithCommandNameConverter ¶ added in v1.8.4
func WithCommandNameConverter(converter NameConversionFunc) ConfigureCmdLineFunc
WithCommandNameConverter allows setting a custom name converter for command names
func WithCustomBindFlag ¶
func WithCustomBindFlag[T any](flag string, bindVar *T, proc ValueSetFunc, argument *Argument, commandPath ...string) ConfigureCmdLineFunc
WithCustomBindFlag is a 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 WithEnvNameConverter ¶ added in v1.8.4
func WithEnvNameConverter(converter NameConversionFunc) ConfigureCmdLineFunc
WithEnvNameConverter allows setting a custom name converter for environment variable names
func WithExecOnParse ¶ added in v1.5.7
func WithExecOnParse(value bool) ConfigureCmdLineFunc
WithExecOnParse specifies whether Command callbacks should be executed during Parse as they are encountered.
func WithFlag ¶
func WithFlag(flag string, argument *Argument) ConfigureCmdLineFunc
WithFlag is a 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 WithFlagNameConverter ¶ added in v1.8.4
func WithFlagNameConverter(converter NameConversionFunc) ConfigureCmdLineFunc
WithFlagNameConverter allows setting a custom name converter for flag names
func WithListDelimiterFunc ¶
func WithListDelimiterFunc(delimiterFunc types.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
type ConfigureCommandFunc ¶
type ConfigureCommandFunc func(command *Command)
ConfigureCommandFunc is used when defining Command options
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 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 WithOverwriteSubcommands ¶ added in v1.5.2
func WithOverwriteSubcommands(subcommands ...*Command) ConfigureCommandFunc
WithOverwriteSubcommands allows replacing a Command's subcommands.
func WithSubcommands ¶
func WithSubcommands(subcommands ...*Command) ConfigureCommandFunc
WithSubcommands function takes a list of subcommands and associates them with a command.
type FilterFunc ¶ added in v0.0.6
FilterFunc used to "filter" (change/evaluate) flag values - see AddFilter/GetPreValidationFilter/HasPreValidationFilter
type FlagInfo ¶ added in v1.5.0
type FlagInfo struct { Argument *Argument CommandPath string // The path of the command that owns this flag }
FlagInfo is used to store information about a flag
type NameConversionFunc ¶ added in v1.8.4
NameConversionFunc converts a field name to a command/flag name
type Parser ¶ added in v1.7.0
type Parser struct {
// contains filtered or unexported fields
}
Parser opaque struct used in all Flag/Command manipulation
func NewCmdLine
deprecated
func NewCmdLine(configs ...ConfigureCmdLineFunc) (*Parser, error)
NewCmdLine creates a new parser with functional configuration.
Deprecated: Use NewParserWith instead. This function will be removed in v2.0.0.
func NewCmdLineFromStruct
deprecated
added in
v1.4.0
func NewCmdLineFromStruct[T any](structWithTags *T, config ...ConfigureCmdLineFunc) (*Parser, error)
NewCmdLineFromStruct is an alias for NewParserFromStruct.
Deprecated: Use NewParserFromStruct instead. This function will be removed in v2.0.0.
func NewCmdLineFromStructWithLevel
deprecated
added in
v1.4.0
func NewCmdLineFromStructWithLevel[T any](structWithTags *T, maxDepth int, config ...ConfigureCmdLineFunc) (*Parser, error)
NewCmdLineFromStructWithLevel is an alias for NewParserFromStructWithLevel.
Deprecated: Use NewParserFromStructWithLevel instead. This function will be removed in v2.0.0.
func NewCmdLineOption
deprecated
func NewCmdLineOption() *Parser
NewCmdLineOption creates a new parser with default initialization.
Deprecated: Use NewParser instead. This function will be removed in v2.0.0.
func NewParser ¶ added in v1.7.0
func NewParser() *Parser
NewParser convenience initialization method. Use NewCmdLine to configure CmdLineOption using option functions.
func NewParserFromInterface ¶ added in v1.9.2
func NewParserFromInterface(i interface{}, config ...ConfigureCmdLineFunc) (*Parser, error)
NewParserFromInterface creates a new parser from an interface{} that should be a struct or a pointer to a struct
func NewParserFromStruct ¶ added in v1.7.0
func NewParserFromStruct[T any](structWithTags *T, config ...ConfigureCmdLineFunc) (*Parser, error)
NewParserFromStruct creates a new Parser from a struct. By default, all fields are treated as flags unless:
- They are tagged with `ignore`
- They are unexported
- They are nested structs or slices of structs
Default field behavior:
- Type: Single
- Name: derived from field name
- Flag: true
Use tags to override defaults:
`goopt:"name:custom;type:chained"`
func NewParserFromStructWithLevel ¶ added in v1.7.0
func NewParserFromStructWithLevel[T any](structWithTags *T, maxDepth int, config ...ConfigureCmdLineFunc) (*Parser, error)
NewParserFromStructWithLevel parses a struct and binds its fields to command-line flags up to maxDepth levels
func NewParserWith ¶ added in v1.7.0
func NewParserWith(configs ...ConfigureCmdLineFunc) (*Parser, error)
NewParserWith allows initialization of Parser using option functions. The caller should always test for error on return because Parser will be nil when an error occurs during initialization.
Configuration example:
parser, err := NewParserWith( 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 (*Parser) AcceptPattern ¶ added in v1.7.0
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 (*Parser) AcceptPatterns ¶ added in v1.7.0
func (p *Parser) AcceptPatterns(flag string, acceptVal []types.PatternValue, commandPath ...string) 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 (*Parser) AddCommand ¶ added in v1.7.0
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 (*Parser) AddDependency ¶ added in v1.8.3
AddDependency adds a dependency without value constraints
func (*Parser) AddDependencyValue ¶ added in v1.8.3
func (p *Parser) AddDependencyValue(flag, dependsOn string, allowedValues []string, commandPath ...string) error
AddDependencyValue adds or updates a dependency with specific allowed values
func (*Parser) AddFlag ¶ added in v1.7.0
AddFlag is used to define a Flag. A Flag represents a command line option with a "long" name and an optional "short" form prefixed by '-', '--' or '/'. This version supports both global flags and command-specific flags using the optional commandPath argument.
func (*Parser) AddFlagPostValidationFilter ¶ added in v1.7.0
func (p *Parser) AddFlagPostValidationFilter(flag string, proc FilterFunc, commandPath ...string) error
AddFlagPostValidationFilter adds a filter (user-defined transform/evaluate function) which is called on the Flag value during Parse *after* AcceptedValues are checked
func (*Parser) AddFlagPreValidationFilter ¶ added in v1.7.0
func (p *Parser) AddFlagPreValidationFilter(flag string, proc FilterFunc, commandPath ...string) error
AddFlagPreValidationFilter adds a filter (user-defined transform/evaluate function) which is called on the Flag value during Parse *before* AcceptedValues are checked
func (*Parser) BindFlag ¶ added in v1.7.0
func (p *Parser) BindFlag(bindPtr interface{}, flag string, argument *Argument, commandPath ...string) 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 BindFlagToParser instead
func (*Parser) Clear ¶ added in v1.7.0
func (p *Parser) Clear(config ClearConfig)
Clear can be used to selectively clear sensitive options or when re-defining options on the fly.
func (*Parser) ClearAll ¶ added in v1.7.0
func (p *Parser) 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 (*Parser) CustomBindFlag ¶ added in v1.7.0
func (p *Parser) CustomBindFlag(data any, proc ValueSetFunc, flag string, argument *Argument, commandPath ...string) 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 (*Parser) DependsOnFlag ¶ added in v1.7.0
DependsOnFlag adds a dependency without value constraints
func (*Parser) DependsOnFlagValue ¶ added in v1.7.0
DependsOnFlagValue adds a dependency with specific value constraints
func (*Parser) DescribeFlag ¶ added in v1.7.0
DescribeFlag is used to provide a description of a Flag
func (*Parser) ExecuteCommand ¶ added in v1.7.0
ExecuteCommand command callbacks are placed on a FIFO queue during parsing until ExecuteCommands is called. Returns the error which occurred during execution of a command callback.
func (*Parser) ExecuteCommands ¶ added in v1.7.0
ExecuteCommands command callbacks are placed on a FIFO queue during parsing until ExecuteCommands is called. Returns the count of errors encountered during execution.
func (*Parser) GenerateCompletion ¶ added in v1.8.0
GenerateCompletion generates completion scripts for the given shell and program name
func (*Parser) Get ¶ added in v1.7.0
Get returns a combination of a Flag's value as string and true if found. If a flag is not set but has a configured default value the default value is registered and is returned. Returns an empty string and false otherwise
func (*Parser) GetAcceptPatterns ¶ added in v1.7.0
func (p *Parser) GetAcceptPatterns(flag string, commandPath ...string) ([]types.PatternValue, error)
GetAcceptPatterns takes a flag string and returns an error if the flag does not exist, a slice of LiterateRegex otherwise
func (*Parser) GetArgument ¶ added in v1.7.0
GetArgument returns the Argument corresponding to the long or short flag or an error when not found
func (*Parser) GetBool ¶ added in v1.7.0
GetBool attempts to convert the string value of a Flag to boolean.
func (*Parser) GetCommandExecutionError ¶ added in v1.7.0
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 (*Parser) GetCommandExecutionErrors ¶ added in v1.8.6
GetCommandExecutionErrors returns the errors which occurred during execution of command callbacks after ExecuteCommands has been called. Returns a KeyValue list of command name and error
func (*Parser) GetCommands ¶ added in v1.7.0
GetCommands returns the list of all commands seen on command-line
func (*Parser) GetCompletionData ¶ added in v1.8.0
func (p *Parser) GetCompletionData() completion.CompletionData
GetCompletionData populates a CompletionData struct containing information for command line completion
func (*Parser) GetConsistencyWarnings
deprecated
added in
v1.7.0
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
Deprecated: Use GetWarnings instead. This function will be removed in v2.0.0.
func (*Parser) GetDescription ¶ added in v1.7.0
GetDescription retrieves a Flag's description as set by DescribeFlag
func (*Parser) GetErrorCount ¶ added in v1.7.0
GetErrorCount is greater than zero when errors were encountered during Parse.
func (*Parser) GetErrors ¶ added in v1.7.0
GetErrors returns a list of the errors encountered during Parse
func (*Parser) GetFloat ¶ added in v1.7.0
GetFloat attempts to convert the string value of a Flag to a float64
func (*Parser) GetInt ¶ added in v1.7.0
GetInt attempts to convert the string value of a Flag to an int64.
func (*Parser) GetList ¶ added in v1.7.0
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 (*Parser) GetMaxDependencyDepth ¶ added in v1.8.8
GetMaxDependencyDepth returns the current maximum allowed depth for flag dependencies. If not explicitly set, returns DefaultMaxDependencyDepth.
func (*Parser) GetOptions ¶ added in v1.7.0
GetOptions returns a slice of KeyValue pairs which have been supplied on the command-line. Note: Short flags are always resolved to their long form in the returned options. For example, if "-d" is specified on the command line and maps to "--debug", the returned option will use "debug" as the key.
func (*Parser) GetOrDefault ¶ added in v1.7.0
GetOrDefault returns the value of a defined Flag or defaultValue if no value is set
func (*Parser) GetPositionalArgCount ¶ added in v1.7.0
GetPositionalArgCount returns the number of positional arguments
func (*Parser) GetPositionalArgs ¶ added in v1.7.0
func (p *Parser) GetPositionalArgs() []PositionalArgument
GetPositionalArgs returns the list of positional arguments - a positional argument is a command line argument that is neither a flag, a flag value, nor a command
func (*Parser) GetPostValidationFilter ¶ added in v1.7.0
func (p *Parser) GetPostValidationFilter(flag string, commandPath ...string) (FilterFunc, error)
GetPostValidationFilter retrieve Flag transform/evaluate function which is called on Parse after checking for acceptable values
func (*Parser) GetPreValidationFilter ¶ added in v1.7.0
func (p *Parser) GetPreValidationFilter(flag string, commandPath ...string) (FilterFunc, error)
GetPreValidationFilter retrieve Flag transform/evaluate function which is called on Parse before checking for acceptable values
func (*Parser) GetShortFlag ¶ added in v1.7.0
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 (*Parser) GetStderr ¶ added in v1.8.3
GetStderr returns the current stderr writer this is a low-level function and should not be used by most users - by default stderr is os.Stderr
func (*Parser) GetStdout ¶ added in v1.8.3
GetStdout returns the current stdout writer this is a low-level function and should not be used by most users - by default stdout is os.Stdout
func (*Parser) GetTerminalReader ¶ added in v1.8.3
func (p *Parser) GetTerminalReader() util.TerminalReader
GetTerminalReader returns the current terminal reader this is a low-level function and should not be used by most users - by default terminal reader is nil and the real terminal is used
func (*Parser) GetWarnings ¶ added in v1.7.0
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 (*Parser) HasAcceptedValues ¶ added in v1.7.0
HasAcceptedValues returns true when a Flag defines a set of valid values it will accept
func (*Parser) HasCommand ¶ added in v1.7.0
HasCommand return true when the name has been seen on the command line.
func (*Parser) HasFlag ¶ added in v1.7.0
HasFlag returns true when the Flag has been seen on the command line.
func (*Parser) HasPositionalArgs ¶ added in v1.7.0
HasPositionalArgs returns true if there are positional arguments
func (*Parser) HasPostValidationFilter ¶ added in v1.7.0
HasPostValidationFilter returns true when an option has a transform/evaluate function which is called on Parse after checking for acceptable values
func (*Parser) HasPreValidationFilter ¶ added in v1.7.0
HasPreValidationFilter returns true when an option has a transform/evaluate function which is called on Parse before checking for acceptable values
func (*Parser) HasRawFlag ¶ added in v1.7.0
HasRawFlag returns true when the Flag has been seen on the command line - can be used to check if a flag was specified on the command line irrespective of the command context.
func (*Parser) Parse ¶ added in v1.7.0
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 Parse processes user command line arguments matching the defined Flag and Command rules.
func (*Parser) ParseString ¶ added in v1.7.0
ParseString calls Parse
func (*Parser) ParseStringWithDefaults ¶ added in v1.7.0
ParseStringWithDefaults calls Parse supplementing missing arguments in argString with default values from defaults
func (*Parser) ParseWithDefaults ¶ added in v1.7.0
ParseWithDefaults calls Parse supplementing missing arguments in args array with default values from defaults
func (*Parser) PrintCommandSpecificFlags ¶ added in v1.7.0
func (p *Parser) PrintCommandSpecificFlags(writer io.Writer, commandPath string, level int, config *PrettyPrintConfig)
PrintCommandSpecificFlags print flags for a specific command with the appropriate indentation
func (*Parser) PrintCommands ¶ added in v1.7.0
PrintCommands writes the list of accepted Command structs to io.Writer.
func (*Parser) PrintCommandsUsing ¶ added in v1.7.0
func (p *Parser) 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.OuterLevelBindPrefix is used for indentation. The indentation is repeated for each Level under the command root. The Command root is at Level 0.
func (*Parser) PrintCommandsWithFlags ¶ added in v1.7.0
func (p *Parser) PrintCommandsWithFlags(writer io.Writer, config *PrettyPrintConfig)
PrintCommandsWithFlags prints commands with their respective flags
func (*Parser) PrintFlags ¶ added in v1.7.0
PrintFlags pretty prints accepted command-line switches to io.Writer
func (*Parser) PrintGlobalFlags ¶ added in v1.7.0
PrintGlobalFlags prints global (non-command-specific) flags
func (*Parser) PrintPositionalArgs ¶ added in v1.9.8
PrintPositionalArgs prints all positional arguments in order
func (*Parser) PrintUsage ¶ added in v1.7.0
PrintUsage pretty prints accepted Flags and Commands to io.Writer.
func (*Parser) PrintUsageWithGroups ¶ added in v1.7.0
PrintUsageWithGroups pretty prints accepted Flags and show command-specific Flags grouped by Commands to io.Writer.
func (*Parser) Remove ¶ added in v1.7.0
Remove used to remove a defined-flag at runtime - returns false if the Flag was not found and true on removal.
func (*Parser) RemoveDependency ¶ added in v1.8.3
RemoveDependency removes a dependency
func (*Parser) SetArgument ¶ added in v1.7.0
func (p *Parser) SetArgument(flag string, paths []string, configs ...ConfigureArgumentFunc) error
SetArgument sets an Argument configuration. Returns an error if the Argument is not found or the configuration results in an error
func (*Parser) SetArgumentPrefixes ¶ added in v1.7.0
SetArgumentPrefixes sets the flag argument prefixes
func (*Parser) SetCommand ¶ added in v1.7.0
func (p *Parser) SetCommand(commandPath string, configs ...ConfigureCommandFunc) error
SetCommand allows for setting of Command fields via option functions Example:
s.Set("user create", WithCommandDescription("create user), WithCommandCallback(callbackFunc), )
func (*Parser) SetCommandNameConverter ¶ added in v1.8.4
func (p *Parser) SetCommandNameConverter(converter NameConversionFunc) NameConversionFunc
SetCommandNameConverter allows setting a custom name converter for command names
func (*Parser) SetEnvNameConverter ¶ added in v1.8.4
func (p *Parser) SetEnvNameConverter(converter NameConversionFunc) NameConversionFunc
SetEnvNameConverter allows setting a custom name converter for environment variable names If set and the environment variable exists, it will be prepended to the args array
func (*Parser) SetExecOnParse ¶ added in v1.7.0
func (*Parser) SetFlag ¶ added in v1.7.0
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. If the Flag is of type File the value is stored in the file.
func (*Parser) SetFlagNameConverter ¶ added in v1.8.4
func (p *Parser) SetFlagNameConverter(converter NameConversionFunc) NameConversionFunc
SetFlagNameConverter allows setting a custom name converter for flag names
func (*Parser) SetListDelimiterFunc ¶ added in v1.7.0
func (p *Parser) SetListDelimiterFunc(delimiterFunc types.ListDelimiterFunc) error
SetListDelimiterFunc sets the value delimiter function for Chained flags
func (*Parser) SetMaxDependencyDepth ¶ added in v1.8.8
SetMaxDependencyDepth sets the maximum allowed depth for flag dependencies. If depth is less than 1, it will be set to DefaultMaxDependencyDepth.
func (*Parser) SetStderr ¶ added in v1.8.3
SetStderr sets the stderr writer and returns the old writer this is a low-level function and should not be used by most users - by default stderr is os.Stderr
func (*Parser) SetStdout ¶ added in v1.8.3
SetStdout sets the stdout writer and returns the old writer this is a low-level function and should not be used by most users - by default stdout is os.Stdout
func (*Parser) SetTerminalReader ¶ added in v1.8.3
func (p *Parser) SetTerminalReader(t util.TerminalReader) util.TerminalReader
SetTerminalReader sets the terminal reader for secure input (by default, the terminal reader is the real terminal) this is useful for testing or mocking the terminal reader or for setting a custom terminal reader the returned value is the old terminal reader, so it can be restored later this is a low-level function and should not be used by most users - by default terminal reader is nil and the real terminal is used
type PositionalArgument ¶
type PositionalArgument struct { Position int // Position in the command line Value string // The actual value Argument *Argument // Reference to the argument definition, if this was bound }
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 // InnerLevelBindPrefix 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. InnerLevelBindPrefix string // OuterLevelBindPrefix is used for indentation after InnerLevelBindPrefix has been rendered. 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. OuterLevelBindPrefix 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
RequiredIfFunc used to specify if an option is required when a particular Command or Flag is specified
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.