README ¶
Kingpin - A Go (golang) command line and flag parser
(check out v2-unstable for bleeding edge features)
Features
- POSIX-style short flag combining.
- Parsed, type-safe flags.
- Parsed, type-safe positional arguments.
- Support for required flags and required positional arguments
- Callbacks per command, flag and argument.
- Help output that isn't as ugly as sin.
Versions
Kingpin uses gopkg.in for versioning.
Usage:
import "gopkg.in/alecthomas/kingpin.v1"
Changes
-
2015-01-23 -- Stable v1.3.4 release.
- Support "--" for separating flags from positional arguments.
- Support loading flags from files (ParseWithFileExpansion()). Use @FILE as an argument.
- Add post-app and post-cmd validation hooks. This allows arbitrary validation to be added.
- A bunch of improvements to help usage and formatting.
- Support arbitrarily nested sub-commands.
-
2014-07-08 -- Stable v1.2.0 release.
- Pass any value through to
Strings()
when final argument. Allows for values that look like flags to be processed. - Allow
--help
to be used with commands. - Support
Hidden()
flags. - Parser for units.Base2Bytes
type. Allows for flags like
--ram=512MB
or--ram=1GB
. - Add an
Enum()
value, allowing only one of a set of values to be selected. eg.Flag(...).Enum("debug", "info", "warning")
.
- Pass any value through to
-
2014-06-27 -- Stable v1.1.0 release.
- Bug fixes.
- Always return an error (rather than panicing) when misconfigured.
OpenFile(flag, perm)
value type added, for finer control over opening files.- Significantly improved usage formatting.
-
2014-06-19 -- Stable v1.0.0 release.
- Support cumulative positional arguments.
- Return error rather than panic when there are fatal errors not caught by the type system. eg. when a default value is invalid.
- Use gokpg.in.
-
2014-06-10 -- Place-holder streamlining.
- Renamed
MetaVar
toPlaceHolder
. - Removed
MetaVarFromDefault
. Kingpin now uses heuristics to determine what to display.
- Renamed
Simple Example
Kingpin can be used for simple flag+arg applications like so:
$ ping --help
usage: ping [<flags>] <ip> [<count>]
Flags:
--debug Enable debug mode.
--help Show help.
-t, --timeout=5s Timeout waiting for ping.
Args:
<ip> IP address to ping.
[<count>] Number of packets to send
$ ping 1.2.3.4 5
Would ping: 1.2.3.4 with timeout 5s and count 0
From the following source:
package main
import (
"fmt"
"gopkg.in/alecthomas/kingpin.v1"
)
var (
debug = kingpin.Flag("debug", "Enable debug mode.").Bool()
timeout = kingpin.Flag("timeout", "Timeout waiting for ping.").Default("5s").OverrideDefaultFromEnvar("PING_TIMEOUT").Short('t').Duration()
ip = kingpin.Arg("ip", "IP address to ping.").Required().IP()
count = kingpin.Arg("count", "Number of packets to send").Int()
)
func main() {
kingpin.Version("0.0.1")
kingpin.Parse()
fmt.Printf("Would ping: %s with timeout %s and count %d", *ip, *timeout, *count)
}
Complex Example
Kingpin can also produce complex command-line applications with global flags, subcommands, and per-subcommand flags, like this:
$ chat --help
usage: chat [<flags>] <command> [<flags>] [<args> ...]
A command-line chat application.
Flags:
--help Show help.
--debug Enable debug mode.
--server=127.0.0.1 Server address.
Commands:
help [<command>]
Show help for a command.
register <nick> <name>
Register a new user.
post [<flags>] <channel> [<text>]
Post a message to a channel.
$ 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 this code:
package main
import (
"os"
"strings"
"gopkg.in/alecthomas/kingpin.v1"
)
var (
app = kingpin.New("chat", "A command-line chat application.")
debug = app.Flag("debug", "Enable debug mode.").Bool()
serverIP = app.Flag("server", "Server address.").Default("127.0.0.1").IP()
register = app.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 = app.Command("post", "Post a message to a channel.")
postImage = post.Flag("image", "Image to post.").File()
postChannel = post.Arg("channel", "Channel to post to.").Required().String()
postText = post.Arg("text", "Text to post.").Strings()
)
func main() {
switch kingpin.MustParse(app.Parse(os.Args[1:])) {
// Register user
case register.FullCommand():
println(*registerNick)
// Post message
case post.FullCommand():
if *postImage != nil {
}
text := strings.Join(*postText, " ")
println("Post:", text)
}
}
Reference Documentation
Help
Second to parsing, providing the user with useful help is probably the most important thing a command-line parser does.
Since 1.3.x, Kingpin uses a bunch of heuristics to display help. For example,
--help
should generally "just work" without much thought from users.
Sub-commands
Kingpin supports nested sub-commands, with separate flag and positional arguments per sub-command. Note that positional arguments may only occur after sub-commands.
For example:
var (
deleteCommand = kingpin.Command("delete", "Delete an object.")
deleteUserCommand = deleteCommand.Command("user", "Delete a user.")
deleteUserUIDFlag = deleteUserCommand.Flag("uid", "Delete user by UID rather than username.")
deleteUserUsername = deleteUserCommand.Arg("username", "Username to delete.")
deletePostCommand = deleteCommand.Command("post", "Delete a post.")
)
func main() {
switch kingpin.Parse() {
case "delete user":
case "delete post":
}
}
Custom Parsers
Kingpin supports both flag and positional argument parsers for converting to
Go types. For example, some included parsers are Int()
, Float()
,
Duration()
and ExistingFile()
.
Parsers conform to Go's flag.Value
interface, so any existing implementations will work.
For example, a parser for accumulating HTTP header values might look like this:
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) String() string {
return ""
}
As a convenience, I would recommend something like this:
func HTTPHeader(s Settings) (target *http.Header) {
target = new(http.Header)
s.SetValue((*HTTPHeaderValue)(target))
return
}
You would use it like so:
headers = HTTPHeader(kingpin.Flag("header", "Add a HTTP header to the request.").Short('H'))
Default Values
The default value is the zero value for a type. This can be overridden with
the Default(value)
function on flags and arguments. This function accepts a
string, which is parsed by the value itself, so it must be compliant with
the format expected.
Place-holders in Help
The place-holder value for a flag is the value used in the help to describe the value of a non-boolean flag.
The value provided to PlaceHolder() is used if provided, then the value provided by Default() if provided, then finally the capitalised flag name is used.
Here are some examples of flags with various permutations:
--name=NAME // Flag(...).String()
--name="Harry" // Flag(...).Default("Harry").String()
--name=FULL-NAME // flag(...).PlaceHolder("FULL-NAME").Default("Harry").String()
Consuming all remaining arguments
A common command-line idiom is to use all remaining arguments for some purpose. eg. The following command accepts an arbitrary number of IP addresses as positional arguments:
./cmd ping 10.1.1.1 192.168.1.1
Kingpin supports this by having Value
provide a IsCumulative() bool
function. If this function exists and returns true, the value parser will be
called repeatedly for every remaining argument.
Examples of this are the Strings()
and StringMap()
values.
To implement the above example we might do something like this:
type ipList []net.IP
func (i *ipList) Set(value string) error {
if ip := net.ParseIP(value); ip == nil {
return fmt.Errorf("'%s' is not an IP address", value)
} else {
*i = append(*i, ip)
return nil
}
}
func (i *ipList) String() string {
return ""
}
func (i *ipList) IsCumulative() bool {
return true
}
func IPList(s Settings) (target *[]net.IP) {
target = new([]net.IP)
s.SetValue((*ipList)(target))
return
}
And use it like so:
ips := IPList(kingpin.Arg("ips", "IP addresses to ping."))
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").File() 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 != "" { } } }
Index ¶
- Variables
- func ExpandArgsFromFiles(args []string) ([]string, error)
- func FatalIfError(err error, prefix string)
- func Fatalf(format string, args ...interface{})
- func MustParse(command string, err error) string
- func Parse() string
- func ParseWithFileExpansion() string
- func Usage()
- func UsageErrorf(format string, args ...interface{})
- func Version(version string)
- type Application
- func (a Application) Arg(name, help string) *ArgClause
- func (a *Application) Command(name, help string) *CmdClause
- func (a *Application) CommandUsage(w io.Writer, command string)
- func (a *Application) Errorf(w io.Writer, format string, args ...interface{})
- func (a *Application) FatalIfError(w io.Writer, err error, prefix string)
- func (a *Application) Fatalf(w io.Writer, format string, args ...interface{})
- func (f Application) Flag(name, help string) *FlagClause
- func (a *Application) Parse(args []string) (command string, err error)
- func (a *Application) Usage(w io.Writer)
- func (a *Application) UsageErrorf(w io.Writer, format string, args ...interface{})
- func (a *Application) Validate(validator ApplicationValidator) *Application
- func (a *Application) Version(version string) *Application
- type ApplicationValidator
- type ArgClause
- func (p *ArgClause) Bool() (target *bool)
- func (p *ArgClause) BoolVar(target *bool)
- func (p *ArgClause) Bytes() (target *units.Base2Bytes)
- func (p *ArgClause) BytesVar(target *units.Base2Bytes)
- func (a *ArgClause) Default(value string) *ArgClause
- func (a *ArgClause) Dispatch(dispatch Dispatch) *ArgClause
- func (p *ArgClause) Duration() (target *time.Duration)
- func (p *ArgClause) DurationVar(target *time.Duration)
- func (p *ArgClause) Enum(options ...string) (target *string)
- func (p *ArgClause) EnumVar(target **string, options ...string)
- func (p *ArgClause) Enums(options ...string) (target *[]string)
- func (p *ArgClause) EnumsVar(target *[]string, options ...string)
- func (p *ArgClause) ExistingDir() (target *string)
- func (p *ArgClause) ExistingDirVar(target *string)
- func (p *ArgClause) ExistingFile() (target *string)
- func (p *ArgClause) ExistingFileVar(target *string)
- func (p *ArgClause) File() (target **os.File)
- func (p *ArgClause) FileVar(target **os.File)
- func (p *ArgClause) Float() (target *float64)
- func (p *ArgClause) FloatVar(target *float64)
- func (p *ArgClause) IP() (target *net.IP)
- func (p *ArgClause) IPVar(target *net.IP)
- func (p *ArgClause) Int() (target *int)
- func (p *ArgClause) Int64() (target *int64)
- func (p *ArgClause) Int64Var(target *int64)
- func (p *ArgClause) IntVar(target *int)
- func (p *ArgClause) OpenFile(flag int, perm os.FileMode) (target **os.File)
- func (p *ArgClause) OpenFileVar(target **os.File, flag int, perm os.FileMode)
- func (a *ArgClause) Required() *ArgClause
- func (p *ArgClause) SetValue(value Value)
- func (p *ArgClause) String() (target *string)
- func (p *ArgClause) StringMap() (target *map[string]string)
- func (p *ArgClause) StringMapVar(target *map[string]string)
- func (p *ArgClause) StringVar(target *string)
- func (p *ArgClause) Strings() (target *[]string)
- func (p *ArgClause) StringsVar(target *[]string)
- func (p *ArgClause) TCP() (target **net.TCPAddr)
- func (p *ArgClause) TCPList() (target *[]*net.TCPAddr)
- func (p *ArgClause) TCPListVar(target *[]*net.TCPAddr)
- func (p *ArgClause) TCPVar(target **net.TCPAddr)
- func (p *ArgClause) URL() (target **url.URL)
- func (p *ArgClause) URLList() (target *[]*url.URL)
- func (p *ArgClause) URLListVar(target *[]*url.URL)
- func (p *ArgClause) URLVar(target **url.URL)
- func (p *ArgClause) Uint64() (target *uint64)
- func (p *ArgClause) Uint64Var(target *uint64)
- type CmdClause
- func (a CmdClause) Arg(name, help string) *ArgClause
- func (c *CmdClause) Command(name, help string) *CmdClause
- func (c *CmdClause) Dispatch(dispatch Dispatch) *CmdClause
- func (f CmdClause) Flag(name, help string) *FlagClause
- func (c *CmdClause) FullCommand() string
- func (c *CmdClause) Validate(validator CmdClauseValidator) *CmdClause
- type CmdClauseValidator
- type Dispatch
- type FlagClause
- func (f *FlagClause) Bool() (target *bool)
- func (p *FlagClause) BoolVar(target *bool)
- func (p *FlagClause) Bytes() (target *units.Base2Bytes)
- func (p *FlagClause) BytesVar(target *units.Base2Bytes)
- func (f *FlagClause) Default(value string) *FlagClause
- func (f *FlagClause) Dispatch(dispatch Dispatch) *FlagClause
- func (p *FlagClause) Duration() (target *time.Duration)
- func (p *FlagClause) DurationVar(target *time.Duration)
- func (p *FlagClause) Enum(options ...string) (target *string)
- func (p *FlagClause) EnumVar(target **string, options ...string)
- func (p *FlagClause) Enums(options ...string) (target *[]string)
- func (p *FlagClause) EnumsVar(target *[]string, options ...string)
- func (p *FlagClause) ExistingDir() (target *string)
- func (p *FlagClause) ExistingDirVar(target *string)
- func (p *FlagClause) ExistingFile() (target *string)
- func (p *FlagClause) ExistingFileVar(target *string)
- func (p *FlagClause) File() (target **os.File)
- func (p *FlagClause) FileVar(target **os.File)
- func (p *FlagClause) Float() (target *float64)
- func (p *FlagClause) FloatVar(target *float64)
- func (f *FlagClause) Hidden() *FlagClause
- func (p *FlagClause) IP() (target *net.IP)
- func (p *FlagClause) IPVar(target *net.IP)
- func (p *FlagClause) Int() (target *int)
- func (p *FlagClause) Int64() (target *int64)
- func (p *FlagClause) Int64Var(target *int64)
- func (p *FlagClause) IntVar(target *int)
- func (p *FlagClause) OpenFile(flag int, perm os.FileMode) (target **os.File)
- func (p *FlagClause) OpenFileVar(target **os.File, flag int, perm os.FileMode)
- func (f *FlagClause) OverrideDefaultFromEnvar(envar string) *FlagClause
- func (f *FlagClause) PlaceHolder(placeholder string) *FlagClause
- func (f *FlagClause) Required() *FlagClause
- func (p *FlagClause) SetValue(value Value)
- func (f *FlagClause) Short(name byte) *FlagClause
- func (p *FlagClause) String() (target *string)
- func (p *FlagClause) StringMap() (target *map[string]string)
- func (p *FlagClause) StringMapVar(target *map[string]string)
- func (p *FlagClause) StringVar(target *string)
- func (p *FlagClause) Strings() (target *[]string)
- func (p *FlagClause) StringsVar(target *[]string)
- func (p *FlagClause) TCP() (target **net.TCPAddr)
- func (p *FlagClause) TCPList() (target *[]*net.TCPAddr)
- func (p *FlagClause) TCPListVar(target *[]*net.TCPAddr)
- func (p *FlagClause) TCPVar(target **net.TCPAddr)
- func (p *FlagClause) URL() (target **url.URL)
- func (p *FlagClause) URLList() (target *[]*url.URL)
- func (p *FlagClause) URLListVar(target *[]*url.URL)
- func (p *FlagClause) URLVar(target **url.URL)
- func (p *FlagClause) Uint64() (target *uint64)
- func (p *FlagClause) Uint64Var(target *uint64)
- type Getter
- type ParseContext
- type Settings
- type Token
- type TokenType
- type Tokens
- type Value
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // CommandLine is the default Kingpin parser. CommandLine = New(filepath.Base(os.Args[0]), "") )
var (
TokenEOLMarker = Token{TokenEOL, ""}
)
Functions ¶
func ExpandArgsFromFiles ¶
ExpandArgsFromFiles expands arguments in the form @<file> into one-arg-per- line read from that file.
func FatalIfError ¶
FatalIfError prints an error and exits if err is not nil. The error is printed with the given prefix.
func Fatalf ¶
func Fatalf(format string, args ...interface{})
Fatalf prints an error message to stderr and exits.
func Parse ¶
func Parse() string
Parse and return the selected command. Will exit with a non-zero status if an error was encountered.
func ParseWithFileExpansion ¶
func ParseWithFileExpansion() string
ParseWithFileExpansion is the same as Parse() but will expand flags from arguments in the form @FILE.
func UsageErrorf ¶
func UsageErrorf(format string, args ...interface{})
UsageErrorf prints an error message followed by usage information, then exits with a non-zero status.
Types ¶
type Application ¶
An Application contains the definitions of flags, arguments and commands for an application.
func (*Application) Command ¶
func (a *Application) Command(name, help string) *CmdClause
Command adds a new top-level command.
func (*Application) CommandUsage ¶
func (a *Application) CommandUsage(w io.Writer, command string)
func (*Application) Errorf ¶
func (a *Application) Errorf(w io.Writer, format string, args ...interface{})
Errorf prints an error message to w.
func (*Application) FatalIfError ¶
func (a *Application) FatalIfError(w io.Writer, err error, prefix string)
FatalIfError prints an error and exits if err is not nil. The error is printed with the given prefix.
func (*Application) Fatalf ¶
func (a *Application) Fatalf(w io.Writer, format string, args ...interface{})
func (Application) Flag ¶
func (f Application) Flag(name, help string) *FlagClause
Flag defines a new flag with the given long name and help.
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.
func (*Application) Usage ¶
func (a *Application) Usage(w io.Writer)
func (*Application) UsageErrorf ¶
func (a *Application) UsageErrorf(w io.Writer, format string, args ...interface{})
UsageErrorf prints an error message followed by usage information, then exits with a non-zero status.
func (*Application) Validate ¶
func (a *Application) Validate(validator ApplicationValidator) *Application
Validate sets a validation function to run when parsing.
func (*Application) Version ¶
func (a *Application) Version(version string) *Application
Version adds a --version flag for displaying the application version.
type ApplicationValidator ¶
type ApplicationValidator func(*Application) error
type ArgClause ¶
type ArgClause struct {
// contains filtered or unexported fields
}
func (*ArgClause) Bool ¶
func (p *ArgClause) Bool() (target *bool)
Bool sets the parser to a boolean parser. Supports --no-<X> to disable the flag.
func (*ArgClause) BoolVar ¶
func (p *ArgClause) BoolVar(target *bool)
Bool sets the parser to a boolean parser. Supports --no-<X> to disable the flag.
func (*ArgClause) Bytes ¶
func (p *ArgClause) Bytes() (target *units.Base2Bytes)
Bytes parses numeric byte units. eg. 1.5KB
func (*ArgClause) BytesVar ¶
func (p *ArgClause) BytesVar(target *units.Base2Bytes)
BytesVar parses numeric byte units. eg. 1.5KB
func (*ArgClause) Default ¶
Default value for this argument. It *must* be parseable by the value of the argument.
func (*ArgClause) DurationVar ¶
Duration sets the parser to a time.Duration parser.
func (*ArgClause) ExistingDir ¶
func (p *ArgClause) ExistingDir() (target *string)
ExistingDir sets the parser to one that requires and returns an existing directory.
func (*ArgClause) ExistingDirVar ¶
func (p *ArgClause) ExistingDirVar(target *string)
ExistingDir sets the parser to one that requires and returns an existing directory.
func (*ArgClause) ExistingFile ¶
func (p *ArgClause) ExistingFile() (target *string)
ExistingFile sets the parser to one that requires and returns an existing file.
func (*ArgClause) ExistingFileVar ¶
func (p *ArgClause) ExistingFileVar(target *string)
ExistingFile sets the parser to one that requires and returns an existing file.
func (*ArgClause) Float ¶
func (p *ArgClause) Float() (target *float64)
Float sets the parser to a float64 parser.
func (*ArgClause) FloatVar ¶
func (p *ArgClause) FloatVar(target *float64)
Float sets the parser to a float64 parser.
func (*ArgClause) Int ¶
func (p *ArgClause) Int() (target *int)
Int sets the parser to an int parser.
func (*ArgClause) IntVar ¶
func (p *ArgClause) IntVar(target *int)
Int sets the parser to an int parser.
func (*ArgClause) OpenFileVar ¶
OpenFileVar calls os.OpenFile(flag, perm)
func (*ArgClause) Required ¶
Required arguments must be input by the user. They can not have a Default() value provided.
func (*ArgClause) String ¶
func (p *ArgClause) String() (target *string)
String sets the parser to a string parser.
func (*ArgClause) StringMapVar ¶
StringMap provides key=value parsing into a map.
func (*ArgClause) StringVar ¶
func (p *ArgClause) StringVar(target *string)
String sets the parser to a string parser.
func (*ArgClause) Strings ¶
func (p *ArgClause) Strings() (target *[]string)
Strings appends multiple occurrences to a string slice.
func (*ArgClause) StringsVar ¶
func (p *ArgClause) StringsVar(target *[]string)
Strings appends multiple occurrences to a string slice.
func (*ArgClause) TCPListVar ¶
TCPVar (host:port) address list.
func (*ArgClause) URLListVar ¶
URLListVar provides a parsed list of url.URL values.
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) Flag ¶
func (f CmdClause) Flag(name, help string) *FlagClause
Flag defines a new flag with the given long name and help.
func (*CmdClause) FullCommand ¶
func (*CmdClause) Validate ¶
func (c *CmdClause) Validate(validator CmdClauseValidator) *CmdClause
Validate sets a validation function to run when parsing.
type CmdClauseValidator ¶
type Dispatch ¶
type Dispatch func(*ParseContext) error
type FlagClause ¶
type FlagClause struct {
// contains filtered or unexported fields
}
FlagClause is a fluid interface used to build flags.
func (*FlagClause) Bool ¶
func (f *FlagClause) Bool() (target *bool)
Bool makes this flag a boolean flag.
func (*FlagClause) BoolVar ¶
func (p *FlagClause) BoolVar(target *bool)
Bool sets the parser to a boolean parser. Supports --no-<X> to disable the flag.
func (*FlagClause) Bytes ¶
func (p *FlagClause) Bytes() (target *units.Base2Bytes)
Bytes parses numeric byte units. eg. 1.5KB
func (*FlagClause) BytesVar ¶
func (p *FlagClause) BytesVar(target *units.Base2Bytes)
BytesVar parses numeric byte units. eg. 1.5KB
func (*FlagClause) Default ¶
func (f *FlagClause) Default(value string) *FlagClause
Default value for this flag. It *must* be parseable by the value of the flag.
func (*FlagClause) Dispatch ¶
func (f *FlagClause) Dispatch(dispatch Dispatch) *FlagClause
Dispatch to the given function when the flag is parsed.
func (*FlagClause) DurationVar ¶
Duration sets the parser to a time.Duration parser.
func (*FlagClause) ExistingDir ¶
func (p *FlagClause) ExistingDir() (target *string)
ExistingDir sets the parser to one that requires and returns an existing directory.
func (*FlagClause) ExistingDirVar ¶
func (p *FlagClause) ExistingDirVar(target *string)
ExistingDir sets the parser to one that requires and returns an existing directory.
func (*FlagClause) ExistingFile ¶
func (p *FlagClause) ExistingFile() (target *string)
ExistingFile sets the parser to one that requires and returns an existing file.
func (*FlagClause) ExistingFileVar ¶
func (p *FlagClause) ExistingFileVar(target *string)
ExistingFile sets the parser to one that requires and returns an existing file.
func (*FlagClause) Float ¶
func (p *FlagClause) Float() (target *float64)
Float sets the parser to a float64 parser.
func (*FlagClause) FloatVar ¶
func (p *FlagClause) FloatVar(target *float64)
Float sets the parser to a float64 parser.
func (*FlagClause) Hidden ¶
func (f *FlagClause) Hidden() *FlagClause
Hidden hides a flag from usage but still allows it to be used.
func (*FlagClause) Int ¶
func (p *FlagClause) Int() (target *int)
Int sets the parser to an int parser.
func (*FlagClause) IntVar ¶
func (p *FlagClause) IntVar(target *int)
Int sets the parser to an int parser.
func (*FlagClause) OpenFileVar ¶
OpenFileVar calls os.OpenFile(flag, perm)
func (*FlagClause) OverrideDefaultFromEnvar ¶
func (f *FlagClause) OverrideDefaultFromEnvar(envar string) *FlagClause
OverrideDefaultFromEnvar overrides the default value for a flag from an environment variable, if available.
func (*FlagClause) PlaceHolder ¶
func (f *FlagClause) PlaceHolder(placeholder string) *FlagClause
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 (*FlagClause) Required ¶
func (f *FlagClause) Required() *FlagClause
Required makes the flag required. You can not provide a Default() value to a Required() flag.
func (*FlagClause) Short ¶
func (f *FlagClause) Short(name byte) *FlagClause
Short sets the short flag name.
func (*FlagClause) String ¶
func (p *FlagClause) String() (target *string)
String sets the parser to a string parser.
func (*FlagClause) StringMapVar ¶
StringMap provides key=value parsing into a map.
func (*FlagClause) StringVar ¶
func (p *FlagClause) StringVar(target *string)
String sets the parser to a string parser.
func (*FlagClause) Strings ¶
func (p *FlagClause) Strings() (target *[]string)
Strings appends multiple occurrences to a string slice.
func (*FlagClause) StringsVar ¶
func (p *FlagClause) StringsVar(target *[]string)
Strings appends multiple occurrences to a string slice.
func (*FlagClause) TCPListVar ¶
TCPVar (host:port) address list.
func (*FlagClause) URLListVar ¶
URLListVar provides a parsed list of url.URL values.
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 ParseContext ¶
func Tokenize ¶
func Tokenize(args []string) *ParseContext
func (*ParseContext) Next ¶
func (p *ParseContext) Next()
func (*ParseContext) Peek ¶
func (p *ParseContext) Peek() *Token
func (*ParseContext) Return ¶
func (p *ParseContext) Return(token *Token)
func (*ParseContext) String ¶
func (p *ParseContext) String() string
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.
Output: