kingpin.v1: gopkg.in/alecthomas/kingpin.v1 Index | Examples | Files

package kingpin

import "gopkg.in/alecthomas/kingpin.v1"

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

Examples

Package Files

app.go args.go cmd.go doc.go flags.go global.go guesswidth_unix.go lexer.go parser.go parsers.go usage.go values.go

Variables

var (
    // CommandLine is the default Kingpin parser.
    CommandLine = New(filepath.Base(os.Args[0]), "")
)
var (
    TokenEOLMarker = Token{TokenEOL, ""}
)

func ExpandArgsFromFiles Uses

func ExpandArgsFromFiles(args []string) ([]string, error)

ExpandArgsFromFiles expands arguments in the form @<file> into one-arg-per- line read from that file.

func FatalIfError Uses

func FatalIfError(err error, prefix string)

FatalIfError prints an error and exits if err is not nil. The error is printed with the given prefix.

func Fatalf Uses

func Fatalf(format string, args ...interface{})

Fatalf prints an error message to stderr and exits.

func MustParse Uses

func MustParse(command string, err error) string

MustParse can be used with app.Parse(args) to exit with an error if parsing fails.

func Parse Uses

func Parse() string

Parse and return the selected command. Will exit with a non-zero status if an error was encountered.

func ParseWithFileExpansion Uses

func ParseWithFileExpansion() string

ParseWithFileExpansion is the same as Parse() but will expand flags from arguments in the form @FILE.

func Usage Uses

func Usage()

Usage prints usage to stderr.

func UsageErrorf Uses

func UsageErrorf(format string, args ...interface{})

UsageErrorf prints an error message followed by usage information, then exits with a non-zero status.

func Version Uses

func Version(version string)

Version adds a flag for displaying the application version number.

type Application Uses

type Application struct {
    Name string
    Help string
    // contains filtered or unexported fields
}

An Application contains the definitions of flags, arguments and commands for an application.

func New Uses

func New(name, help string) *Application

New creates a new Kingpin application instance.

func (Application) Arg Uses

func (a Application) Arg(name, help string) *ArgClause

func (*Application) Command Uses

func (a *Application) Command(name, help string) *CmdClause

Command adds a new top-level command.

func (*Application) CommandUsage Uses

func (a *Application) CommandUsage(w io.Writer, command string)

func (*Application) Errorf Uses

func (a *Application) Errorf(w io.Writer, format string, args ...interface{})

Errorf prints an error message to w.

func (*Application) FatalIfError Uses

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 Uses

func (a *Application) Fatalf(w io.Writer, format string, args ...interface{})

func (Application) Flag Uses

func (f Application) Flag(name, help string) *FlagClause

Flag defines a new flag with the given long name and help.

func (*Application) Parse Uses

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 Uses

func (a *Application) Usage(w io.Writer)

func (*Application) UsageErrorf Uses

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 Uses

func (a *Application) Validate(validator ApplicationValidator) *Application

Validate sets a validation function to run when parsing.

func (*Application) Version Uses

func (a *Application) Version(version string) *Application

Version adds a --version flag for displaying the application version.

type ApplicationValidator Uses

type ApplicationValidator func(*Application) error

type ArgClause Uses

type ArgClause struct {
    // contains filtered or unexported fields
}

func Arg Uses

func Arg(name, help string) *ArgClause

Arg adds a new argument to the top-level of the default parser.

func (*ArgClause) Bool Uses

func (p *ArgClause) Bool() (target *bool)

Bool sets the parser to a boolean parser. Supports --no-<X> to disable the flag.

func (*ArgClause) BoolVar Uses

func (p *ArgClause) BoolVar(target *bool)

Bool sets the parser to a boolean parser. Supports --no-<X> to disable the flag.

func (*ArgClause) Bytes Uses

func (p *ArgClause) Bytes() (target *units.Base2Bytes)

Bytes parses numeric byte units. eg. 1.5KB

func (*ArgClause) BytesVar Uses

func (p *ArgClause) BytesVar(target *units.Base2Bytes)

BytesVar parses numeric byte units. eg. 1.5KB

func (*ArgClause) Default Uses

func (a *ArgClause) Default(value string) *ArgClause

Default value for this argument. It *must* be parseable by the value of the argument.

func (*ArgClause) Dispatch Uses

func (a *ArgClause) Dispatch(dispatch Dispatch) *ArgClause

func (*ArgClause) Duration Uses

func (p *ArgClause) Duration() (target *time.Duration)

Duration sets the parser to a time.Duration parser.

func (*ArgClause) DurationVar Uses

func (p *ArgClause) DurationVar(target *time.Duration)

Duration sets the parser to a time.Duration parser.

func (*ArgClause) Enum Uses

func (p *ArgClause) Enum(options ...string) (target *string)

Enum allows a value from a set of options.

func (*ArgClause) EnumVar Uses

func (p *ArgClause) EnumVar(target **string, options ...string)

EnumVar allows a value from a set of options.

func (*ArgClause) Enums Uses

func (p *ArgClause) Enums(options ...string) (target *[]string)

Enums allows a set of values from a set of options.

func (*ArgClause) EnumsVar Uses

func (p *ArgClause) EnumsVar(target *[]string, options ...string)

EnumVar allows a value from a set of options.

func (*ArgClause) ExistingDir Uses

func (p *ArgClause) ExistingDir() (target *string)

ExistingDir sets the parser to one that requires and returns an existing directory.

func (*ArgClause) ExistingDirVar Uses

func (p *ArgClause) ExistingDirVar(target *string)

ExistingDir sets the parser to one that requires and returns an existing directory.

func (*ArgClause) ExistingFile Uses

func (p *ArgClause) ExistingFile() (target *string)

ExistingFile sets the parser to one that requires and returns an existing file.

func (*ArgClause) ExistingFileVar Uses

func (p *ArgClause) ExistingFileVar(target *string)

ExistingFile sets the parser to one that requires and returns an existing file.

func (*ArgClause) File Uses

func (p *ArgClause) File() (target **os.File)

File returns an os.File against an existing file.

func (*ArgClause) FileVar Uses

func (p *ArgClause) FileVar(target **os.File)

FileVar opens an existing file.

func (*ArgClause) Float Uses

func (p *ArgClause) Float() (target *float64)

Float sets the parser to a float64 parser.

func (*ArgClause) FloatVar Uses

func (p *ArgClause) FloatVar(target *float64)

Float sets the parser to a float64 parser.

func (*ArgClause) IP Uses

func (p *ArgClause) IP() (target *net.IP)

IP sets the parser to a net.IP parser.

func (*ArgClause) IPVar Uses

func (p *ArgClause) IPVar(target *net.IP)

IP sets the parser to a net.IP parser.

func (*ArgClause) Int Uses

func (p *ArgClause) Int() (target *int)

Int sets the parser to an int parser.

func (*ArgClause) Int64 Uses

func (p *ArgClause) Int64() (target *int64)

Int64 parses an int64

func (*ArgClause) Int64Var Uses

func (p *ArgClause) Int64Var(target *int64)

Int64 parses an int64

func (*ArgClause) IntVar Uses

func (p *ArgClause) IntVar(target *int)

Int sets the parser to an int parser.

func (*ArgClause) OpenFile Uses

func (p *ArgClause) OpenFile(flag int, perm os.FileMode) (target **os.File)

File attempts to open a File with os.OpenFile(flag, perm).

func (*ArgClause) OpenFileVar Uses

func (p *ArgClause) OpenFileVar(target **os.File, flag int, perm os.FileMode)

OpenFileVar calls os.OpenFile(flag, perm)

func (*ArgClause) Required Uses

func (a *ArgClause) Required() *ArgClause

Required arguments must be input by the user. They can not have a Default() value provided.

func (*ArgClause) SetValue Uses

func (p *ArgClause) SetValue(value Value)

func (*ArgClause) String Uses

func (p *ArgClause) String() (target *string)

String sets the parser to a string parser.

func (*ArgClause) StringMap Uses

func (p *ArgClause) StringMap() (target *map[string]string)

StringMap provides key=value parsing into a map.

func (*ArgClause) StringMapVar Uses

func (p *ArgClause) StringMapVar(target *map[string]string)

StringMap provides key=value parsing into a map.

func (*ArgClause) StringVar Uses

func (p *ArgClause) StringVar(target *string)

String sets the parser to a string parser.

func (*ArgClause) Strings Uses

func (p *ArgClause) Strings() (target *[]string)

Strings appends multiple occurrences to a string slice.

func (*ArgClause) StringsVar Uses

func (p *ArgClause) StringsVar(target *[]string)

Strings appends multiple occurrences to a string slice.

func (*ArgClause) TCP Uses

func (p *ArgClause) TCP() (target **net.TCPAddr)

TCP (host:port) address.

func (*ArgClause) TCPList Uses

func (p *ArgClause) TCPList() (target *[]*net.TCPAddr)

TCP (host:port) address list.

func (*ArgClause) TCPListVar Uses

func (p *ArgClause) TCPListVar(target *[]*net.TCPAddr)

TCPVar (host:port) address list.

func (*ArgClause) TCPVar Uses

func (p *ArgClause) TCPVar(target **net.TCPAddr)

TCPVar (host:port) address.

func (*ArgClause) URL Uses

func (p *ArgClause) URL() (target **url.URL)

URL provides a valid, parsed url.URL.

func (*ArgClause) URLList Uses

func (p *ArgClause) URLList() (target *[]*url.URL)

URLList provides a parsed list of url.URL values.

func (*ArgClause) URLListVar Uses

func (p *ArgClause) URLListVar(target *[]*url.URL)

URLListVar provides a parsed list of url.URL values.

func (*ArgClause) URLVar Uses

func (p *ArgClause) URLVar(target **url.URL)

URL provides a valid, parsed url.URL.

func (*ArgClause) Uint64 Uses

func (p *ArgClause) Uint64() (target *uint64)

Uint64 parses a uint64

func (*ArgClause) Uint64Var Uses

func (p *ArgClause) Uint64Var(target *uint64)

Uint64 parses a uint64

type CmdClause Uses

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 Command Uses

func Command(name, help string) *CmdClause

Command adds a new command to the default parser.

func (CmdClause) Arg Uses

func (a CmdClause) Arg(name, help string) *ArgClause

func (*CmdClause) Command Uses

func (c *CmdClause) Command(name, help string) *CmdClause

Command adds a new sub-command.

func (*CmdClause) Dispatch Uses

func (c *CmdClause) Dispatch(dispatch Dispatch) *CmdClause

func (CmdClause) Flag Uses

func (f CmdClause) Flag(name, help string) *FlagClause

Flag defines a new flag with the given long name and help.

func (*CmdClause) FullCommand Uses

func (c *CmdClause) FullCommand() string

func (*CmdClause) Validate Uses

func (c *CmdClause) Validate(validator CmdClauseValidator) *CmdClause

Validate sets a validation function to run when parsing.

type CmdClauseValidator Uses

type CmdClauseValidator func(*CmdClause) error

type Dispatch Uses

type Dispatch func(*ParseContext) error

type FlagClause Uses

type FlagClause struct {
    // contains filtered or unexported fields
}

FlagClause is a fluid interface used to build flags.

func Flag Uses

func Flag(name, help string) *FlagClause

Flag adds a new flag to the default parser.

func (*FlagClause) Bool Uses

func (f *FlagClause) Bool() (target *bool)

Bool makes this flag a boolean flag.

func (*FlagClause) BoolVar Uses

func (p *FlagClause) BoolVar(target *bool)

Bool sets the parser to a boolean parser. Supports --no-<X> to disable the flag.

func (*FlagClause) Bytes Uses

func (p *FlagClause) Bytes() (target *units.Base2Bytes)

Bytes parses numeric byte units. eg. 1.5KB

func (*FlagClause) BytesVar Uses

func (p *FlagClause) BytesVar(target *units.Base2Bytes)

BytesVar parses numeric byte units. eg. 1.5KB

func (*FlagClause) Default Uses

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 Uses

func (f *FlagClause) Dispatch(dispatch Dispatch) *FlagClause

Dispatch to the given function when the flag is parsed.

func (*FlagClause) Duration Uses

func (p *FlagClause) Duration() (target *time.Duration)

Duration sets the parser to a time.Duration parser.

func (*FlagClause) DurationVar Uses

func (p *FlagClause) DurationVar(target *time.Duration)

Duration sets the parser to a time.Duration parser.

func (*FlagClause) Enum Uses

func (p *FlagClause) Enum(options ...string) (target *string)

Enum allows a value from a set of options.

func (*FlagClause) EnumVar Uses

func (p *FlagClause) EnumVar(target **string, options ...string)

EnumVar allows a value from a set of options.

func (*FlagClause) Enums Uses

func (p *FlagClause) Enums(options ...string) (target *[]string)

Enums allows a set of values from a set of options.

func (*FlagClause) EnumsVar Uses

func (p *FlagClause) EnumsVar(target *[]string, options ...string)

EnumVar allows a value from a set of options.

func (*FlagClause) ExistingDir Uses

func (p *FlagClause) ExistingDir() (target *string)

ExistingDir sets the parser to one that requires and returns an existing directory.

func (*FlagClause) ExistingDirVar Uses

func (p *FlagClause) ExistingDirVar(target *string)

ExistingDir sets the parser to one that requires and returns an existing directory.

func (*FlagClause) ExistingFile Uses

func (p *FlagClause) ExistingFile() (target *string)

ExistingFile sets the parser to one that requires and returns an existing file.

func (*FlagClause) ExistingFileVar Uses

func (p *FlagClause) ExistingFileVar(target *string)

ExistingFile sets the parser to one that requires and returns an existing file.

func (*FlagClause) File Uses

func (p *FlagClause) File() (target **os.File)

File returns an os.File against an existing file.

func (*FlagClause) FileVar Uses

func (p *FlagClause) FileVar(target **os.File)

FileVar opens an existing file.

func (*FlagClause) Float Uses

func (p *FlagClause) Float() (target *float64)

Float sets the parser to a float64 parser.

func (*FlagClause) FloatVar Uses

func (p *FlagClause) FloatVar(target *float64)

Float sets the parser to a float64 parser.

func (*FlagClause) Hidden Uses

func (f *FlagClause) Hidden() *FlagClause

Hidden hides a flag from usage but still allows it to be used.

func (*FlagClause) IP Uses

func (p *FlagClause) IP() (target *net.IP)

IP sets the parser to a net.IP parser.

func (*FlagClause) IPVar Uses

func (p *FlagClause) IPVar(target *net.IP)

IP sets the parser to a net.IP parser.

func (*FlagClause) Int Uses

func (p *FlagClause) Int() (target *int)

Int sets the parser to an int parser.

func (*FlagClause) Int64 Uses

func (p *FlagClause) Int64() (target *int64)

Int64 parses an int64

func (*FlagClause) Int64Var Uses

func (p *FlagClause) Int64Var(target *int64)

Int64 parses an int64

func (*FlagClause) IntVar Uses

func (p *FlagClause) IntVar(target *int)

Int sets the parser to an int parser.

func (*FlagClause) OpenFile Uses

func (p *FlagClause) OpenFile(flag int, perm os.FileMode) (target **os.File)

File attempts to open a File with os.OpenFile(flag, perm).

func (*FlagClause) OpenFileVar Uses

func (p *FlagClause) OpenFileVar(target **os.File, flag int, perm os.FileMode)

OpenFileVar calls os.OpenFile(flag, perm)

func (*FlagClause) OverrideDefaultFromEnvar Uses

func (f *FlagClause) OverrideDefaultFromEnvar(envar string) *FlagClause

OverrideDefaultFromEnvar overrides the default value for a flag from an environment variable, if available.

func (*FlagClause) PlaceHolder Uses

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 Uses

func (f *FlagClause) Required() *FlagClause

Required makes the flag required. You can not provide a Default() value to a Required() flag.

func (*FlagClause) SetValue Uses

func (p *FlagClause) SetValue(value Value)

func (*FlagClause) Short Uses

func (f *FlagClause) Short(name byte) *FlagClause

Short sets the short flag name.

