Documentation
¶
Overview ¶
Package kingpin provides command line interfaces like this:
$ chat usage: chat [<flags>] <command> [<flags>] [<args> ...] Flags: --debug enable debug mode --help Show help. --server=127.0.0.1 server address Commands: help <command> Show help for a command. post [<flags>] <channel> Post a message to a channel. register <nick> <name> Register a new user. $ chat help post usage: chat [<flags>] post [<flags>] <channel> [<text>] Post a message to a channel. Flags: --image=IMAGE image to post Args: <channel> channel to post to [<text>] text to post $ chat post --image=~/Downloads/owls.jpg pics
From code like this:
package main import "gopkg.in/alecthomas/kingpin.v1" var ( debug = kingpin.Flag("debug", "enable debug mode").Default("false").Bool() serverIP = kingpin.Flag("server", "server address").Default("127.0.0.1").IP() register = kingpin.Command("register", "Register a new user.") registerNick = register.Arg("nick", "nickname for user").Required().String() registerName = register.Arg("name", "name of user").Required().String() post = kingpin.Command("post", "Post a message to a channel.") postImage = post.Flag("image", "image to post").ExistingFile() postChannel = post.Arg("channel", "channel to post to").Required().String() postText = post.Arg("text", "text to post").String() ) func main() { switch kingpin.Parse() { // Register user case "register": println(*registerNick) // Post message case "post": if *postImage != nil { } if *postText != "" { } } }
nolint: golint
Index ¶
- Variables
- func Errorf(format string, args ...interface{})
- func ExpandArgsFromFile(filename string) (out []string, err error)
- func FatalIfError(err error, format string, args ...interface{})
- func FatalUsage(format string, args ...interface{})
- func FatalUsageContext(context *ParseContext, format string, args ...interface{})
- func Fatalf(format string, args ...interface{})
- func JSONConfigClause(app *Application, clause *Clause) *string
- func MustParse(command string, err error) string
- func Parse() string
- func SetLanguage(lang string, others ...string) error
- func TError(msg string, args ...interface{}) error
- func Usage()
- type AccumulatorOption
- type Action
- type Application
- func (a *Application) Action(action Action) *Application
- func (a *Application) Author(author string) *Application
- func (c *Application) CmdCompletion(context *ParseContext) []string
- func (a *Application) Command(name, help string) *CmdClause
- func (a *Application) DefaultEnvars() *Application
- func (a *Application) EnvarSeparator(sep string) *Application
- func (a *Application) Errorf(format string, args ...interface{})
- func (a *Application) FatalIfError(err error, format string, args ...interface{})
- func (a *Application) FatalUsage(format string, args ...interface{})
- func (a *Application) FatalUsageContext(context *ParseContext, format string, args ...interface{})
- func (a *Application) Fatalf(format string, args ...interface{})
- func (c *Application) FlagCompletion(flagName string, flagValue string) (choices []string, flagMatch bool, optionMatch bool)
- func (a *Application) Interspersed(interspersed bool) *Application
- func (a *Application) Model() *ApplicationModel
- func (a *Application) Parse(args []string) (command string, err error)
- func (a *Application) ParseContext(args []string) (*ParseContext, error)
- func (a *Application) PreAction(action Action) *Application
- func (a *Application) Resolver(resolvers ...Resolver) *Application
- func (a *Application) Struct(v interface{}) error
- func (a *Application) Terminate(terminate func(int)) *Application
- func (a *Application) Usage(args []string)
- func (a *Application) UsageContext(context *UsageContext) *Application
- func (a *Application) UsageForContext(context *ParseContext) error
- func (a *Application) UsageForContextWithTemplate(usageContext *UsageContext, parseContext *ParseContext) error
- func (a *Application) UsageTemplate(template string) *Application
- func (a *Application) Version(version string) *Application
- func (a *Application) Writers(out, err io.Writer) *Application
- type ApplicationModel
- type ArgGroupModel
- type BoolFlag
- type Clause
- func (c *Clause) Action(action Action) *Clause
- func (p *Clause) Bool() (target *bool)
- func (p *Clause) BoolList(options ...AccumulatorOption) (target *[]bool)
- func (p *Clause) BoolListVar(target *[]bool, options ...AccumulatorOption)
- func (p *Clause) BoolVar(target *bool)
- func (c *Clause) Bytes() (target *units.Base2Bytes)
- func (c *Clause) BytesVar(target *units.Base2Bytes)
- func (c *Clause) Counter() (target *int)
- func (c *Clause) CounterVar(target *int)
- func (c *Clause) Default(values ...string) *Clause
- func (p *Clause) Duration() (target *time.Duration)
- func (p *Clause) DurationList(options ...AccumulatorOption) (target *[]time.Duration)
- func (p *Clause) DurationListVar(target *[]time.Duration, options ...AccumulatorOption)
- func (p *Clause) DurationVar(target *time.Duration)
- func (c *Clause) Enum(options ...string) (target *string)
- func (c *Clause) EnumVar(target *string, options ...string)
- func (c *Clause) Enums(options ...string) (target *[]string)
- func (c *Clause) EnumsVar(target *[]string, options ...string)
- func (c *Clause) Envar(name string) *Clause
- func (c *Clause) ExistingDir() (target *string)
- func (c *Clause) ExistingDirVar(target *string)
- func (p *Clause) ExistingDirs(options ...AccumulatorOption) (target *[]string)
- func (p *Clause) ExistingDirsVar(target *[]string, options ...AccumulatorOption)
- func (c *Clause) ExistingFile() (target *string)
- func (c *Clause) ExistingFileOrDir() (target *string)
- func (c *Clause) ExistingFileOrDirVar(target *string)
- func (c *Clause) ExistingFileVar(target *string)
- func (p *Clause) ExistingFiles(options ...AccumulatorOption) (target *[]string)
- func (p *Clause) ExistingFilesOrDirs(options ...AccumulatorOption) (target *[]string)
- func (p *Clause) ExistingFilesOrDirsVar(target *[]string, options ...AccumulatorOption)
- func (p *Clause) ExistingFilesVar(target *[]string, options ...AccumulatorOption)
- func (c *Clause) Float() (target *float64)
- func (p *Clause) Float32() (target *float32)
- func (p *Clause) Float32List(options ...AccumulatorOption) (target *[]float32)
- func (p *Clause) Float32ListVar(target *[]float32, options ...AccumulatorOption)
- func (p *Clause) Float32Var(target *float32)
- func (p *Clause) Float64() (target *float64)
- func (p *Clause) Float64List(options ...AccumulatorOption) (target *[]float64)
- func (p *Clause) Float64ListVar(target *[]float64, options ...AccumulatorOption)
- func (p *Clause) Float64Var(target *float64)
- func (c *Clause) FloatVar(target *float64)
- func (c *Clause) Help(help string) *Clause
- func (p *Clause) HexBytes() (target *[]byte)
- func (p *Clause) HexBytesList(options ...AccumulatorOption) (target *[][]byte)
- func (p *Clause) HexBytesListVar(target *[][]byte, options ...AccumulatorOption)
- func (p *Clause) HexBytesVar(target *[]byte)
- func (c *Clause) Hidden() *Clause
- func (c *Clause) HintAction(action HintAction) *Clause
- func (c *Clause) HintOptions(options ...string) *Clause
- func (c *Clause) IP() (target *net.IP)
- func (p *Clause) IPList(options ...AccumulatorOption) (target *[]net.IP)
- func (p *Clause) IPListVar(target *[]net.IP, options ...AccumulatorOption)
- func (c *Clause) IPVar(target *net.IP)
- func (p *Clause) Int() (target *int)
- func (p *Clause) Int16() (target *int16)
- func (p *Clause) Int16List(options ...AccumulatorOption) (target *[]int16)
- func (p *Clause) Int16ListVar(target *[]int16, options ...AccumulatorOption)
- func (p *Clause) Int16Var(target *int16)
- func (p *Clause) Int32() (target *int32)
- func (p *Clause) Int32List(options ...AccumulatorOption) (target *[]int32)
- func (p *Clause) Int32ListVar(target *[]int32, options ...AccumulatorOption)
- func (p *Clause) Int32Var(target *int32)
- func (p *Clause) Int64() (target *int64)
- func (p *Clause) Int64List(options ...AccumulatorOption) (target *[]int64)
- func (p *Clause) Int64ListVar(target *[]int64, options ...AccumulatorOption)
- func (p *Clause) Int64Var(target *int64)
- func (p *Clause) Int8() (target *int8)
- func (p *Clause) Int8List(options ...AccumulatorOption) (target *[]int8)
- func (p *Clause) Int8ListVar(target *[]int8, options ...AccumulatorOption)
- func (p *Clause) Int8Var(target *int8)
- func (p *Clause) IntVar(target *int)
- func (p *Clause) Ints(options ...AccumulatorOption) (target *[]int)
- func (p *Clause) IntsVar(target *[]int, options ...AccumulatorOption)
- func (f *Clause) Model() *ClauseModel
- func (p *Clause) NegatableBool() (target *bool)
- func (p *Clause) NegatableBoolList(options ...AccumulatorOption) (target *[]bool)
- func (p *Clause) NegatableBoolListVar(target *[]bool, options ...AccumulatorOption)
- func (p *Clause) NegatableBoolVar(target *bool)
- func (c *Clause) NoEnvar() *Clause
- func (c *Clause) PlaceHolder(placeholder string) *Clause
- func (c *Clause) PreAction(action Action) *Clause
- func (p *Clause) Regexp() (target **regexp.Regexp)
- func (p *Clause) RegexpList(options ...AccumulatorOption) (target *[]*regexp.Regexp)
- func (p *Clause) RegexpListVar(target *[]*regexp.Regexp, options ...AccumulatorOption)
- func (p *Clause) RegexpVar(target **regexp.Regexp)
- func (c *Clause) Required() *Clause
- func (c *Clause) SetValue(value Value)
- func (c *Clause) Short(name rune) *Clause
- func (p *Clause) String() (target *string)
- func (c *Clause) StringMap(options ...AccumulatorOption) (target *map[string]string)
- func (c *Clause) StringMapVar(target *map[string]string, options ...AccumulatorOption)
- func (p *Clause) StringVar(target *string)
- func (p *Clause) Strings(options ...AccumulatorOption) (target *[]string)
- func (p *Clause) StringsVar(target *[]string, options ...AccumulatorOption)
- func (p *Clause) Time(format string) (target *time.Time)
- func (p *Clause) TimeList(format string, options ...AccumulatorOption) (target *[]time.Time)
- func (p *Clause) TimeListVar(format string, target *[]time.Time, options ...AccumulatorOption)
- func (p *Clause) TimeVar(format string, target *time.Time)
- func (p *Clause) URL() (target **url.URL)
- func (p *Clause) URLList(options ...AccumulatorOption) (target *[]*url.URL)
- func (p *Clause) URLListVar(target *[]*url.URL, options ...AccumulatorOption)
- func (p *Clause) URLVar(target **url.URL)
- func (p *Clause) Uint() (target *uint)
- func (p *Clause) Uint16() (target *uint16)
- func (p *Clause) Uint16List(options ...AccumulatorOption) (target *[]uint16)
- func (p *Clause) Uint16ListVar(target *[]uint16, options ...AccumulatorOption)
- func (p *Clause) Uint16Var(target *uint16)
- func (p *Clause) Uint32() (target *uint32)
- func (p *Clause) Uint32List(options ...AccumulatorOption) (target *[]uint32)
- func (p *Clause) Uint32ListVar(target *[]uint32, options ...AccumulatorOption)
- func (p *Clause) Uint32Var(target *uint32)
- func (p *Clause) Uint64() (target *uint64)
- func (p *Clause) Uint64List(options ...AccumulatorOption) (target *[]uint64)
- func (p *Clause) Uint64ListVar(target *[]uint64, options ...AccumulatorOption)
- func (p *Clause) Uint64Var(target *uint64)
- func (p *Clause) Uint8() (target *uint8)
- func (p *Clause) Uint8List(options ...AccumulatorOption) (target *[]uint8)
- func (p *Clause) Uint8ListVar(target *[]uint8, options ...AccumulatorOption)
- func (p *Clause) Uint8Var(target *uint8)
- func (p *Clause) UintVar(target *uint)
- func (p *Clause) Uints(options ...AccumulatorOption) (target *[]uint)
- func (p *Clause) UintsVar(target *[]uint, options ...AccumulatorOption)
- func (c *Clause) UsageAction(context *UsageContext) *Clause
- func (c *Clause) UsageActionTemplate(template string) *Clause
- type ClauseModel
- type CmdClause
- func (c *CmdClause) Action(action Action) *CmdClause
- func (c *CmdClause) Alias(name string) *CmdClause
- func (c *CmdClause) CmdCompletion(context *ParseContext) []string
- func (c *CmdClause) Command(name, help string) *CmdClause
- func (c *CmdClause) Default() *CmdClause
- func (c *CmdClause) FlagCompletion(flagName string, flagValue string) (choices []string, flagMatch bool, optionMatch bool)
- func (c *CmdClause) FullCommand() string
- func (c *CmdClause) Hidden() *CmdClause
- func (c *CmdClause) Model(parent *CmdModel) *CmdModel
- func (c *CmdClause) OptionalSubcommands() *CmdClause
- func (c *CmdClause) PreAction(action Action) *CmdClause
- func (c *CmdClause) Struct(v interface{}) error
- func (c *CmdClause) Validate(validator CmdClauseValidator) *CmdClause
- type CmdClauseValidator
- type CmdGroupModel
- type CmdModel
- type FlagGroupModel
- type Getter
- type HintAction
- type OneOfClause
- type ParseContext
- func (p *ParseContext) Args() []*Clause
- func (p *ParseContext) CombinedFlagsAndArgs() []*Clause
- func (p *ParseContext) EOL() bool
- func (p *ParseContext) Flags() []*Clause
- func (p *ParseContext) HasTrailingArgs() bool
- func (p *ParseContext) LastCmd(element *ParseElement) bool
- func (p *ParseContext) Next() *Token
- func (p *ParseContext) Peek() *Token
- func (p *ParseContext) Push(token *Token) *Token
- func (p *ParseContext) String() string
- type ParseElement
- type ParseElements
- type Resolver
- func DontResolve(resolver Resolver, keys ...string) Resolver
- func JSONResolver(r io.Reader) (Resolver, error)
- func MapResolver(values map[string][]string) Resolver
- func PrefixedEnvarResolver(prefix, separator string) Resolver
- func RenamingResolver(resolver Resolver, rename func(string) string) Resolver
- type ResolverFunc
- type Token
- type TokenType
- type UsageContext
- type V
- type Value
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var BashCompletionTemplate = `` /* 327-byte string literal not displayed */
var ( // CommandLine is the default Kingpin parser. CommandLine = New(filepath.Base(os.Args[0]), "") )
var CompactUsageTemplate = `` /* 1320-byte string literal not displayed */
CompactUsageTemplate is a template with compactly formatted commands for large command structures.
var DefaultUsageTemplate = `` /* 996-byte string literal not displayed */
DefaultUsageTemplate is the default usage template.
var ManPageTemplate = `` /* 890-byte string literal not displayed */
var T = initI18N()
T is a translation function.
var (
TokenEOLMarker = Token{-1, TokenEOL, ""}
)
var ZshCompletionTemplate = `` /* 470-byte string literal not displayed */
Functions ¶
func Errorf ¶
func Errorf(format string, args ...interface{})
Errorf prints an error message to stderr.
func ExpandArgsFromFile ¶
Expand arguments from a file. Lines starting with # will be treated as comments.
func FatalIfError ¶
FatalIfError prints an error and exits if err is not nil. The error is printed with the given prefix.
func FatalUsage ¶
func FatalUsage(format string, args ...interface{})
FatalUsage prints an error message followed by usage information, then exits with a non-zero status.
func FatalUsageContext ¶
func FatalUsageContext(context *ParseContext, format string, args ...interface{})
FatalUsageContext writes a printf formatted error message to stderr, then usage information for the given ParseContext, before exiting.
func Fatalf ¶
func Fatalf(format string, args ...interface{})
Fatalf prints an error message to stderr and exits.
func JSONConfigClause ¶
func JSONConfigClause(app *Application, clause *Clause) *string
JSONConfigClause installs a JSONResolver into app that will be loaded by invocation of clause (typically a flag).
eg.
JSONConfigClause(app, app.Flag("config", "Load configuration.").Required())
func Parse ¶
func Parse() string
Parse and return the selected command. Will call the termination handler if an error is encountered.
func SetLanguage ¶
SetLanguage sets the language for Kingpin.
Types ¶
type AccumulatorOption ¶
type AccumulatorOption func(a *accumulatorOptions)
AccumulatorOption are used to modify the behaviour of values that accumulate into slices, maps, etc.
eg. Separator(',')
func Separator ¶
func Separator(separator string) AccumulatorOption
Separator configures an accumulating value to split on this value.
type Action ¶
type Action func(element *ParseElement, context *ParseContext) error
Action callback triggered during parsing.
"element" is the flag, argument or command associated with the callback. It contains the Clause and string value, if any.
"context" contains the full parse context, including all other elements that have been parsed.
type Application ¶
An Application contains the definitions of flags, arguments and commands for an application.
func UsageTemplate ¶
func UsageTemplate(template string) *Application
UsageTemplate associates a template with a flag. The flag must be a Bool() and must already be defined.
func Version ¶
func Version(version string) *Application
Version adds a flag for displaying the application version number.
func (*Application) Action ¶
func (a *Application) Action(action Action) *Application
Action is an application-wide callback. It is used in two situations: first, with a nil "element" parameter when parsing is complete, and second whenever a command, argument or flag is encountered.
func (*Application) Author ¶
func (a *Application) Author(author string) *Application
Author sets the author name for usage templates.
func (*Application) CmdCompletion ¶
func (c *Application) CmdCompletion(context *ParseContext) []string
CmdCompletion returns completion options for arguments, if that's where parsing left off, or commands if there aren't any unsatisfied args.
func (*Application) Command ¶
func (a *Application) Command(name, help string) *CmdClause
Command adds a new top-level command.
func (*Application) DefaultEnvars ¶
func (a *Application) DefaultEnvars() *Application
DefaultEnvars configures all flags (that do not already have an associated envar) to use a default environment variable in the form "<app>_<flag>".
For example, if the application is named "foo" and a flag is named "bar- waz" the environment variable: "FOO_BAR_WAZ".
func (*Application) EnvarSeparator ¶
func (a *Application) EnvarSeparator(sep string) *Application
EnvarSeparator sets the string that is used for separating values in environment variables.
This defaults to the current OS's path list separator (typically : or ;).
func (*Application) Errorf ¶
func (a *Application) Errorf(format string, args ...interface{})
Errorf prints an error message to w in the format "<appname>: error: <message>".
func (*Application) FatalIfError ¶
func (a *Application) FatalIfError(err error, format string, args ...interface{})
FatalIfError prints an error and exits if err is not nil. The error is printed with the given formatted string, if any.
func (*Application) FatalUsage ¶
func (a *Application) FatalUsage(format string, args ...interface{})
FatalUsage prints an error message followed by usage information, then exits with a non-zero status.
func (*Application) FatalUsageContext ¶
func (a *Application) FatalUsageContext(context *ParseContext, format string, args ...interface{})
FatalUsageContext writes a printf formatted error message to w, then usage information for the given ParseContext, before exiting.
func (*Application) Fatalf ¶
func (a *Application) Fatalf(format string, args ...interface{})
Fatalf writes a formatted error to w then terminates with exit status 1.
func (*Application) FlagCompletion ¶
func (*Application) Interspersed ¶
func (a *Application) Interspersed(interspersed bool) *Application
Interspersed control if flags can be interspersed with positional arguments
true (the default) means that they can, false means that all the flags must appear before the first positional arguments.
func (*Application) Model ¶
func (a *Application) Model() *ApplicationModel
func (*Application) Parse ¶
func (a *Application) Parse(args []string) (command string, err error)
Parse parses command-line arguments. It returns the selected command and an error. The selected command will be a space separated subcommand, if subcommands have been configured.
This will populate all flag and argument values, call all callbacks, and so on.
func (*Application) ParseContext ¶
func (a *Application) ParseContext(args []string) (*ParseContext, error)
ParseContext parses the given command line and returns the fully populated ParseContext.
func (*Application) PreAction ¶
func (a *Application) PreAction(action Action) *Application
PreAction adds a callback action to be executed after flag values are parsed but before any other processing, such as help, completion, etc.
It is called in two situations: first, with a nil "element" parameter, and second, whenever a command, argument or flag is encountered.
func (*Application) Resolver ¶
func (a *Application) Resolver(resolvers ...Resolver) *Application
Resolver adds an ordered set of flag/argument resolvers.
Resolvers provide default flag/argument values, from environment variables, configuration files, etc. Multiple resolvers may be added, and they are processed in order.
The last Resolver to return a value always wins. Values returned from resolvers are not cumulative.
func (*Application) Struct ¶
func (a *Application) Struct(v interface{}) error
Struct allows applications to define flags with struct tags.
Supported struct tags are: help, placeholder, default, short, long, required, hidden, env, enum, and arg.
The name of the flag will default to the CamelCase name transformed to camel-case. This can be overridden with the "long" tag.
All basic Go types are supported including floats, ints, strings, time.Duration, and slices of same.
For compatibility, also supports the tags used by https://github.com/jessevdk/go-flags
func (*Application) Terminate ¶
func (a *Application) Terminate(terminate func(int)) *Application
Terminate specifies the termination handler. Defaults to os.Exit(status). If nil is passed, a no-op function will be used.
func (*Application) Usage ¶
func (a *Application) Usage(args []string)
Usage writes application usage to Writer. It parses args to determine appropriate help context, such as which command to show help for.
func (*Application) UsageContext ¶
func (a *Application) UsageContext(context *UsageContext) *Application
UsageContext specifies the UsageContext to use when displaying usage information via --help.
func (*Application) UsageForContext ¶
func (a *Application) UsageForContext(context *ParseContext) error
UsageForContext displays usage information from a ParseContext (obtained from Application.ParseContext() or Action(f) callbacks).
func (*Application) UsageForContextWithTemplate ¶
func (a *Application) UsageForContextWithTemplate(usageContext *UsageContext, parseContext *ParseContext) error
UsageForContextWithTemplate is for fine-grained control over usage messages. You generally don't need to use this.
func (*Application) UsageTemplate ¶
func (a *Application) UsageTemplate(template string) *Application
UsageTemplate specifies the text template to use when displaying usage information via --help. The default is DefaultUsageTemplate.
func (*Application) Version ¶
func (a *Application) Version(version string) *Application
Version adds a --version flag for displaying the application version.
func (*Application) Writers ¶
func (a *Application) Writers(out, err io.Writer) *Application
Writers specifies the writers to use for usage and errors. Defaults to os.Stderr.
type ApplicationModel ¶
type ApplicationModel struct { Name string Help string Version string Author string *ArgGroupModel *CmdGroupModel *FlagGroupModel }
func (*ApplicationModel) AppSummary ¶
func (a *ApplicationModel) AppSummary() string
func (*ApplicationModel) FindModelForCommand ¶
func (a *ApplicationModel) FindModelForCommand(cmd *CmdClause) *CmdModel
type ArgGroupModel ¶
type ArgGroupModel struct {
Args []*ClauseModel
}
func (*ArgGroupModel) ArgSummary ¶
func (a *ArgGroupModel) ArgSummary() string
type BoolFlag ¶
type BoolFlag interface { // Specify if the flag is negatable (ie. supports both --no-<name> and --name). BoolFlagIsNegatable() bool }
BoolFlag is an optional interface to specify that a flag is a boolean flag.
type Clause ¶
type Clause struct {
// contains filtered or unexported fields
}
A Clause represents a flag or an argument passed by the user.
func (*Clause) Action ¶
Action adds a callback action to be executed after the command line is parsed and any non-terminating builtin actions have completed (eg. help, completion, etc.).
func (*Clause) BoolList ¶
func (p *Clause) BoolList(options ...AccumulatorOption) (target *[]bool)
BoolList accumulates bool values into a slice.
func (*Clause) BoolListVar ¶
func (p *Clause) BoolListVar(target *[]bool, options ...AccumulatorOption)
func (*Clause) Bytes ¶
func (c *Clause) Bytes() (target *units.Base2Bytes)
Bytes parses numeric byte units. eg. 1.5KB
func (*Clause) BytesVar ¶
func (c *Clause) BytesVar(target *units.Base2Bytes)
BytesVar parses numeric byte units. eg. 1.5KB
func (*Clause) CounterVar ¶
func (*Clause) Default ¶
Default values for this flag. They *must* be parseable by the value of the flag.
func (*Clause) DurationList ¶
func (p *Clause) DurationList(options ...AccumulatorOption) (target *[]time.Duration)
DurationList accumulates time.Duration values into a slice.
func (*Clause) DurationListVar ¶
func (p *Clause) DurationListVar(target *[]time.Duration, options ...AccumulatorOption)
func (*Clause) DurationVar ¶
func (*Clause) Envar ¶
Envar overrides the default value(s) for a flag from an environment variable, if it is set. Several default values can be provided by using new lines to separate them.
func (*Clause) ExistingDir ¶
ExistingDir sets the parser to one that requires and returns an existing directory.
func (*Clause) ExistingDirVar ¶
ExistingDir sets the parser to one that requires and returns an existing directory.
func (*Clause) ExistingDirs ¶
func (p *Clause) ExistingDirs(options ...AccumulatorOption) (target *[]string)
ExistingDirs accumulates string values into a slice.
func (*Clause) ExistingDirsVar ¶
func (p *Clause) ExistingDirsVar(target *[]string, options ...AccumulatorOption)
func (*Clause) ExistingFile ¶
ExistingFile sets the parser to one that requires and returns an existing file.
func (*Clause) ExistingFileOrDir ¶
ExistingFileOrDir sets the parser to one that requires and returns an existing file OR directory.
func (*Clause) ExistingFileOrDirVar ¶
ExistingDir sets the parser to one that requires and returns an existing directory.
func (*Clause) ExistingFileVar ¶
ExistingFile sets the parser to one that requires and returns an existing file.
func (*Clause) ExistingFiles ¶
func (p *Clause) ExistingFiles(options ...AccumulatorOption) (target *[]string)
ExistingFiles accumulates string values into a slice.
func (*Clause) ExistingFilesOrDirs ¶
func (p *Clause) ExistingFilesOrDirs(options ...AccumulatorOption) (target *[]string)
ExistingFilesOrDirs accumulates string values into a slice.
func (*Clause) ExistingFilesOrDirsVar ¶
func (p *Clause) ExistingFilesOrDirsVar(target *[]string, options ...AccumulatorOption)
func (*Clause) ExistingFilesVar ¶
func (p *Clause) ExistingFilesVar(target *[]string, options ...AccumulatorOption)
func (*Clause) Float32List ¶
func (p *Clause) Float32List(options ...AccumulatorOption) (target *[]float32)
Float32List accumulates float32 values into a slice.
func (*Clause) Float32ListVar ¶
func (p *Clause) Float32ListVar(target *[]float32, options ...AccumulatorOption)
func (*Clause) Float32Var ¶
func (*Clause) Float64List ¶
func (p *Clause) Float64List(options ...AccumulatorOption) (target *[]float64)
Float64List accumulates float64 values into a slice.
func (*Clause) Float64ListVar ¶
func (p *Clause) Float64ListVar(target *[]float64, options ...AccumulatorOption)
func (*Clause) Float64Var ¶
func (*Clause) HexBytesList ¶
func (p *Clause) HexBytesList(options ...AccumulatorOption) (target *[][]byte)
HexBytesList accumulates []byte values into a slice.
func (*Clause) HexBytesListVar ¶
func (p *Clause) HexBytesListVar(target *[][]byte, options ...AccumulatorOption)
func (*Clause) HexBytesVar ¶
func (*Clause) HintAction ¶
func (c *Clause) HintAction(action HintAction) *Clause
HintAction registers a HintAction (function) for the flag to provide completions
func (*Clause) HintOptions ¶
HintOptions registers any number of options for the flag to provide completions
func (*Clause) IPList ¶
func (p *Clause) IPList(options ...AccumulatorOption) (target *[]net.IP)
IPList accumulates net.IP values into a slice.
func (*Clause) IPListVar ¶
func (p *Clause) IPListVar(target *[]net.IP, options ...AccumulatorOption)
func (*Clause) Int16List ¶
func (p *Clause) Int16List(options ...AccumulatorOption) (target *[]int16)
Int16List accumulates int16 values into a slice.
func (*Clause) Int16ListVar ¶
func (p *Clause) Int16ListVar(target *[]int16, options ...AccumulatorOption)
func (*Clause) Int32List ¶
func (p *Clause) Int32List(options ...AccumulatorOption) (target *[]int32)
Int32List accumulates int32 values into a slice.
func (*Clause) Int32ListVar ¶
func (p *Clause) Int32ListVar(target *[]int32, options ...AccumulatorOption)
func (*Clause) Int64List ¶
func (p *Clause) Int64List(options ...AccumulatorOption) (target *[]int64)
Int64List accumulates int64 values into a slice.
func (*Clause) Int64ListVar ¶
func (p *Clause) Int64ListVar(target *[]int64, options ...AccumulatorOption)
func (*Clause) Int8List ¶
func (p *Clause) Int8List(options ...AccumulatorOption) (target *[]int8)
Int8List accumulates int8 values into a slice.
func (*Clause) Int8ListVar ¶
func (p *Clause) Int8ListVar(target *[]int8, options ...AccumulatorOption)
func (*Clause) Ints ¶
func (p *Clause) Ints(options ...AccumulatorOption) (target *[]int)
Ints accumulates int values into a slice.
func (*Clause) IntsVar ¶
func (p *Clause) IntsVar(target *[]int, options ...AccumulatorOption)
func (*Clause) Model ¶
func (f *Clause) Model() *ClauseModel
func (*Clause) NegatableBool ¶
NegatableBool parses the next command-line value as bool.
func (*Clause) NegatableBoolList ¶
func (p *Clause) NegatableBoolList(options ...AccumulatorOption) (target *[]bool)
NegatableBoolList accumulates bool values into a slice.
func (*Clause) NegatableBoolListVar ¶
func (p *Clause) NegatableBoolListVar(target *[]bool, options ...AccumulatorOption)
func (*Clause) NegatableBoolVar ¶
func (*Clause) NoEnvar ¶
NoEnvar forces environment variable defaults to be disabled for this flag. Most useful in conjunction with PrefixedEnvarResolver.
func (*Clause) PlaceHolder ¶
PlaceHolder sets the place-holder string used for flag values in the help. The default behaviour is to use the value provided by Default() if provided, then fall back on the capitalized flag name.
func (*Clause) PreAction ¶
PreAction adds a callback action to be executed after flag values are parsed but before any other processing, such as help, completion, etc.
func (*Clause) RegexpList ¶
func (p *Clause) RegexpList(options ...AccumulatorOption) (target *[]*regexp.Regexp)
RegexpList accumulates *regexp.Regexp values into a slice.
func (*Clause) RegexpListVar ¶
func (p *Clause) RegexpListVar(target *[]*regexp.Regexp, options ...AccumulatorOption)
func (*Clause) Required ¶
Required makes the flag required. You can not provide a Default() value to a Required() flag.
func (*Clause) StringMap ¶
func (c *Clause) StringMap(options ...AccumulatorOption) (target *map[string]string)
StringMap provides key=value parsing into a map.
func (*Clause) StringMapVar ¶
func (c *Clause) StringMapVar(target *map[string]string, options ...AccumulatorOption)
StringMap provides key=value parsing into a map.
func (*Clause) Strings ¶
func (p *Clause) Strings(options ...AccumulatorOption) (target *[]string)
Strings accumulates string values into a slice.
func (*Clause) StringsVar ¶
func (p *Clause) StringsVar(target *[]string, options ...AccumulatorOption)
func (*Clause) Time ¶
Time parses a time.Time.
Format is the layout as specified at https://golang.org/pkg/time/#Parse
func (*Clause) TimeList ¶
func (p *Clause) TimeList(format string, options ...AccumulatorOption) (target *[]time.Time)
TimeList accumulates time.Time values into a slice.
func (*Clause) TimeListVar ¶
func (p *Clause) TimeListVar(format string, target *[]time.Time, options ...AccumulatorOption)
func (*Clause) URLList ¶
func (p *Clause) URLList(options ...AccumulatorOption) (target *[]*url.URL)
URLList accumulates *url.URL values into a slice.
func (*Clause) URLListVar ¶
func (p *Clause) URLListVar(target *[]*url.URL, options ...AccumulatorOption)
func (*Clause) Uint16List ¶
func (p *Clause) Uint16List(options ...AccumulatorOption) (target *[]uint16)
Uint16List accumulates uint16 values into a slice.
func (*Clause) Uint16ListVar ¶
func (p *Clause) Uint16ListVar(target *[]uint16, options ...AccumulatorOption)
func (*Clause) Uint32List ¶
func (p *Clause) Uint32List(options ...AccumulatorOption) (target *[]uint32)
Uint32List accumulates uint32 values into a slice.
func (*Clause) Uint32ListVar ¶
func (p *Clause) Uint32ListVar(target *[]uint32, options ...AccumulatorOption)
func (*Clause) Uint64List ¶
func (p *Clause) Uint64List(options ...AccumulatorOption) (target *[]uint64)
Uint64List accumulates uint64 values into a slice.
func (*Clause) Uint64ListVar ¶
func (p *Clause) Uint64ListVar(target *[]uint64, options ...AccumulatorOption)
func (*Clause) Uint8List ¶
func (p *Clause) Uint8List(options ...AccumulatorOption) (target *[]uint8)
Uint8List accumulates uint8 values into a slice.
func (*Clause) Uint8ListVar ¶
func (p *Clause) Uint8ListVar(target *[]uint8, options ...AccumulatorOption)
func (*Clause) Uints ¶
func (p *Clause) Uints(options ...AccumulatorOption) (target *[]uint)
Uints accumulates uint values into a slice.
func (*Clause) UintsVar ¶
func (p *Clause) UintsVar(target *[]uint, options ...AccumulatorOption)
func (*Clause) UsageAction ¶
func (c *Clause) UsageAction(context *UsageContext) *Clause
UsageAction adds a PreAction() that will display the given UsageContext.
func (*Clause) UsageActionTemplate ¶
type ClauseModel ¶
type ClauseModel struct { Name string Help string Short rune Default []string PlaceHolder string Required bool Hidden bool Value Value Cumulative bool Envar string }
func (*ClauseModel) FormatPlaceHolder ¶
func (c *ClauseModel) FormatPlaceHolder() string
func (*ClauseModel) IsBoolFlag ¶
func (c *ClauseModel) IsBoolFlag() bool
func (*ClauseModel) IsNegatable ¶
func (c *ClauseModel) IsNegatable() bool
func (*ClauseModel) String ¶
func (c *ClauseModel) String() string
type CmdClause ¶
type CmdClause struct {
// contains filtered or unexported fields
}
A CmdClause is a single top-level command. It encapsulates a set of flags and either subcommands or positional arguments.
func (*CmdClause) CmdCompletion ¶
func (c *CmdClause) CmdCompletion(context *ParseContext) []string
CmdCompletion returns completion options for arguments, if that's where parsing left off, or commands if there aren't any unsatisfied args.
func (*CmdClause) FlagCompletion ¶
func (*CmdClause) FullCommand ¶
FullCommand returns the fully qualified "path" to this command, including interspersed argument placeholders. Does not include trailing argument placeholders.
eg. "signup <username> <email>"
func (*CmdClause) OptionalSubcommands ¶
OptionalSubcommands makes subcommands optional
func (*CmdClause) Struct ¶
Struct allows applications to define flags with struct tags.
Supported struct tags are: help, placeholder, default, short, long, required, hidden, env, enum, and arg.
The name of the flag will default to the CamelCase name transformed to camel-case. This can be overridden with the "long" tag.
All basic Go types are supported including floats, ints, strings, time.Duration, and slices of same.
For compatibility, also supports the tags used by https://github.com/jessevdk/go-flags
func (*CmdClause) Validate ¶
func (c *CmdClause) Validate(validator CmdClauseValidator) *CmdClause
Validate sets a validation function to run when parsing.
type CmdClauseValidator ¶
type CmdGroupModel ¶
type CmdGroupModel struct {
Commands []*CmdModel
}
func (*CmdGroupModel) FlattenedCommands ¶
func (c *CmdGroupModel) FlattenedCommands() (out []*CmdModel)
type CmdModel ¶
type CmdModel struct { Name string Aliases []string Help string Depth int Hidden bool Default bool OptionalSubcommands bool Parent *CmdModel *FlagGroupModel *ArgGroupModel *CmdGroupModel }
func (*CmdModel) CmdSummary ¶
func (*CmdModel) FullCommand ¶
FullCommand is the command path to this node, excluding positional arguments and flags.
type FlagGroupModel ¶
type FlagGroupModel struct {
Flags []*ClauseModel
}
func (*FlagGroupModel) FlagByName ¶
func (f *FlagGroupModel) FlagByName(name string) *ClauseModel
func (*FlagGroupModel) FlagSummary ¶
func (f *FlagGroupModel) FlagSummary() string
type Getter ¶
type Getter interface { Value Get() interface{} }
Getter is an interface that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.
type HintAction ¶
type HintAction func() []string
HintAction is a function type who is expected to return a slice of possible command line arguments.
type OneOfClause ¶
type ParseContext ¶
type ParseContext struct { Application *Application // May be nil in tests. SelectedCommand *CmdClause // Flags, arguments and commands encountered and collected during parse. Elements ParseElements // contains filtered or unexported fields }
ParseContext holds the current context of the parser. When passed to Action() callbacks Elements will be fully populated with *FlagClause, *ArgClause and *CmdClause values and their corresponding arguments (if any).
func (*ParseContext) Args ¶
func (p *ParseContext) Args() []*Clause
func (*ParseContext) CombinedFlagsAndArgs ¶
func (p *ParseContext) CombinedFlagsAndArgs() []*Clause
func (*ParseContext) EOL ¶
func (p *ParseContext) EOL() bool
func (*ParseContext) Flags ¶
func (p *ParseContext) Flags() []*Clause
func (*ParseContext) HasTrailingArgs ¶
func (p *ParseContext) HasTrailingArgs() bool
HasTrailingArgs returns true if there are unparsed command-line arguments. This can occur if the parser can not match remaining arguments.
func (*ParseContext) LastCmd ¶
func (p *ParseContext) LastCmd(element *ParseElement) bool
LastCmd returns true if the element is the last (sub)command being evaluated.
func (*ParseContext) Peek ¶
func (p *ParseContext) Peek() *Token
func (*ParseContext) Push ¶
func (p *ParseContext) Push(token *Token) *Token
func (*ParseContext) String ¶
func (p *ParseContext) String() string
type ParseElement ¶
type ParseElement struct { // Clause associated with this element. Exactly one of these will be present. OneOf OneOfClause // Value is corresponding value for an argument or flag. For commands this value will be nil. Value *string }
A ParseElement represents the parsers view of each element in the command-line argument slice.
type ParseElements ¶
type ParseElements []*ParseElement
ParseElements represents each element in the command-line argument slice.
func (ParseElements) ArgMap ¶
func (p ParseElements) ArgMap() map[string]*ParseElement
ArgMap collects all parsed positional arguments into a map keyed by long name.
func (ParseElements) FlagMap ¶
func (p ParseElements) FlagMap() map[string]*ParseElement
FlagMap collects all parsed flags into a map keyed by long name.
type Resolver ¶
type Resolver interface { // Resolve clause in the given parse context. // // A nil slice should be returned if the clause can not be resolved. Resolve(clause *ClauseModel, context *ParseContext) ([]string, error) }
A Resolver retrieves flag/arg values from an external source, such as a configuration file or environment variables.
func DontResolve ¶
DontResolve returns a Resolver that will never return values for the given keys, even if provided.
func JSONResolver ¶
JSONResolver returns a Resolver that retrieves values from a JSON source.
func MapResolver ¶
MapResolver resolves values from a static map.
func PrefixedEnvarResolver ¶
PrefixedEnvarResolver resolves any flag/argument via environment variables.
"prefix" is the common-prefix for the environment variables. "separator", is the character used to separate multiple values within a single envar (eg. ";")
With a prefix of APP_, flags in the form --some-flag will be transformed to APP_SOME_FLAG.
type ResolverFunc ¶
type ResolverFunc func(clause *ClauseModel, context *ParseContext) ([]string, error)
ResolverFunc is a function that is also a Resolver.
func (ResolverFunc) Resolve ¶
func (r ResolverFunc) Resolve(clause *ClauseModel, context *ParseContext) ([]string, error)
type UsageContext ¶
type UsageContext struct { // The text/template body to use. Template string // Indentation multiplier (defaults to 2 of omitted). Indent int // Width of wrap. Defaults wraps to the terminal. Width int // Funcs available in the template. Funcs template.FuncMap // Vars available in the template. Vars map[string]interface{} }
UsageContext contains all of the context used to render a usage message.
type V ¶
type V map[string]interface{}
V is a convenience alias for translation function variables. eg. T("Something {{.Arg0}}", V{"Arg0": "moo"})
type Value ¶
Value is the interface to the dynamic value stored in a flag. (The default value is represented as a string.)
If a Value has an IsBoolFlag() bool method returning true, the command-line parser makes --name equivalent to -name=true rather than using the next command-line argument, and adds a --no-name counterpart for negating the flag.
Example ¶
This example ilustrates how to define custom parsers. HTTPHeader cumulatively parses each encountered --header flag into a http.Header struct.
package main import ( "fmt" "net/http" "strings" ) type HTTPHeaderValue http.Header func (h *HTTPHeaderValue) Set(value string) error { parts := strings.SplitN(value, ":", 2) if len(parts) != 2 { return fmt.Errorf("expected HEADER:VALUE got '%s'", value) } (*http.Header)(h).Add(parts[0], parts[1]) return nil } func (h *HTTPHeaderValue) Get() interface{} { return (http.Header)(*h) } func (h *HTTPHeaderValue) String() string { return "" } func HTTPHeader(s *Clause) (target *http.Header) { target = new(http.Header) s.SetValue((*HTTPHeaderValue)(target)) return } // This example ilustrates how to define custom parsers. HTTPHeader // cumulatively parses each encountered --header flag into a http.Header struct. func main() { var ( curl = New("curl", "transfer a URL") headers = HTTPHeader(curl.Flag("headers", "Add HTTP headers to the request.").Short('H').PlaceHolder("HEADER:VALUE")) ) curl.Parse([]string{"-H Content-Type:application/octet-stream"}) for key, value := range *headers { fmt.Printf("%s = %s\n", key, value) } }
Output: