Documentation ¶
Overview ¶
Package cmdline implements a command line parser.
It supports structured command invocation, several option types and mapping to basic variable types.
Design revolves around athe central Config type that defines everything from arguments to parse, commands to handle them and their options and customizes the parse behaviour.
It mostly mimics GNU style option parsing with the addition of commands.
See Config and Config.Parse docs for more details.
Index ¶
- Constants
- Variables
- func Parse(config *Config) error
- func ParseCtx(ctx context.Context, config *Config) error
- func PrintCommand(w io.Writer, config *Config, command *Command, indent int)
- func PrintCommands(w io.Writer, config *Config, commands Commands, indent int)
- func PrintCommandsGroup(w io.Writer, config *Config, commands Commands, indent int)
- func PrintCommandsNoOptions(w io.Writer, config *Config, commands Commands, indent int)
- func PrintConfig(w io.Writer, config *Config)
- func PrintOption(w io.Writer, config *Config, option *Option, indent int)
- func PrintOptions(w io.Writer, config *Config, options Options, indent int)
- func ValidateCommands(commands Commands) (err error)
- func ValidateOptions(options Options) error
- type Args
- type Argument
- type Command
- type Commands
- func (self Commands) AnyExecuted() bool
- func (self Commands) Count() int
- func (self Commands) Find(name string) *Command
- func (self *Commands) Handle(name, help string, h Handler) (c *Command)
- func (self *Commands) Register(command *Command) Commands
- func (self Commands) Reset()
- func (self Commands) Walk(f VisitCommand)
- func (self Commands) WalkExecuted(f VisitCommand)
- func (self Commands) WalkNotExecuted(f VisitCommand)
- type Config
- type Context
- type ExclusivityGroup
- type ExclusivityGroups
- type Handler
- type Kind
- type Option
- type Options
- func (self *Options) Boolean(longName, shortName, help string) *Options
- func (self *Options) BooleanVar(longName, shortName, help string, v any) *Options
- func (self Options) Count() int
- func (self Options) FindLong(longName string) *Option
- func (self Options) FindShort(shortName string) *Option
- func (self *Options) Indexed(name, help string) *Options
- func (self *Options) IndexedVar(name, help string, v any) *Options
- func (self *Options) Optional(longName, shortName, help string) *Options
- func (self *Options) OptionalVar(longName, shortName, help string, v any) *Options
- func (self Options) Parsed(longName string) bool
- func (self *Options) Register(option *Option) *Options
- func (self *Options) Repeated(longName, shortName, help string) *Options
- func (self *Options) RepeatedVar(longName, shortName, help string, v any) *Options
- func (self *Options) Required(longName, shortName, help string) *Options
- func (self *Options) RequiredVar(longName, shortName, help string, v any) *Options
- func (self Options) Reset()
- func (self Options) Values(longName string) Values
- func (self *Options) Variadic(name, help string) *Options
- func (self *Options) VariadicVar(name, help string, v any) *Options
- type TopicMap
- type Value
- type Values
- type VisitCommand
Constants ¶
const ( // DefaultLongPrefix is the default prefix for long option names. DefaultLongPrefix = "--" // DefaultShortPrefix is the default prefix for short option names. DefaultShortPrefix = "-" )
Variables ¶
var ( // ErrNoArgs is returned by Parse if no arguments were given for parsing. ErrNoArgs = errors.New("no arguments") )
var NopHandler = func(Context) error { return nil }
NopHandler is an no-op handler that just returns a nil error. It can be used as a placeholder to skip Command Handler implementation and allow for the command chain execution to continue.
Functions ¶
func Parse ¶
Parse parses config.Arguments into config.Globals then config.Commands. It returns nil on success or an error if one occured. It invokes Config.Parse with a context.Background(). See Config.Parse for more details.
func ParseCtx ¶
Parse parses config.Arguments into config.Globals then config.Commands. It returns nil on success or an error if one occured. It invokes COnfig.Parse with the specified ctx. See Config.Parse for more details.
func PrintCommand ¶
PrintCommand prints command to w idented with ident tabs using config.
func PrintCommands ¶
PrintOptions prints commands to w idented with ident tabs using config.
func PrintCommandsGroup ¶
PrintCommandsGroup prints only the commands without recursing into subcommands.
func PrintCommandsNoOptions ¶
PrintOptions prints commands to w idented with ident tabs using config.
func PrintConfig ¶
PrintConfig prints Globals and Commands to w from config.
func PrintOption ¶
PrintOption prints option to w idented with ident tabs using config.
func PrintOptions ¶
PrintOptions prints options to w idented with ident tabs using config.
func ValidateCommands ¶
ValidateCommands validates that Command instances within commands have non-empty and unique names. It validates commands and their SubCommands in the same manner recursively. Returns nil on success.
func ValidateOptions ¶
ValidateOptions validates that Option instances within options have unique and non-empty long names and that short names, if not empty, are unique as well. Returns nil on success.
Types ¶
type Args ¶
type Args []string
Args is a slice of strings containing arguments to parse and implements a few helpers to tokenize, scan and process the slice.
It is used by [Commands.parse] and [Options.parse].
func (Args) First ¶
First returns first element of the slice, unmodified. If slice is empty returns an empty string.
type Argument ¶
type Argument int
Argument defines the kind of argument being parsed.
const ( // NoArgument indicates no argument. It's returned if Arguments are empty. NoArgument Argument = iota // LongArgument indicates a token with a long option prefix. LongArgument // ShortArgument indicates a token with a short option prefix. ShortArgument // TextArgument indicates a text token with no prefix. TextArgument )
type Command ¶
type Command struct { // Name is the name of the Command by which it is invoked from arguments. // Command name is required, must not be empty and must be unique in // Commands. Name string // Help is the short Command help text displayed in command listing that // should prefferably fit the standard width of a terminal. Help string // Doc is the command documentation, a longer text displayed when additional // command details in addition to [Command.Help] are requested. Doc string // Handler is the function to call when the Command gets invoked from // arguments during parsing. // // A command without a handler will generate an error. You can use // [NopHandler] as handler placeholder. Handler Handler // SubCommands are this Command's sub commands. Command invocation can be // chained as described in the Parse method. SubCommands are optional. SubCommands Commands // Options are this Command's options. Options are optional :| Options Options // RequireSubExecution if true, will raise an error if none of this // Command's SubCommands were executed. The setting is ignored if Command // has no SubCommands defined. // // Default: false RequireSubExecution bool // ExclusivityGroups are the exclusivity groups for this Command's Options. // If more than one Option from an ExclusivityGroup is passed in arguments // Parse/ParseCtx will return an error. // // If no ExclusivityGroups are defined no checking is performed. ExclusivityGroups ExclusivityGroups // contains filtered or unexported fields }
Command defines a command invocable by name.
func HelpCommand ¶
HelpCommand is a utility function that returns a command that handles "help" using HelpHandler.
type Commands ¶
type Commands []*Command
Commands holds a set of Commands. Commands are never sorted and the order in which they are declared is important to the Print function which prints the Commands in the same order.
func (Commands) AnyExecuted ¶
AnyExecuted returns true if any commands in Commands was executed.
func (*Commands) Handle ¶
Handle is a helper that registers a new Command from arguments. It returns the newly registered command.
func (*Commands) Register ¶
Register is a helper that registers a fully defined Command and returns self.
func (Commands) Reset ¶
func (self Commands) Reset()
Reset resets all command and command otpion states recursively.
func (Commands) Walk ¶
func (self Commands) Walk(f VisitCommand)
Walk calls f for each command in self, recursively. Order is top-down, i.e. parents first.
func (Commands) WalkExecuted ¶
func (self Commands) WalkExecuted(f VisitCommand)
WalkExecuted calls f for each executed command in self, recursively. Order is top-down, i.e. parents first.
func (Commands) WalkNotExecuted ¶
func (self Commands) WalkNotExecuted(f VisitCommand)
WalkNotExecuted calls f for each not executed command in self, recursively. Order is top-down, i.e. parents first.
type Config ¶
type Config struct { // Args are the arguments to parse. This is usually set to os.Args[1:]. Args Args // Usage is a function to call when no arguments are given to Parse. // // If unset, invokes the built in [Config.PrintUsage]. [Parse] will still // return [ErrNoArgs]. Usage func() // Output is the output for printing usage. // // It is nil by default in which case all the output goes to os.Stdout. Output io.Writer // Globals are the global Options, independant of any defined commands. // // They are parsed from arguments that precede any command invocation. // Their state can be inspected either from [Config.GlobalsHandler] or // after parsing by inspecting the Globals directly. Globals Options // GlobalsHandler is an optional handler for Globals. // // It is invoked if any global options get parsed and before any command // handlers are invoked. // // If it returns an error no commands will be parsed and the error // propagated back to the caller. GlobalsHandler Handler // GlobalExclusivityGroups are exclusivity groups for Globals. GlobalExclusivityGroups ExclusivityGroups // Commands is the root command set. Commands Commands // UseAssignment requires that [Option] value must be given using an // assignment operator such that option name is immediately followed by an // assignment operator then immediately with the option value. // E.g: '--key=value' instead of '--key value'. // // Default: false UseAssignment bool // IndexedFirst requires that Indexed Options are specified before any // other type of [Option] in [Options]. // // If disabled, arguments to Indexed options may be specifies in between // other types of [Option] but in order as they are defined in [Options]. // // Default: false IndexedFirst bool // ExecAllHandlers specifies that handlers of all commands in the execution // chain parsed from Args will be executed in order as specified. // // First [Handler] in the chain that returns an error stops the chain // execution and the error is passed back to the caller. // // If false only the handler of the last command in the chain is invoked. // // Default: false ExecAllHandlers bool // LongPrefix is the long Option prefix to use. It is optional and is // defaulted to DefaultLongPrefix by Parse() if left empty. LongPrefix string // ShortPrefix is the short Option prefix to use. It is optional and is // defaulted to DefaultShortPrefix by Parse() if left empty. ShortPrefix string // PrintInDefinedOrder if true makes the print functions print options in // the order they were defined. // // If disabled options are printed in groups by type: // Boolean, Optional, Required, Repeated, Indexed, Variadic // then by order of definition. // // Default: false. PrintInDefinedOrder bool // NoPrintUsage if true does not print the usage if no arguments were // given for parsing // // Default: false. NoPrintUsage bool // contains filtered or unexported fields }
Config is the command line parser configuration.
It contains global option definitions ([Config.Globals]), commands [Config.Commands], arguments to parse ([Config.Args]) and various other options that control the parse behaviour.
See Config.Parse on details how Config is used and rules for how [Config.Args] are parsed.
func DefaultOS ¶
func DefaultOS() *Config
DefaultOS returns Default with os.Args[1:]... as arguments.
func (*Config) GetOutput ¶
GetOutput returns the output to write to. If [Config.Output] is set it returns that, if not returns [defaultOutput].
func (*Config) Parse ¶
Parse parses [Config.Args] into [Config.Globals] then [Config.Commands] and their Options, recursively.
Both [Config.Globals] and [Config.Commands] are optional and if none are defined in the Config, Parse will not parse any arguments and return nil regardless if any arguments were given. In every case of no arguments it returns ErrNoArgs.
Parse will first parse [Config.Globals] and call[Config.GlobalsHandler] if set after they have been parsed. If no [Config.GlobalsHandler] is set, [Config.Globals] may be inspected manually from the Config after parse.
Parse then continues matching the following argument to a Command, parsing Options for that Command. If this is the last command in the command execution chain or [Config.ExecAllHandlers] is true, Command's Handler is executed.
If the Command contains sub Commands and there are unparsed arguments left, it continues parsing arguments into that Command's sub Commands.
If an undefined Command or Option was specified, either due to a typo or malformatted arguments Parse will return a descriptive error.
If no arguments were given Parse will call [Config.Usage] if set or call Config.PrintUsage if not. In both cases returns ErrNoArgs.
If a Command handler returns an error the parse process is immediately aborted and the error propagated back to the Parse/ParseCtx caller.
Parse first runs the validation pass that checks that the Config definition is valid and well formatted.
Following validation rules are enforced before the parse process and will return a descriptive error if any validation fails:
* There may be no duplicate Command instance names per their Commands group. * There may be no duplicate Option instance names within their Options group. For more details see Command, Option, ValidateOptions and ValidateCommands.
* If an Options set contains a Variadic Option which consumes all following arguments as value to self, there may be no Command invocations following it.
This means that if [Config.Globals] contains a Variadic Option there may be no [Config.Commands] defined. This is also the case for a Command at any level as Variadic Option in Command's Options consume all following arguments in the same way.
During Option parsing, if an Option has a mapped variable its value will be set at option parse time. See Option for details.
func (*Config) PrintUsage ¶
func (self *Config) PrintUsage()
Usage prints the default autogenerated usage text to Stdout. It is called in the case of no arguments if no Config.Usage is set and may be called manually.
type Context ¶
type Context interface { // Context embeds the standard Context. // // It might carry a timeout, deadline or values available to invoked // Command Handler. It will be the context given to ParseCtx or // context.Background if Parse was used. context.Context // Parsed returns true if an [Option] with specified LongName was parsed. Parsed(string) bool // Values returns an array of strings that were passed to the // [Option] under specified LongName or Name. // // Unparsed Options and options that take no arguments return nil. Values(string) Values // Config returns the config that is being used to parse. Config() *Config // Command returns the owner [Command] of the handler this Context is // inspcted from. // // If this handler is the global options handler result will be nil. Command() *Command // ParentCommand returns the parent command of this handler's [Command]. // // It may return nil if this command has no parent command or if this // handler is the global options handler. ParentCommand() *Command // Options returns this Command's Options. Options() Options }
Context is passed to the Command handler that allows inspection of Command's Options states. It wraps the standard context passed to Config.Parse possibly via Parse or ParseCtx.
type ExclusivityGroup ¶
type ExclusivityGroup []string
ExclusivityGroup defines a group of option names which are mutually exclusive and may not be passed together to a command at the same time.
type ExclusivityGroups ¶
type ExclusivityGroups []ExclusivityGroup
ExclusivityGroups is a group of ExclusivityGroup used to define more than one ExclusivityGroup.
type Handler ¶
Handler is a Command invocation callback prototype. It carries a Command Context which allows inspection of the parse state.
If the handler returns a nil error the parser continues the command chain execution.
If the Handler returns a non-nil error the parser aborts the command chain execution and the error is pushed back to the Set.Parse() caller.
type Kind ¶
type Kind int
Kind specifies the kind of an Option.
It defines the Option behaviour and how it parses its arguments.
const ( // Invalid is an invalid, undefined or unknown type of option. Invalid Kind = iota // Boolean is a boolean Option. // // A Boolean option is an option that takes no arguments. It is marked as // parsed if it was specified in command arguments. Boolean // Optional is an optional Option. // // It will not return an error during parse if it was not specified in // command arguments. // // It takes a single value. Optional // Required is a required Option. // // A required option is an option which raises an error if not parsed from // arguments. It takes a value in the same way as [Optional]. Required // Repeated is a repeated Option. // // Repeated option is an optional option that can be specified one or more // times. Each value give to an invocation of this option is appended to the // Option's RawValues slice. Repeated // Indexed is an indexed Option. // // An indexed option is an option that is not qualified by name when passed // to a Command but is instead matched by index of being defined in // Command's Options to index of an argument to the Command. // // Indexed options are parsed after named Options and their values must be // given after any and all named options that are to be set. Index of the // argument is counted from 0 after all named arguments were given. // // In this example the "indexedOptionValue" is the value for the first // Indexed Option defined in Options: // // myprog.exe somecommand --namedOption=namedOptionValue indexedOptionValue // // Indexed options may be declared at any point in between other types of // options in Options but the order in which Indexed options are declared // is important and defines the index of the Indexed command. // // An Indexed option is required and will raise an error if not parsed. Indexed // Variadic is a variadic Option. // // A Variadic Option is an option that takes any and all unparsed arguments // as an single argument to this Option. // // For that reason a Variadic Option's Parent Options may have no // Sub-Options. // // Variadic option is parsed after all other options and consumes all // unused arguments as arguments to self. // // There may only be a single variadic option in [Options]. Variadic )
type Option ¶
type Option struct { // LongName is the long, more descriptive option name. // // It must contain no spaces and must be unique in Options as it is the // primary key for Option addressing. // // It is used as the Name for [Indexed] and [Variadic] options in // registration methods. Those options cannot be addressed directly in // arguments and so require no [Option.ShortName]. // // An argument with a long prefix is matched against this property. LongName string // ShortName is the option short name. // // ShortName consists of a single alphanumeric. It is optional and if not // empty must be unique in all Options ShortName properties. // // [Indexed] and [Variadic] options do not use ShortName. // // An argument with a short prefix is matched against this property. ShortName string // Help is the option help text. // // It should be a short, single line description of the option. Help string // IsParsed indicates if the Option was parsed from arguments. // // For Repeated Options it indicates that the Option was parsed at least // once. IsParsed bool // Kind is the kind of option which determines how the Option parses // its arguments. // // See [Kind] for details. Kind // Values contains any string values passed to the option in arguments. // // How Values is parsed depends on [Option.Kind]. Values // Var is an optional pointer to a variable that will be set from Option // argument(s). // // Only basic types are supported and a slice of string. Var any }
Option defines an option.
Several option types exist and define how option is parsed. For details see Kind enum set for details.
An Option can map to a variable whose value is set from the option value via [Option.Var] which must be a pointer to a supported type or any type that supports conversion from a string by implementing the Value interface.
Supported types are: *bool, *string, *float32, *float64, *int, *int8, *int16, *1nt32, *int64, *uint, *uint8, *uint16, *u1nt32, *uint64 *time.Duration, *[]string, and any type supporting Value interface.
If an unsupported type was set as [Option.Var] Parse will return a conversion error.
type Options ¶
type Options []*Option
Options contains and manages a set of Options.
Options are never sorted and the order in which Options are declared is importan; Print lists them in the oder they were declared and Indexed options are matched to indexes of their arguments.
func (*Options) BooleanVar ¶
Boolean registers a new Boolean option in self and returns self.
func (*Options) IndexedVar ¶
Indexed registers a new indexed option in self and returns self.
func (*Options) OptionalVar ¶
Optional registers a new optional option in self and returns self.
func (*Options) RepeatedVar ¶
Repeated registers a new repeated option in self and returns self.
func (*Options) RequiredVar ¶
Required registers a new required option in self and returns self.
func (Options) Reset ¶
func (self Options) Reset()
Reset resets all options to initial parse state. It does not modify the linked variable.
type Value ¶
type Value interface { // String must return a string representation of the type. String() string // Set must parse a string into self or return an error if it failed. Set(Values) error }
Value defines a type that is capable of parsing a string into a value it represents.
Options support parsing aruments in types that satisfy the Value interface. A Value can be set as a target Var in an Option.
type Values ¶
type Values []string
Values is a helper alias for a slice of strings representing arguments passed to an Option. It implements several utilities for retrieving values.
type VisitCommand ¶
VisitCommand is a prototype of a function called for each Command visited. It must return true to continue enumeration.