kingpin

package module
v2.2.5+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 27, 2017 License: MIT Imports: 20 Imported by: 0

README

Kingpin - A Go (golang) command line and flag parser

Build Status Gitter chat

Overview

Kingpin is a fluent-style, type-safe command-line parser. It supports flags, nested commands, and positional arguments.

Install it with:

$ go get gopkg.in/alecthomas/kingpin.v2

It looks like this:

var (
  verbose = kingpin.Flag("verbose", "Verbose mode.").Short('v').Bool()
  name    = kingpin.Arg("name", "Name of user.").Required().String()
)

func main() {
  kingpin.Parse()
  fmt.Printf("%v, %s\n", *verbose, *name)
}

More examples are available.

Second to parsing, providing the user with useful help is probably the most important thing a command-line parser does. Kingpin tries to provide detailed contextual help if --help is encountered at any point in the command line (excluding after --).

Features

  • Help output that isn't as ugly as sin.
  • Fully customisable help, via Go templates.
  • Parsed, type-safe flags (kingpin.Flag("f", "help").Int())
  • Parsed, type-safe positional arguments (kingpin.Arg("a", "help").Int()).
  • Parsed, type-safe, arbitrarily deep commands (kingpin.Command("c", "help")).
  • Support for required flags and required positional arguments (kingpin.Flag("f", "").Required().Int()).
  • Support for arbitrarily nested default commands (command.Default()).
  • Callbacks per command, flag and argument (kingpin.Command("c", "").Action(myAction)).
  • POSIX-style short flag combining (-a -b -> -ab).
  • Short-flag+parameter combining (-a parm -> -aparm).
  • Read command-line from files (@<file>).
  • Automatically generate man pages (--help-man).

User-visible changes between v1 and v2

Flags can be used at any point after their definition.

Flags can be specified at any point after their definition, not just immediately after their associated command. From the chat example below, the following used to be required:

$ chat --server=chat.server.com:8080 post --image=~/Downloads/owls.jpg pics

But the following will now work:

$ chat post --server=chat.server.com:8080 --image=~/Downloads/owls.jpg pics
Short flags can be combined with their parameters

Previously, if a short flag was used, any argument to that flag would have to be separated by a space. That is no longer the case.

API changes between v1 and v2

  • ParseWithFileExpansion() is gone. The new parser directly supports expanding @<file>.
  • Added FatalUsage() and FatalUsageContext() for displaying an error + usage and terminating.
  • Dispatch() renamed to Action().
  • Added ParseContext() for parsing a command line into its intermediate context form without executing.
  • Added Terminate() function to override the termination function.
  • Added UsageForContextWithTemplate() for printing usage via a custom template.
  • Added UsageTemplate() for overriding the default template to use. Two templates are included:
    1. DefaultUsageTemplate - default template.
    2. CompactUsageTemplate - compact command template for larger applications.

Versions

Kingpin uses gopkg.in for versioning.

The current stable version is gopkg.in/alecthomas/kingpin.v2. The previous version, gopkg.in/alecthomas/kingpin.v1, is deprecated and in maintenance mode.

V2 is the current stable version

Installation:

$ go get gopkg.in/alecthomas/kingpin.v2
V1 is the OLD stable version

Installation:

$ go get gopkg.in/alecthomas/kingpin.v1

Change History

  • 2015-09-19 -- Stable v2.1.0 release.

    • Added command.Default() to specify a default command to use if no other command matches. This allows for convenient user shortcuts.
    • Exposed HelpFlag and VersionFlag for further customisation.
    • Action() and PreAction() added and both now support an arbitrary number of callbacks.
    • kingpin.SeparateOptionalFlagsUsageTemplate.
    • --help-long and --help-man (hidden by default) flags.
    • Flags are "interspersed" by default, but can be disabled with app.Interspersed(false).
    • Added flags for all simple builtin types (int8, uint16, etc.) and slice variants.
    • Use app.Writer(os.Writer) to specify the default writer for all output functions.
    • Dropped os.Writer prefix from all printf-like functions.
  • 2015-05-22 -- Stable v2.0.0 release.

    • Initial stable release of v2.0.0.
    • Fully supports interspersed flags, commands and arguments.
    • Flags can be present at any point after their logical definition.
    • Application.Parse() terminates if commands are present and a command is not parsed.
    • Dispatch() -> Action().
    • Actions are dispatched after all values are populated.
    • Override termination function (defaults to os.Exit).
    • Override output stream (defaults to os.Stderr).
    • Templatised usage help, with default and compact templates.
    • Make error/usage functions more consistent.
    • Support argument expansion from files by default (with @).
    • Fully public data model is available via .Model().
    • Parser has been completely refactored.
    • Parsing and execution has been split into distinct stages.
    • Use go generate to generate repeated flags.
    • Support combined short-flag+argument: -fARG.
  • 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").
  • 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 to PlaceHolder.
    • Removed MetaVarFromDefault. Kingpin now uses heuristics to determine what to display.

Examples

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.v2"
)

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\n", *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.v2"
)

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

Displaying errors and usage information

Kingpin exports a set of functions to provide consistent errors and usage information to the user.

Error messages look something like this:

<app>: error: <message>

The functions on Application are:

Function Purpose
Errorf(format, args) Display a printf formatted error to the user.
Fatalf(format, args) As with Errorf, but also call the termination handler.
FatalUsage(format, args) As with Fatalf, but also print contextual usage information.
FatalUsageContext(context, format, args) As with Fatalf, but also print contextual usage information from a ParseContext.
FatalIfError(err, format, args) Conditionally print an error prefixed with format+args, then call the termination handler