func (*FlagClause) String Uses

func (p *FlagClause) String() (target *string)

String sets the parser to a string parser.

func (*FlagClause) StringMap Uses

func (p *FlagClause) StringMap() (target *map[string]string)

StringMap provides key=value parsing into a map.

func (*FlagClause) StringMapVar Uses

func (p *FlagClause) StringMapVar(target *map[string]string)

StringMap provides key=value parsing into a map.

func (*FlagClause) StringVar Uses

func (p *FlagClause) StringVar(target *string)

String sets the parser to a string parser.

func (*FlagClause) Strings Uses

func (p *FlagClause) Strings() (target *[]string)

Strings appends multiple occurrences to a string slice.

func (*FlagClause) StringsVar Uses

func (p *FlagClause) StringsVar(target *[]string)

Strings appends multiple occurrences to a string slice.

func (*FlagClause) TCP Uses

func (p *FlagClause) TCP() (target **net.TCPAddr)

TCP (host:port) address.

func (*FlagClause) TCPList Uses

func (p *FlagClause) TCPList() (target *[]*net.TCPAddr)

TCP (host:port) address list.

func (*FlagClause) TCPListVar Uses

func (p *FlagClause) TCPListVar(target *[]*net.TCPAddr)

TCPVar (host:port) address list.

func (*FlagClause) TCPVar Uses

func (p *FlagClause) TCPVar(target **net.TCPAddr)

TCPVar (host:port) address.

func (*FlagClause) URL Uses

func (p *FlagClause) URL() (target **url.URL)

URL provides a valid, parsed url.URL.

func (*FlagClause) URLList Uses

func (p *FlagClause) URLList() (target *[]*url.URL)

URLList provides a parsed list of url.URL values.

func (*FlagClause) URLListVar Uses

func (p *FlagClause) URLListVar(target *[]*url.URL)

URLListVar provides a parsed list of url.URL values.

func (*FlagClause) URLVar Uses

func (p *FlagClause) URLVar(target **url.URL)

URL provides a valid, parsed url.URL.

func (*FlagClause) Uint64 Uses

func (p *FlagClause) Uint64() (target *uint64)

Uint64 parses a uint64

func (*FlagClause) Uint64Var Uses

func (p *FlagClause) Uint64Var(target *uint64)

Uint64 parses a uint64

type Getter Uses

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 Uses

type ParseContext struct {
    Tokens          Tokens
    SelectedCommand string
}

func Tokenize Uses

func Tokenize(args []string) *ParseContext

func (*ParseContext) Next Uses

func (p *ParseContext) Next()

func (*ParseContext) Peek Uses

func (p *ParseContext) Peek() *Token

func (*ParseContext) Return Uses

func (p *ParseContext) Return(token *Token)

func (*ParseContext) String Uses

func (p *ParseContext) String() string

type Settings Uses

type Settings interface {
    SetValue(value Value)
}

type Token Uses

type Token struct {
    Type  TokenType
    Value string
}

func (*Token) IsEOF Uses

func (t *Token) IsEOF() bool

func (*Token) IsFlag Uses

func (t *Token) IsFlag() bool

func (*Token) String Uses

func (t *Token) String() string

type TokenType Uses

type TokenType int
const (
    TokenShort TokenType = iota
    TokenLong
    TokenArg
    TokenEOL
)

Token types.

type Tokens Uses

type Tokens []*Token

func (Tokens) Next Uses

func (t Tokens) Next() Tokens

func (Tokens) Peek Uses

func (t Tokens) Peek() *Token

func (Tokens) Return Uses

func (t Tokens) Return(token *Token) Tokens

func (Tokens) String Uses

func (t Tokens) String() string

type Value Uses

type Value interface {
    String() string
    Set(string) error
}

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.

This example ilustrates how to define custom parsers. HTTPHeader cumulatively parses each encountered --header flag into a http.Header struct.

Code:

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) String() string {
    return ""
}

func HTTPHeader(s Settings) (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)
    }
}

Package kingpin imports 16 packages (graph) and is imported by 112 packages. Updated 2016-07-15. Refresh now. Tools for package owners.