Documentation ¶
Overview ¶
argparse is a Golang command line argument parsing library, taking heavy influance from Python's argparse module.
Using argparse, it is possible to easily create command-line interfaces, such as:
> exc --help usage: main [-h] [-v] [-e] [-x ...] [-n] [-f] [-k] [p PATTERN] [s SPLIT] [c CHAR] Construct and execute arguments from Stdin positional arguments: [p PATTERN] Stdin regex grouping pattern [s SPLIT] Delimiting regex for Stdin [c CHAR] Replacement string for argument parsing optional arguments: -h, --help Show program help -v, --version Show program version -e, --empty Allow empty text -x, --exec Pasrable command string -n, --dry-run Output commands instead of executing -f, --force Force continue command execution upon errored commands -k, --keep-newline Allow trailing newline from Stdin
Much of the heavy lifting for creating a cmd-line interface is managed by argparse, so you can focus on getting your program created and running.
For example, the code required to create the above interface is as follows:
import ( "github.com/clagraff/argparse" ) func main() { p := argparse.NewParser("Construct and execute arguments from Stdin").Version("0.0.0") p.AddHelp().AddVersion() // Enable `--help` & `-h` to display usage text to the user. pattern := argparse.NewArg("p pattern", "pattern", "Stdin regex grouping pattern").Default(".*") split := argparse.NewArg("s split", "split", "Delimiting regex for Stdin").Default("\n") nonEmpty := argparse.NewOption("e empty", "empty", "Allow empty text") keepNewline := argparse.NewFlag("k keep-newline", "keep-newline", "Allow trailing newline from Stdin").Default("false") command := argparse.NewOption("x exec", "exec", "Pasrable command string").Nargs("r").Action(argparse.Store) replacementChar := argparse.NewArg("c char", "char", "Replacement string for argument parsing").Default("%") dryRun := argparse.NewFlag("n dry-run", "dry", "Output commands instead of executing") ignoreErrors := argparse.NewFlag("f force", "force", "Force continue command execution upon errored commands") p.AddOptions(pattern, split, nonEmpty, command, replacementChar, dryRun, ignoreErrors, keepNewline) ns, _, err := p.Parse(os.Args[1:]...) switch err.(type) { case argparse.ShowHelpErr: return case error: fmt.Println(err, "\n") p.ShowHelp() return }
To get started, all you need is a Parser and a few Options!
Index ¶
- func Append(p *Parser, f *Option, args ...string) ([]string, error)
- func AppendConst(p *Parser, f *Option, args ...string) ([]string, error)
- func ShowHelp(p *Parser, f *Option, args ...string) ([]string, error)
- func ShowVersion(p *Parser, f *Option, args ...string) ([]string, error)
- func Store(p *Parser, f *Option, args ...string) ([]string, error)
- func StoreConst(p *Parser, f *Option, args ...string) ([]string, error)
- func StoreFalse(p *Parser, f *Option, args ...string) ([]string, error)
- func StoreTrue(p *Parser, f *Option, args ...string) ([]string, error)
- func ValidateChoice(f Option, arg string) error
- func ValidateType(f Option, arg string) error
- type Action
- type InvalidChoiceErr
- type InvalidFlagNameErr
- type InvalidOptionErr
- type InvalidParserNameErr
- type InvalidTypeErr
- type MissingOneOrMoreArgsErr
- type MissingOptionErr
- type MissingParserErr
- type Namespace
- func (n *Namespace) Get(key string) interface{}
- func (n *Namespace) KeyExists(key string) bool
- func (n *Namespace) Require(keys ...string) error
- func (n *Namespace) Set(key string, value interface{}) *Namespace
- func (n *Namespace) Slice(key string) []string
- func (n *Namespace) String(key string) string
- func (n *Namespace) Try(key string) (interface{}, error)
- type Option
- func (f *Option) Action(action Action) *Option
- func (f *Option) Choices(choices ...string) *Option
- func (f *Option) Const(value string) *Option
- func (f *Option) Default(value string) *Option
- func (f *Option) Dest(name string) *Option
- func (f *Option) DisplayName() string
- func (f *Option) GetChoices() string
- func (f *Option) GetUsage() string
- func (f *Option) Help(text string) *Option
- func (f *Option) IsPublicName(name string) bool
- func (f *Option) MetaVar(meta string, metaSlice ...string) *Option
- func (f *Option) Nargs(nargs interface{}) *Option
- func (f *Option) NotPositional() *Option
- func (f *Option) NotRequired() *Option
- func (f *Option) Positional() *Option
- func (f *Option) Required() *Option
- func (f *Option) String() string
- func (f *Option) Type(kind reflect.Kind) *Option
- type Parser
- func (p *Parser) AddHelp() *Parser
- func (p *Parser) AddOption(f *Option) *Parser
- func (p *Parser) AddOptions(opts ...*Option) *Parser
- func (p *Parser) AddParser(name string, parser *Parser) *Parser
- func (p *Parser) AddVersion() *Parser
- func (p *Parser) GetHelp() string
- func (p *Parser) GetOption(name string) (*Option, error)
- func (p Parser) GetParser(name string) (*Parser, error)
- func (p *Parser) GetVersion() string
- func (p *Parser) Parse(allArgs ...string)
- func (p *Parser) Path(progPath string) *Parser
- func (p *Parser) Prog(name string) *Parser
- func (p *Parser) ShowHelp() *Parser
- func (p *Parser) ShowVersion() *Parser
- func (p *Parser) Usage(usage string) *Parser
- func (p *Parser) Version(version string) *Parser
- type ShowHelpErr
- type ShowVersionErr
- type SubParser
- type TooFewArgsErr
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Append ¶
Append retrives the appropriate number of argumnents for the current option, (if any), and appends them individually into the parser. Remaining arguments and errors are returned.
func AppendConst ¶
AppendConst appends the option's constant value into the parser. Provided arguments remain unmodified.
func ShowHelp ¶
ShowHelp calls the parser's ShowHelp function to output parser usage information and help information for each option to stdout. Provided arguments remain unchanged. It returns a ShowHelpErr error instance, used to prevent further parsing.
func ShowVersion ¶
ShowVersion calls the parser's ShowVersion function to output parser/program version information. Provided arguments remain unchanged. It returns a ShowVersionErr instance, used to prevent further parsing.
func Store ¶
Store will attempt to store the appropriate number of arguments for the option, (if any), into the parser. Remaining arguments & any errors are returned.
func StoreConst ¶
StoreConst stores the option's constant value into the parser. Provided arguments remain unmodified.
func StoreFalse ¶
StoreFalse stores a boolean `false` into the parser. Provided arguments remain unmodified.
func StoreTrue ¶
StoreTrue stores a boolean `true` into the parser. Provided arguments remain unmodified.
func ValidateChoice ¶
ValidateChoice returns an error if the provided interface value does not exists as valid choice for the provided flag.
func ValidateType ¶
ValidateType attempt to type-convert the string argument to the flag's desired type. It will return an error if the provided interface value does not satisfy the Option's expected Reflect.Kind type.
Types ¶
type Action ¶
Action is type to represent a callable function which will operate on a parser, a option, and an array of argument strings.
type InvalidChoiceErr ¶
type InvalidChoiceErr struct {
// contains filtered or unexported fields
}
InvalidChoiceErr indicates that an argument is not among the valid choices for the option.
func (InvalidChoiceErr) Error ¶
func (err InvalidChoiceErr) Error() string
Error will return a string error message for the InvalidChoiceErr
type InvalidFlagNameErr ¶
type InvalidFlagNameErr struct {
// contains filtered or unexported fields
}
InvalidFlagNameErr indicates that an argument with the provided public name not exist.
func (InvalidFlagNameErr) Error ¶
func (err InvalidFlagNameErr) Error() string
Error will return a string error message for the InvalidFlagNameErr
type InvalidOptionErr ¶
type InvalidOptionErr struct {
// contains filtered or unexported fields
}
InvalidOptionErr indicates that an option is invalid.
func (InvalidOptionErr) Error ¶
func (err InvalidOptionErr) Error() string
Error will return a string error message for the InvalidFlagNameErr
type InvalidParserNameErr ¶
type InvalidParserNameErr struct {
// contains filtered or unexported fields
}
InvalidParserNameErr indicates that a Command name has already been assigned and cannot be re-assigned.
func (InvalidParserNameErr) Error ¶
func (err InvalidParserNameErr) Error() string
Error will return a string error message for the InvalidParserNameErr
type InvalidTypeErr ¶
type InvalidTypeErr struct {
// contains filtered or unexported fields
}
InvalidTypeErr indicates that an argument cannot be casted the the option's expected type.
func (InvalidTypeErr) Error ¶
func (err InvalidTypeErr) Error() string
Error will return a string error message for the InvalidTypeErr
type MissingOneOrMoreArgsErr ¶
type MissingOneOrMoreArgsErr struct {
// contains filtered or unexported fields
}
MissingOneOrMoreArgsErr indicated that not enough arguments were provided, when one or more arguments were expected, for the option.
func (MissingOneOrMoreArgsErr) Error ¶
func (err MissingOneOrMoreArgsErr) Error() string
Error will return a string error message for the TooFewArgsErr
type MissingOptionErr ¶
type MissingOptionErr struct {
// contains filtered or unexported fields
}
MissingOptionErr indicated that an option was required but is missing.
func (MissingOptionErr) Error ¶
func (err MissingOptionErr) Error() string
Error will return a string error message for the MissingOptionErr
type MissingParserErr ¶
type MissingParserErr struct {
Parsers []SubParser
}
MissingParserErr indicated that commands were available, but none were used.
func (MissingParserErr) Error ¶
func (err MissingParserErr) Error() string
Error will return a string error message for the MissingParserErr
type Namespace ¶
type Namespace struct {
Mapping map[string]interface{}
}
Namespace is a struct for storing the key-value pairings between options' destinations and their associated values.
func (*Namespace) Get ¶
Get will retrieve either a string or a []string if the specified key exists in the mapping. Otherwise, an empty string is returned
func (*Namespace) KeyExists ¶
KeyExists returns a bool indicating true if the key does exist in the mapping, or otherwise false.
func (*Namespace) Slice ¶
Slice will retrieve either a string or a []string if the specified key exists in the mapping. Otherwise, an empty string is returned
type Option ¶
type Option struct { ArgNum string // Any digit, "+", "?", "*", or "r" and "R" to represent how many arguments an option can expect. ConstVal string // A constant value to represent when used with the actions.StoreConst action. DefaultVal string // A value to represent the Option by default. DesiredAction Action // A callback function which will parse an option and its arguments. DestName string // A unique identifier to store an option's value within a namespace. ExpectedType reflect.Kind // The variable-type that an Option's arguments are to be interpretted as. HelpText string // Text describing the usage/meaning of the Option. IsRequired bool // Indicate if an Option must be present when parsing. IsPositional bool // Indicate that an Option is identified by its position when parsing. MetaVarText []string // Text used when representing an Option and its arguments. PublicNames []string // Qualifiers for identifying the option during parsing. ValidChoices []string // A slice of valid choices for arguments of the Option. }
Option contains the necessary attributes for representing a parsable option. You can create a vanilla Option by using the NewOption function, or you can create Flag-type or Argument-type Option using the NewFlag and NewArg functions, respectivly.
An example of using these functions can be seen below:
o := argparse.NewOption("-o", "output", "Enable output") o.Positional().Required().Nargs("0").Action(StoreTrue).Default("false") f := argparse.NewFlag("-n --dry", "dryRun", "Enable dry-run mode") a := argparse.NewArg("--in", "inputPath", "Path to specified input file")
func NewArg ¶
NewArg initializes a new Option pointer, and sets its Nargs to 1, its action to Store, and makes it a positional option.
func NewFlag ¶
NewFlag initializes a new Option pointer, sets its Nargs to 0, its action to StoreTrue, and its default value to false.
func NewOption ¶
NewOption instantiates a new Option pointer, initializing it as a boolean flag. Multiple names should be delimited by a space; names should not contain the prefix character.
func (*Option) Const ¶
Const sets the option's constant value to the provided interface. A option's constant value is only used for certain actions. By default, the constant value is `nil`.
func (*Option) Default ¶
Default sets the option's default value. A option's default value is only used for certain actions. By default, the default value is `nil`.
func (*Option) Dest ¶
Dest sets a option's destination name. This is used as the key for storing the option's values within the parser.
func (*Option) DisplayName ¶
DisplayName returns the option's public name, prefixed with the appropriate number of hyphen-minus characters.
func (*Option) GetChoices ¶
GetChoices returns a string-representation of the valid chocies for the current Option.
func (*Option) GetUsage ¶
GetUsage returns the usage text for the option. This includes proper formatting of the option's display name & parameters. For parameters: by default, parameters will be the option's public name. This can be overridden by modifying the MetaVars slice for the option.
func (*Option) IsPublicName ¶
func (*Option) MetaVar ¶
MetaVar sets the option's metavar text to the provided string. Additional metavar strings can be provided, and will be used for options with more than expected argument.
func (*Option) Nargs ¶
Nargs sets the option's number of expected arguments. Integers represent the absolute number of arguments to be expected. The `?` character represents an expection of zero or one arguments. The `*` character represents an expectation of any number or arguments. The `+` character represents an expectation of one or more arguments. The `r` and `R` characters represent using all arguments not used after the initial parsing of options.
func (*Option) NotPositional ¶
NotPositional disables a option from being positionally interpretted.
func (*Option) NotRequired ¶
NotRequired prevents the option from being required to be present when parsing arguments.
func (*Option) Positional ¶
Positional enables a option to be positionally interpretted.
func (*Option) Required ¶
Required enables the option to required to be present when parsing arguments.
type Parser ¶
type Parser struct { Callback func(*Parser, *Namespace, []string, error) ProgramName string AllowAbbrev bool Options []*Option Parsers []SubParser UsageText string VersionDesc string Namespace *Namespace }
Parser contains program-level settings and information, stores options, and values collected upon parsing.
func NewParser ¶
NewParser returns an instantiated pointer to a new parser instance, with a description matching the provided string.
func (*Parser) AddHelp ¶
AddHelp adds a new option to output usage information for the current parser and each of its options.
func (*Parser) AddOptions ¶
AddOptions appends the provided options to the current parser.
func (*Parser) AddParser ¶
AddParser appends the provided parse to the current parser as an available command.
func (*Parser) AddVersion ¶
AddVersion adds a new option to the program version.
func (*Parser) GetHelp ¶
GetHelp returns a string containing the parser's description text, and the usage information for each option currently incorperated within the parser.
func (*Parser) GetOption ¶
GetOption retrieves the first option with a public name matching the specified name, or will otherwise return an error.
func (Parser) GetParser ¶
GetParser retrieves the desired sub-parser from the current parser, or returns an error if the desired parser does not exist.
func (*Parser) GetVersion ¶
GetVersion will return the version text for the current parser.
func (*Parser) Parse ¶
Parser accepts a slice of strings as options and arguments to be parsed. The parser will call each encountered option's action. Unexpected options will cause an error. All errors are returned.
func (*Parser) Path ¶
Path will set the parser's program name to the program name specified by the provided path.
func (*Parser) ShowVersion ¶
ShowVersion outputs to stdout the parser's generated versioning text.
type ShowHelpErr ¶
type ShowHelpErr struct{}
ShowHelpErr indicates that the program was instructed to show it's help text.
func (ShowHelpErr) Error ¶
func (err ShowHelpErr) Error() string
type ShowVersionErr ¶
type ShowVersionErr struct{}
ShowVersionErr indicates that the program was instructed to show it's versioning text.
func (ShowVersionErr) Error ¶
func (err ShowVersionErr) Error() string
type TooFewArgsErr ¶
type TooFewArgsErr struct {
// contains filtered or unexported fields
}
TooFewArgsErr indicated that not enough arguments were provided for the option.
func (TooFewArgsErr) Error ¶
func (err TooFewArgsErr) Error() string
Error will return a string error message for the TooFewArgsErr