There are equivalent global functions in the kingpin namespace for the default kingpin.CommandLine instance.

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() (see parsers.go for a complete list of included parsers).

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 = &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'))
Repeatable flags

Depending on the Value they hold, some flags may be repeated. The IsCumulative() bool function on Value tells if it's safe to call Set() multiple times or if an error should be raised if several values are passed.

The built-in Values returning slices and maps, as well as Counter are examples of Values that make a flag repeatable.

Boolean values

Boolean values are uniquely managed by Kingpin. Each boolean flag will have a negative complement: --<name> and --no-<name>.

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 one or several strings, which are parsed by the value itself, so they 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

Such arguments are similar to repeatable flags, but for arguments. Therefore they use the same IsCumulative() bool function on the underlying Value, so the built-in Values for which the Set() function can be called several times will consume multiple arguments.

To implement the above example with a custom Value, 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."))
Bash/ZSH Shell Completion

By default, all flags and commands/subcommands generate completions internally.

Out of the box, CLI tools using kingpin should be able to take advantage of completion hinting for flags and commands. By specifying --completion-bash as the first argument, your CLI tool will show possible subcommands. By ending your argv with --, hints for flags will be shown.

To allow your end users to take advantage you must package a /etc/bash_completion.d script with your distribution (or the equivalent for your target platform/shell). An alternative is to instruct your end user to source a script from their bash_profile (or equivalent).

Fortunately Kingpin makes it easy to generate or source a script for use with end users shells. ./yourtool --completion-script-bash and ./yourtool --completion-script-zsh will generate these scripts for you.

Installation by Package

For the best user experience, you should bundle your pre-created completion script with your CLI tool and install it inside /etc/bash_completion.d (or equivalent). A good suggestion is to add this as an automated step to your build pipeline, in the implementation is improved for bug fixed.

Installation by bash_profile

Alternatively, instruct your users to add an additional statement to their bash_profile (or equivalent):

eval "$(your-cli-tool --completion-script-bash)"

Or for ZSH

eval "$(your-cli-tool --completion-script-zsh)"
Additional API

To provide more flexibility, a completion option API has been exposed for flags to allow user defined completion options, to extend completions further than just EnumVar/Enum.

Provide Static Options

When using an Enum or EnumVar, users are limited to only the options given. Maybe we wish to hint possible options to the user, but also allow them to provide their own custom option. HintOptions gives this functionality to flags.

app := kingpin.New("completion", "My application with bash completion.")
app.Flag("port", "Provide a port to connect to").
    Required().
    HintOptions("80", "443", "8080").
    IntVar(&c.port)

Provide Dynamic Options Consider the case that you needed to read a local database or a file to provide suggestions. You can dynamically generate the options

func listHosts() []string {
  // Provide a dynamic list of hosts from a hosts file or otherwise
  // for bash completion. In this example we simply return static slice.

  // You could use this functionality to reach into a hosts file to provide
  // completion for a list of known hosts.
  return []string{"sshhost.example", "webhost.example", "ftphost.example"}
}

app := kingpin.New("completion", "My application with bash completion.")
app.Flag("flag-1", "").HintAction(listHosts).String()

EnumVar/Enum When using Enum or EnumVar, any provided options will be automatically used for bash autocompletion. However, if you wish to provide a subset or different options, you can use HintOptions or HintAction which will override the default completion options for Enum/EnumVar.

Examples You can see an in depth example of the completion API within examples/completion/main.go

Supporting -h for help

kingpin.CommandLine.HelpFlag.Short('h')

Custom help

Kingpin v2 supports templatised help using the text/template library (actually, a fork).

You can specify the template to use with the Application.UsageTemplate() function.

There are four included templates: kingpin.DefaultUsageTemplate is the default, kingpin.CompactUsageTemplate provides a more compact representation for more complex command-line structures, kingpin.SeparateOptionalFlagsUsageTemplate looks like the default template, but splits required and optional command flags into separate lists, and kingpin.ManPageTemplate is used to generate man pages.

See the above templates for examples of usage, and the the function UsageForContextWithTemplate() method for details on the context.

Default help template
$ go run ./examples/curl/curl.go --help
usage: curl [<flags>] <command> [<args> ...]

An example implementation of curl.

Flags:
  --help            Show help.
  -t, --timeout=5s  Set connection timeout.
  -H, --headers=HEADER=VALUE
                    Add HTTP headers to the request.

Commands:
  help [<command>...]
    Show help.

  get url <url>
    Retrieve a URL.

  get file <file>
    Retrieve a file.

  post [<flags>] <url>
    POST a resource.
Compact help template
$ go run ./examples/curl/curl.go --help
usage: curl [<flags>] <command> [<args> ...]

An example implementation of curl.

Flags:
  --help            Show help.
  -t, --timeout=5s  Set connection timeout.
  -H, --headers=HEADER=VALUE
                    Add HTTP headers to the request.

Commands:
  help [<command>...]
  get [<flags>]
    url <url>
    file <file>
  post [<flags>] <url>

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.v2"

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 != "" {
    }
  }
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// CommandLine is the default Kingpin parser.
	CommandLine = New(filepath.Base(os.Args[0]), "")
	// Global help flag. Exposed for user customisation.
	HelpFlag = CommandLine.HelpFlag
	// Top-level help command. Exposed for user customisation. May be nil.
	HelpCommand = CommandLine.HelpCommand
	// Global version flag. Exposed for user customisation. May be nil.
	VersionFlag = CommandLine.VersionFlag
)
View Source
var BashCompletionTemplate = `` /* 327-byte string literal not displayed */
View Source
var CompactUsageTemplate = `` /* 1254-byte string literal not displayed */

Usage template with compactly formatted commands.

View Source
var DefaultUsageTemplate = `` /* 1185-byte string literal not displayed */

Default usage template.

View Source
var (
	ErrCommandNotSpecified = fmt.Errorf("command not specified")
)
View Source
var LongHelpTemplate = `` /* 925-byte string literal not displayed */

Default usage template.

View Source
var ManPageTemplate = `` /* 1083-byte string literal not displayed */
View Source
var SeparateOptionalFlagsUsageTemplate = `` /* 1349-byte string literal not displayed */

Usage template where command's optional flags are listed separately

View Source
var (
	TokenEOLMarker = Token{-1, TokenEOL, ""}
)
View Source
var ZshCompletionTemplate = `` /* 424-byte string literal not displayed */

Functions

func Errorf

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

Errorf prints an error message to stderr.

func ExpandArgsFromFile

func ExpandArgsFromFile(filename string) (out []string, err error)

Expand arguments from a file. Lines starting with # will be treated as comments.

func FatalIfError

func 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 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 MustParse

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

func Parse() string

Parse and return the selected command. Will call the termination handler if an error is encountered.

func Usage

func Usage()

Usage prints usage to stderr.

Types

type Action

type Action func(*ParseContext) error

Action callback executed at various stages after all values are populated. The application, commands, arguments and flags all have corresponding actions.

type Application

type Application struct {
	Name string
	Help string

	// Help flag. Exposed for user customisation.
	HelpFlag *FlagClause
	// Help command. Exposed for user customisation. May be nil.
	HelpCommand *CmdClause
	// Version flag. Exposed for user customisation. May be nil.
	VersionFlag *FlagClause
	// contains filtered or unexported fields
}

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

func New

func New(name, help string) *Application

New creates a new Kingpin application instance.

func UsageTemplate

func UsageTemplate(template string) *Application

Set global usage template to use (defaults to DefaultUsageTemplate).

func Version added in v0.3.0

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 callback to call when all values are populated and parsing is complete, but before any command, flag or argument actions.

All Action() callbacks are called in the order they are encountered on the command line.

func (*Application) Author

func (a *Application) Author(author string) *Application

Author sets the author output by some help 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) ErrorWriter

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

ErrorWriter sets the io.Writer to use for errors.

func (*Application) Errorf added in v1.2.3

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

Errorf prints an error message to w in the format "<appname>: error: <message>".

func (*Application) FatalIfError added in v1.2.3

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 added in v1.3.0

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 (c *Application) FlagCompletion(flagName string, flagValue string) (choices []string, flagMatch bool, optionMatch bool)

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

Action called after parsing completes but before validation and execution.

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 w. It parses args to determine appropriate help context, such as which command to show help for.

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(context *ParseContext, indent int, tmpl string) error

UsageForContextWithTemplate is the base usage function. 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. The default is UsageTemplate.

func (*Application) UsageWriter

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

UsageWriter sets the io.Writer to use for errors.

func (*Application) Validate added in v1.3.3

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

Validate sets a validation function to run when parsing.

func (*Application) Version added in v0.3.0

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

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

func (*Application) Writer

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

Writer specifies the writer to use for usage and errors. Defaults to os.Stderr. DEPRECATED: See ErrorWriter and UsageWriter.

type ApplicationModel

type ApplicationModel struct {
	Name    string
	Help    string
	Version string
	Author  string
	*ArgGroupModel
	*CmdGroupModel
	*FlagGroupModel
}

type ApplicationValidator added in v1.3.3

type ApplicationValidator func(*Application) error

type ArgClause

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

func Arg

func Arg(name, help string) *ArgClause

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

func (*ArgClause) Action

func (a *ArgClause) Action(action Action) *ArgClause

func (*ArgClause) Bool

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

Bool parses the next command-line value as bool.

func (*ArgClause) BoolList

func (p *ArgClause) BoolList() (target *[]bool)

BoolList accumulates bool values into a slice.

func (*ArgClause) BoolListVar

func (p *ArgClause) BoolListVar(target *[]bool)

func (*ArgClause) BoolVar

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

func (*ArgClause) Bytes added in v1.2.0

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

Bytes parses numeric byte units. eg. 1.5KB

func (*ArgClause) BytesVar added in v1.2.0

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

BytesVar parses numeric byte units. eg. 1.5KB

func (*ArgClause) Counter

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

A Counter increments a number each time it is encountered.

func (*ArgClause) CounterVar

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

func (*ArgClause) Default

func (a *ArgClause) Default(values ...string) *ArgClause

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

func (*ArgClause) Duration

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

Duration sets the parser to a time.Duration parser.

func (*ArgClause) DurationList

func (p *ArgClause) DurationList() (target *[]time.Duration)

DurationList accumulates time.Duration values into a slice.

func (*ArgClause) DurationListVar

func (p *ArgClause) DurationListVar(target *[]time.Duration)

func (*ArgClause) DurationVar

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

Duration sets the parser to a time.Duration parser.

func (*ArgClause) Enum added in v1.2.0

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

Enum allows a value from a set of options.

func (*ArgClause) EnumVar added in v1.2.0

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

EnumVar allows a value from a set of options.

func (*ArgClause) Enums added in v1.3.6

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

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

func (*ArgClause) EnumsVar added in v1.3.6

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

EnumVar allows a value from a set of options.

func (*ArgClause) Envar

func (a *ArgClause) Envar(name string) *ArgClause

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 (*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) ExistingDirs

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

ExistingDirs accumulates string values into a slice.

func (*ArgClause) ExistingDirsVar

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

func (*ArgClause) ExistingFile

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

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

func (*ArgClause) ExistingFileOrDir

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

ExistingFileOrDir sets the parser to one that requires and returns an existing file OR directory.

func (*ArgClause) ExistingFileOrDirVar

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

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

func (*ArgClause) ExistingFileVar

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

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

func (*ArgClause) ExistingFiles

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

ExistingFiles accumulates string values into a slice.

func (*ArgClause) ExistingFilesOrDirs

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

ExistingFilesOrDirs accumulates string values into a slice.

func (*ArgClause) ExistingFilesOrDirsVar

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

func (*ArgClause) ExistingFilesVar

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

func (*ArgClause) File

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

File returns an os.File against an existing file.

func (*ArgClause) FileVar

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

FileVar opens an existing file.

func (*ArgClause) Float

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

Float sets the parser to a float64 parser.

func (*ArgClause) Float32

func (p *ArgClause) Float32() (target *float32)

Float32 parses the next command-line value as float32.

func (*ArgClause) Float32List

func (p *ArgClause) Float32List() (target *[]float32)

Float32List accumulates float32 values into a slice.

func (*ArgClause) Float32ListVar

func (p *ArgClause) Float32ListVar(target *[]float32)

func (*ArgClause) Float32Var

func (p *ArgClause) Float32Var(target *float32)

func (*ArgClause) Float64

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

Float64 parses the next command-line value as float64.

func (*ArgClause) Float64List

func (p *ArgClause) Float64List() (target *[]float64)

Float64List accumulates float64 values into a slice.

func (*ArgClause) Float64ListVar

func (p *ArgClause) Float64ListVar(target *[]float64)

func (*ArgClause) Float64Var

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

func (*ArgClause) FloatVar

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

Float sets the parser to a float64 parser.

func (*ArgClause) GetEnvarValue

func (e *ArgClause) GetEnvarValue() string

func (*ArgClause) GetSplitEnvarValue

func (e *ArgClause) GetSplitEnvarValue() []string

func (*ArgClause) HasEnvarValue

func (e *ArgClause) HasEnvarValue() bool

func (*ArgClause) HexBytes

func (p *ArgClause) HexBytes() (target *[]byte)

Bytes as a hex string.

func (*ArgClause) HexBytesList

func (p *ArgClause) HexBytesList() (target *[][]byte)

HexBytesList accumulates []byte values into a slice.

func (*ArgClause) HexBytesListVar

func (p *ArgClause) HexBytesListVar(target *[][]byte)

func (*ArgClause) HexBytesVar

func (p *ArgClause) HexBytesVar(target *[]byte)

func (*ArgClause) HintAction

func (a *ArgClause) HintAction(action HintAction) *ArgClause

HintAction registers a HintAction (function) for the arg to provide completions

func (*ArgClause) HintOptions

func (a *ArgClause) HintOptions(options ...string) *ArgClause

HintOptions registers any number of options for the flag to provide completions

func (*ArgClause) IP

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

IP sets the parser to a net.IP parser.

func (*ArgClause) IPList

func (p *ArgClause) IPList() (target *[]net.IP)

IPList accumulates net.IP values into a slice.

func (*ArgClause) IPListVar

func (p *ArgClause) IPListVar(target *[]net.IP)

func (*ArgClause) IPVar

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

IP sets the parser to a net.IP parser.

func (*ArgClause) Int

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

Int parses the next command-line value as int.

func (*ArgClause) Int16

func (p *ArgClause) Int16() (target *int16)

Int16 parses the next command-line value as int16.

func (*ArgClause) Int16List

func (p *ArgClause) Int16List() (target *[]int16)

Int16List accumulates int16 values into a slice.

func (*ArgClause) Int16ListVar

func (p *ArgClause) Int16ListVar(target *[]int16)

func (*ArgClause) Int16Var

func (p *ArgClause) Int16Var(target *int16)

func (*ArgClause) Int32

func (p *ArgClause) Int32() (target *int32)

Int32 parses the next command-line value as int32.

func (*ArgClause) Int32List

func (p *ArgClause) Int32List() (target *[]int32)

Int32List accumulates int32 values into a slice.

func (*ArgClause) Int32ListVar

func (p *ArgClause) Int32ListVar(target *[]int32)

func (*ArgClause) Int32Var

func (p *ArgClause) Int32Var(target *int32)

func (*ArgClause) Int64

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

Int64 parses the next command-line value as int64.

func (*ArgClause) Int64List

func (p *ArgClause) Int64List() (target *[]int64)

Int64List accumulates int64 values into a slice.

func (*ArgClause) Int64ListVar

func (p *ArgClause) Int64ListVar(target *[]int64)

func (*ArgClause) Int64Var

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

func (*ArgClause) Int8

func (p *ArgClause) Int8() (target *int8)

Int8 parses the next command-line value as int8.

func (*ArgClause) Int8List

func (p *ArgClause) Int8List() (target *[]int8)

Int8List accumulates int8 values into a slice.

func (*ArgClause) Int8ListVar

func (p *ArgClause) Int8ListVar(target *[]int8)

func (*ArgClause) Int8Var

func (p *ArgClause) Int8Var(target *int8)

func (*ArgClause) IntVar

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

func (*ArgClause) Ints

func (p *ArgClause) Ints() (target *[]int)

Ints accumulates int values into a slice.

func (*ArgClause) IntsVar

func (p *ArgClause) IntsVar(target *[]int)

func (*ArgClause) Model

func (a *ArgClause) Model() *ArgModel

func (*ArgClause) NoEnvar

func (a *ArgClause) NoEnvar() *ArgClause

NoEnvar forces environment variable defaults to be disabled for this flag. Most useful in conjunction with app.DefaultEnvars().

func (*ArgClause) OpenFile added in v1.1.0

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 added in v1.1.0

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

OpenFileVar calls os.OpenFile(flag, perm)

func (*ArgClause) PreAction

func (a *ArgClause) PreAction(action Action) *ArgClause

func (*ArgClause) Regexp

func (p *ArgClause) Regexp() (target **regexp.Regexp)

Regexp parses the next command-line value as *regexp.Regexp.

func (*ArgClause) RegexpList

func (p *ArgClause) RegexpList() (target *[]*regexp.Regexp)

RegexpList accumulates *regexp.Regexp values into a slice.

func (*ArgClause) RegexpListVar

func (p *ArgClause) RegexpListVar(target *[]*regexp.Regexp)

func (*ArgClause) RegexpVar

func (p *ArgClause) RegexpVar(target **regexp.Regexp)

func (*ArgClause) Required

func (a *ArgClause) Required() *ArgClause

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

func (*ArgClause) ResolvedIP

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

Resolve a hostname or IP to an IP.

func (*ArgClause) ResolvedIPList

func (p *ArgClause) ResolvedIPList() (target *[]net.IP)

ResolvedIPList accumulates net.IP values into a slice.

func (*ArgClause) ResolvedIPListVar

func (p *ArgClause) ResolvedIPListVar(target *[]net.IP)

func (*ArgClause) ResolvedIPVar

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

func (*ArgClause) SetValue

func (p *ArgClause) SetValue(value Value)

func (*ArgClause) String

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

String parses the next command-line value as string.

func (*ArgClause) StringMap

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

StringMap provides key=value parsing into a map.

func (*ArgClause) StringMapVar

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

StringMap provides key=value parsing into a map.

func (*ArgClause) StringVar

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

func (*ArgClause) Strings

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

Strings accumulates string values into a slice.

func (*ArgClause) StringsVar

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

func (*ArgClause) TCP

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

TCP (host:port) address.

func (*ArgClause) TCPList

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

TCPList accumulates *net.TCPAddr values into a slice.

func (*ArgClause) TCPListVar

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

func (*ArgClause) TCPVar

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

TCPVar (host:port) address.

func (*ArgClause) URL

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

URL provides a valid, parsed url.URL.

func (*ArgClause) URLList

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

URLList provides a parsed list of url.URL values.

func (*ArgClause) URLListVar

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

URLListVar provides a parsed list of url.URL values.

func (*ArgClause) URLVar

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

URL provides a valid, parsed url.URL.

func (*ArgClause) Uint

func (p *ArgClause) Uint() (target *uint)

Uint parses the next command-line value as uint.

func (*ArgClause) Uint16

func (p *ArgClause) Uint16() (target *uint16)

Uint16 parses the next command-line value as uint16.

func (*ArgClause) Uint16List

func (p *ArgClause) Uint16List() (target *[]uint16)

Uint16List accumulates uint16 values into a slice.

func (*ArgClause) Uint16ListVar

func (p *ArgClause) Uint16ListVar(target *[]uint16)

func (*ArgClause) Uint16Var

func (p *ArgClause) Uint16Var(target *uint16)

func (*ArgClause) Uint32

func (p *ArgClause) Uint32() (target *uint32)

Uint32 parses the next command-line value as uint32.

func (*ArgClause) Uint32List

func (p *ArgClause) Uint32List() (target *[]uint32)

Uint32List accumulates uint32 values into a slice.

func (*ArgClause) Uint32ListVar

func (p *ArgClause) Uint32ListVar(target *[]uint32)

func (*ArgClause) Uint32Var

func (p *ArgClause) Uint32Var(target *uint32)

func (*ArgClause) Uint64

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

Uint64 parses the next command-line value as uint64.

func (*ArgClause) Uint64List

func (p *ArgClause) Uint64List() (target *[]uint64)

Uint64List accumulates uint64 values into a slice.

func (*ArgClause) Uint64ListVar

func (p *ArgClause) Uint64ListVar(target *[]uint64)

func (*ArgClause) Uint64Var

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

func (*ArgClause) Uint8

func (p *ArgClause) Uint8() (target *uint8)

Uint8 parses the next command-line value as uint8.

func (*ArgClause) Uint8List

func (p *ArgClause) Uint8List() (target *[]uint8)

Uint8List accumulates uint8 values into a slice.

func (*ArgClause) Uint8ListVar

func (p *ArgClause) Uint8ListVar(target *[]uint8)

func (*ArgClause) Uint8Var

func (p *ArgClause) Uint8Var(target *uint8)

func (*ArgClause) UintVar

func (p *ArgClause) UintVar(target *uint)

func (*ArgClause) Uints

func (p *ArgClause) Uints() (target *[]uint)

Uints accumulates uint values into a slice.

func (*ArgClause) UintsVar

func (p *ArgClause) UintsVar(target *[]uint)

type ArgGroupModel

type ArgGroupModel struct {
	Args []*ArgModel
}

func (*ArgGroupModel) ArgSummary

func (a *ArgGroupModel) ArgSummary() string

type ArgModel

type ArgModel struct {
	Name     string
	Help     string
	Default  []string
	Envar    string
	Required bool
	Value    Value
}

func (*ArgModel) String

func (a *ArgModel) 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 Command

func Command(name, help string) *CmdClause

Command adds a new command to the default parser.

func (*CmdClause) Action

func (c *CmdClause) Action(action Action) *CmdClause

func (*CmdClause) Alias

func (c *CmdClause) Alias(name string) *CmdClause

Add an Alias for this command.

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) Command added in v1.2.6

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

Command adds a new sub-command.

func (*CmdClause) Default

func (c *CmdClause) Default() *CmdClause

Default makes this command the default if commands don't match.

func (*CmdClause) FlagCompletion

func (c *CmdClause) FlagCompletion(flagName string, flagValue string) (choices []string, flagMatch bool, optionMatch bool)

func (*CmdClause) FullCommand added in v1.3.1

func (c *CmdClause) FullCommand() string

func (*CmdClause) Hidden

func (c *CmdClause) Hidden() *CmdClause

func (*CmdClause) Model

func (c *CmdClause) Model() *CmdModel

func (*CmdClause) PreAction

func (c *CmdClause) PreAction(action Action) *CmdClause

func (*CmdClause) Validate added in v1.3.3

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

Validate sets a validation function to run when parsing.

type CmdClauseValidator added in v1.3.3

type CmdClauseValidator func(*CmdClause) error

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
	FullCommand string
	Depth       int
	Hidden      bool
	Default     bool
	*FlagGroupModel
	*ArgGroupModel
	*CmdGroupModel
}

func (*CmdModel) String

func (c *CmdModel) String() string

type FlagClause

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

FlagClause is a fluid interface used to build flags.

func Flag

func Flag(name, help string) *FlagClause

Flag adds a new flag to the default parser.

func (*FlagClause) Action

func (f *FlagClause) Action(action Action) *FlagClause

Dispatch to the given function after the flag is parsed and validated.

func (*FlagClause) Bool

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

Bool makes this flag a boolean flag.

func (*FlagClause) BoolList

func (p *FlagClause) BoolList() (target *[]bool)

BoolList accumulates bool values into a slice.

func (*FlagClause) BoolListVar

func (p *FlagClause) BoolListVar(target *[]bool)

func (*FlagClause) BoolVar

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

func (*FlagClause) Bytes added in v1.2.0

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

Bytes parses numeric byte units. eg. 1.5KB

func (*FlagClause) BytesVar added in v1.2.0

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

BytesVar parses numeric byte units. eg. 1.5KB

func (*FlagClause) Counter

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

A Counter increments a number each time it is encountered.

func (*FlagClause) CounterVar

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

func (*FlagClause) Default

func (f *FlagClause) Default(values ...string) *FlagClause

Default values for this flag. They *must* be parseable by the value of the flag.

func (*FlagClause) Duration

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

Duration sets the parser to a time.Duration parser.

func (*FlagClause) DurationList

func (p *FlagClause) DurationList() (target *[]time.Duration)

DurationList accumulates time.Duration values into a slice.

func (*FlagClause) DurationListVar

func (p *FlagClause) DurationListVar(target *[]time.Duration)

func (*FlagClause) DurationVar

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

Duration sets the parser to a time.Duration parser.

func (*FlagClause) Enum added in v1.2.0

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

func (*FlagClause) EnumVar added in v1.2.0

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

func (*FlagClause) Enums added in v1.3.6

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

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

func (*FlagClause) EnumsVar added in v1.3.6

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

EnumVar allows a value from a set of options.

func (*FlagClause) Envar

func (f *FlagClause) Envar(name string) *FlagClause

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 (*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) ExistingDirs

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

ExistingDirs accumulates string values into a slice.

func (*FlagClause) ExistingDirsVar

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

func (*FlagClause) ExistingFile

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

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

func (*FlagClause) ExistingFileOrDir

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

ExistingFileOrDir sets the parser to one that requires and returns an existing file OR directory.

func (*FlagClause) ExistingFileOrDirVar

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

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

func (*FlagClause) ExistingFileVar

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

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

func (*FlagClause) ExistingFiles

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

ExistingFiles accumulates string values into a slice.

func (*FlagClause) ExistingFilesOrDirs

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

ExistingFilesOrDirs accumulates string values into a slice.

func (*FlagClause) ExistingFilesOrDirsVar

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

func (*FlagClause) ExistingFilesVar

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

func (*FlagClause) File

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

File returns an os.File against an existing file.

func (*FlagClause) FileVar

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

FileVar opens an existing file.

func (*FlagClause) Float

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

Float sets the parser to a float64 parser.

func (*FlagClause) Float32

func (p *FlagClause) Float32() (target *float32)

Float32 parses the next command-line value as float32.

func (*FlagClause) Float32List

func (p *FlagClause) Float32List() (target *[]float32)

Float32List accumulates float32 values into a slice.

func (*FlagClause) Float32ListVar

func (p *FlagClause) Float32ListVar(target *[]float32)

func (*FlagClause) Float32Var

func (p *FlagClause) Float32Var(target *float32)

func (*FlagClause) Float64

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

Float64 parses the next command-line value as float64.

func (*FlagClause) Float64List

func (p *FlagClause) Float64List() (target *[]float64)

Float64List accumulates float64 values into a slice.

func (*FlagClause) Float64ListVar

func (p *FlagClause) Float64ListVar(target *[]float64)

func (*FlagClause) Float64Var

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

func (*FlagClause) FloatVar

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

Float sets the parser to a float64 parser.

func (*FlagClause) GetEnvarValue

func (e *FlagClause) GetEnvarValue() string

func (*FlagClause) GetSplitEnvarValue

func (e *FlagClause) GetSplitEnvarValue() []string

func (*FlagClause) HasEnvarValue

func (e *FlagClause) HasEnvarValue() bool

func (*FlagClause) HexBytes

func (p *FlagClause) HexBytes() (target *[]byte)

Bytes as a hex string.

func (*FlagClause) HexBytesList

func (p *FlagClause) HexBytesList() (target *[][]byte)

HexBytesList accumulates []byte values into a slice.

func (*FlagClause) HexBytesListVar

func (p *FlagClause) HexBytesListVar(target *[][]byte)

func (*FlagClause) HexBytesVar

func (p *FlagClause) HexBytesVar(target *[]byte)

func (*FlagClause) Hidden added in v1.2.0

func (f *FlagClause) Hidden() *FlagClause

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

func (*FlagClause) HintAction

func (a *FlagClause) HintAction(action HintAction) *FlagClause

HintAction registers a HintAction (function) for the flag to provide completions

func (*FlagClause) HintOptions

func (a *FlagClause) HintOptions(options ...string) *FlagClause

HintOptions registers any number of options for the flag to provide completions

func (*FlagClause) IP

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

IP sets the parser to a net.IP parser.

func (*FlagClause) IPList

func (p *FlagClause) IPList() (target *[]net.IP)

IPList accumulates net.IP values into a slice.

func (*FlagClause) IPListVar

func (p *FlagClause) IPListVar(target *[]net.IP)

func (*FlagClause) IPVar

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

IP sets the parser to a net.IP parser.

func (*FlagClause) Int

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

Int parses the next command-line value as int.

func (*FlagClause) Int16

func (p *FlagClause) Int16() (target *int16)

Int16 parses the next command-line value as int16.

func (*FlagClause) Int16List

func (p *FlagClause) Int16List() (target *[]int16)

Int16List accumulates int16 values into a slice.

func (*FlagClause) Int16ListVar

func (p *FlagClause) Int16ListVar(target *[]int16)

func (*FlagClause) Int16Var

func (p *FlagClause) Int16Var(target *int16)

func (*FlagClause) Int32

func (p *FlagClause) Int32() (target *int32)

Int32 parses the next command-line value as int32.

func (*FlagClause) Int32List

func (p *FlagClause) Int32List() (target *[]int32)

Int32List accumulates int32 values into a slice.

func (*FlagClause) Int32ListVar

func (p *FlagClause) Int32ListVar(target *[]int32)

func (*FlagClause) Int32Var

func (p *FlagClause) Int32Var(target *int32)

func (*FlagClause) Int64

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

Int64 parses the next command-line value as int64.

func (*FlagClause) Int64List

func (p *FlagClause) Int64List() (target *[]int64)

Int64List accumulates int64 values into a slice.

func (*FlagClause) Int64ListVar

func (p *FlagClause) Int64ListVar(target *[]int64)

func (*FlagClause) Int64Var

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

func (*FlagClause) Int8

func (p *FlagClause) Int8() (target *int8)

Int8 parses the next command-line value as int8.

func (*FlagClause) Int8List

func (p *FlagClause) Int8List() (target *[]int8)

Int8List accumulates int8 values into a slice.

func (*FlagClause) Int8ListVar

func (p *FlagClause) Int8ListVar(target *[]int8)

func (*FlagClause) Int8Var

func (p *FlagClause) Int8Var(target *int8)

func (*FlagClause) IntVar

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

func (*FlagClause) Ints

func (p *FlagClause) Ints() (target *[]int)

Ints accumulates int values into a slice.

func (*FlagClause) IntsVar

func (p *FlagClause) IntsVar(target *[]int)

func (*FlagClause) Model

func (f *FlagClause) Model() *FlagModel

func (*FlagClause) NoEnvar

func (f *FlagClause) NoEnvar() *FlagClause

NoEnvar forces environment variable defaults to be disabled for this flag. Most useful in conjunction with app.DefaultEnvars().

func (*FlagClause) OpenFile added in v1.1.0

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 added in v1.1.0

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

OpenFileVar calls os.OpenFile(flag, perm)

func (*FlagClause) OverrideDefaultFromEnvar added in v0.3.0

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

DEPRECATED: Use Envar(name) instead.

func (*FlagClause) PlaceHolder added in v0.2.0

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) PreAction

func (f *FlagClause) PreAction(action Action) *FlagClause

func (*FlagClause) Regexp

func (p *FlagClause) Regexp() (target **regexp.Regexp)

Regexp parses the next command-line value as *regexp.Regexp.

func (*FlagClause) RegexpList

func (p *FlagClause) RegexpList() (target *[]*regexp.Regexp)

RegexpList accumulates *regexp.Regexp values into a slice.

func (*FlagClause) RegexpListVar

func (p *FlagClause) RegexpListVar(target *[]*regexp.Regexp)

func (*FlagClause) RegexpVar

func (p *FlagClause) RegexpVar(target **regexp.Regexp)

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) ResolvedIP

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

Resolve a hostname or IP to an IP.

func (*FlagClause) ResolvedIPList

func (p *FlagClause) ResolvedIPList() (target *[]net.IP)

ResolvedIPList accumulates net.IP values into a slice.

func (*FlagClause) ResolvedIPListVar

func (p *FlagClause) ResolvedIPListVar(target *[]net.IP)

func (*FlagClause) ResolvedIPVar

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

func (*FlagClause) SetValue

func (p *FlagClause) SetValue(value Value)

func (*FlagClause) Short

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

Short sets the short flag name.

func (*FlagClause) String

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

String parses the next command-line value as string.

func (*FlagClause) StringMap

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

StringMap provides key=value parsing into a map.

func (*FlagClause) StringMapVar

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

StringMap provides key=value parsing into a map.

func (*FlagClause) StringVar

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

func (*FlagClause) Strings

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

Strings accumulates string values into a slice.

func (*FlagClause) StringsVar

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

func (*FlagClause) TCP

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

TCP (host:port) address.

func (*FlagClause) TCPList

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

TCPList accumulates *net.TCPAddr values into a slice.

func (*FlagClause) TCPListVar

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

func (*FlagClause) TCPVar

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

TCPVar (host:port) address.

func (*FlagClause) URL

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

URL provides a valid, parsed url.URL.

func (*FlagClause) URLList

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

URLList provides a parsed list of url.URL values.

func (*FlagClause) URLListVar

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

URLListVar provides a parsed list of url.URL values.

func (*FlagClause) URLVar

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

URL provides a valid, parsed url.URL.

func (*FlagClause) Uint

func (p *FlagClause) Uint() (target *uint)

Uint parses the next command-line value as uint.

func (*FlagClause) Uint16

func (p *FlagClause) Uint16() (target *uint16)

Uint16 parses the next command-line value as uint16.

func (*FlagClause) Uint16List

func (p *FlagClause) Uint16List() (target *[]uint16)

Uint16List accumulates uint16 values into a slice.

func (*FlagClause) Uint16ListVar

func (p *FlagClause) Uint16ListVar(target *[]uint16)

func (*FlagClause) Uint16Var

func (p *FlagClause) Uint16Var(target *uint16)

func (*FlagClause) Uint32

func (p *FlagClause) Uint32() (target *uint32)

Uint32 parses the next command-line value as uint32.

func (*FlagClause) Uint32List

func (p *FlagClause) Uint32List() (target *[]uint32)

Uint32List accumulates uint32 values into a slice.

func (*FlagClause) Uint32ListVar

func (p *FlagClause) Uint32ListVar(target *[]uint32)

func (*FlagClause) Uint32Var

func (p *FlagClause) Uint32Var(target *uint32)

func (*FlagClause) Uint64

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

Uint64 parses the next command-line value as uint64.

func (*FlagClause) Uint64List

func (p *FlagClause) Uint64List() (target *[]uint64)

Uint64List accumulates uint64 values into a slice.

func (*FlagClause) Uint64ListVar

func (p *FlagClause) Uint64ListVar(target *[]uint64)

func (*FlagClause) Uint64Var

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

func (*FlagClause) Uint8

func (p *FlagClause) Uint8() (target *uint8)

Uint8 parses the next command-line value as uint8.

func (*FlagClause) Uint8List

func (p *FlagClause) Uint8List() (target *[]uint8)

Uint8List accumulates uint8 values into a slice.

func (*FlagClause) Uint8ListVar

func (p *FlagClause) Uint8ListVar(target *[]uint8)

func (*FlagClause) Uint8Var

func (p *FlagClause) Uint8Var(target *uint8)

func (*FlagClause) UintVar

func (p *FlagClause) UintVar(target *uint)

func (*FlagClause) Uints

func (p *FlagClause) Uints() (target *[]uint)

Uints accumulates uint values into a slice.

func (*FlagClause) UintsVar

func (p *FlagClause) UintsVar(target *[]uint)

type FlagGroupModel

type FlagGroupModel struct {
	Flags []*FlagModel
}

func (*FlagGroupModel) FlagSummary

func (f *FlagGroupModel) FlagSummary() string

type FlagModel

type FlagModel struct {
	Name        string
	Help        string
	Short       rune
	Default     []string
	Envar       string
	PlaceHolder string
	Required    bool
	Hidden      bool
	Value       Value
}

func (*FlagModel) FormatPlaceHolder

func (f *FlagModel) FormatPlaceHolder() string

func (*FlagModel) IsBoolFlag

func (f *FlagModel) IsBoolFlag() bool

func (*FlagModel) String

func (f *FlagModel) String() 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 ParseContext added in v1.3.0

type ParseContext struct {
	SelectedCommand *CmdClause

	// Flags, arguments and commands encountered and collected during parse.
	Elements []*ParseElement
	// 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) EOL

func (p *ParseContext) EOL() bool

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) Next added in v1.3.0

func (p *ParseContext) Next() *Token

Next token in the parse context.

func (*ParseContext) Peek added in v1.3.0

func (p *ParseContext) Peek() *Token

func (*ParseContext) Push

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

func (*ParseContext) String added in v1.3.2

func (p *ParseContext) String() string

type ParseElement

type ParseElement struct {
	// Clause is either *CmdClause, *ArgClause or *FlagClause.
	Clause interface{}
	// Value is corresponding value for an ArgClause or FlagClause (if any).
	Value *string
}

A union of possible elements in a parse stack.

type Settings

type Settings interface {
	SetValue(value Value)
}

type Token added in v1.3.0

type Token struct {
	Index int
	Type  TokenType
	Value string
}

func (*Token) Equal

func (t *Token) Equal(o *Token) bool

func (*Token) IsEOF added in v1.3.0

func (t *Token) IsEOF() bool

func (*Token) IsFlag added in v1.3.0

func (t *Token) IsFlag() bool

func (*Token) String added in v1.3.0

func (t *Token) String() string

type TokenType added in v1.3.0

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

Token types.

func (TokenType) String

func (t TokenType) String() string

type Value

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.

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 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)
	}
}
Output:

Directories

Path Synopsis
_examples
curl
A curl-like HTTP command-line client.
A curl-like HTTP command-line client.
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL