kingpin

package module
v3.0.0-...-95d230a Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2019 License: MIT Imports: 26 Imported by: 136

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).
  • Negatable boolean flags (--[no-]flag).

User-visible changes between v2 and v3

Some flag types have been removed.

Some flag types had unintended side-effects, or poor usability. For example, flags that created/opened files could result in file-descriptor leaks. To avoid confusion these have been removed.

Semantics around boolean flags have changed.

Bool() now creates a non-negatable flag.

Use NegatableBool() to add a boolean flag that supports both --flag and --no-flag. This will be displayed in the help.

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", *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().

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."))
Configuration files and other external sources of flag/argument values

Kingpin v3 now supports custom value resolvers for flags and arguments. This is used internally to resolve default values and environment variables, but applications can define their own resolvers to load flags from configuration files, or elsewhere.

Included is a JSONResolver that loads values from a JSON file, including multi-value flags.

Struct tag interpolation

Kingpin v3 now supports defining flags, arguments and commands via struct reflection. If desired, this can (almost) completely replace the fluent-style interface.

The name of the flag will default to the CamelCase name transformed to camel- case. This can be overridden with the "long" tag.

All basic Go types are supported including floats, ints, strings, time.Duration, and slices of same.

For compatibility, also supports the tags used by https://github.com/jessevdk/go-flags

type MyFlags struct {
  Arg string `arg:"true" help:"An argument"`
  Debug bool `help:"Enable debug mode."`
  URL string `help:"URL to connect to." default:"localhost:80"`

  Login struct {
    Name string `help:"Username to authenticate with." args:"true"`
  } `help:"Login to server."`
}

flags := &MyFlags{}
kingpin.Struct(flags)

Supported struct tags are:

Tag Description
help Help text.
placeholder Placeholder text.
default Default value.
short Short name, if flag.
long Long name, for overriding field name.
required If present, flag/arg is required.
hidden If present, flag/arg/command is hidden.
enum For enums, a comma separated list of cases.
arg If true, field is an argument.
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(args []string) []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.GetFlag("help").Short('h')

Custom help

Kingpin supports templatised help using the text/template library.

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, 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.

Adding a new help command

It is often useful to add extra help formats, such as man pages, etc. Here's how you'd add a --help-man flag:

kingpin.Flag("help-man", "Generate man page.").
  UsageActionTemplate(kingpin.ManPageTemplate).
  Bool()
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.v1"

var (
  debug    = kingpin.Flag("debug", "enable debug mode").Default("false").Bool()
  serverIP = kingpin.Flag("server", "server address").Default("127.0.0.1").IP()

  register     = kingpin.Command("register", "Register a new user.")
  registerNick = register.Arg("nick", "nickname for user").Required().String()
  registerName = register.Arg("name", "name of user").Required().String()

  post        = kingpin.Command("post", "Post a message to a channel.")
  postImage   = post.Flag("image", "image to post").ExistingFile()
  postChannel = post.Arg("channel", "channel to post to").Required().String()
  postText    = post.Arg("text", "text to post").String()
)

func main() {
  switch kingpin.Parse() {
  // Register user
  case "register":
    println(*registerNick)

  // Post message
  case "post":
    if *postImage != nil {
    }
    if *postText != "" {
    }
  }
}

nolint: golint

Index

Examples

Constants

This section is empty.

Variables

View Source
var BashCompletionTemplate = `` /* 327-byte string literal not displayed */
View Source
var (
	// CommandLine is the default Kingpin parser.
	CommandLine = New(filepath.Base(os.Args[0]), "")
)
View Source
var CompactUsageTemplate = `` /* 1320-byte string literal not displayed */

CompactUsageTemplate is a template with compactly formatted commands for large command structures.

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

DefaultUsageTemplate is the default usage template.

View Source
var ManPageTemplate = `` /* 890-byte string literal not displayed */
View Source
var T = initI18N()

T is a translation function.

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

Functions

func Errorf

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

Errorf prints an error message to stderr.

func ExpandArgsFromFile

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 JSONConfigClause

func JSONConfigClause(app *Application, clause *Clause) *string

JSONConfigClause installs a JSONResolver into app that will be loaded by invocation of clause (typically a flag).

eg.

JSONConfigClause(app, app.Flag("config", "Load configuration.").Required())

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

func SetLanguage(lang string, others ...string) error

SetLanguage sets the language for Kingpin.

func TError

func TError(msg string, args ...interface{}) error

TError is an error that translates itself.

It has the same signature and usage as T().

func Usage

func Usage()

Usage prints usage to stderr.

Types

type AccumulatorOption

type AccumulatorOption func(a *accumulatorOptions)

AccumulatorOption are used to modify the behaviour of values that accumulate into slices, maps, etc.

eg. Separator(',')

func Separator

func Separator(separator string) AccumulatorOption

Separator configures an accumulating value to split on this value.

type Action

type Action func(element *ParseElement, context *ParseContext) error

Action callback triggered during parsing.

"element" is the flag, argument or command associated with the callback. It contains the Clause and string value, if any.

"context" contains the full parse context, including all other elements that have been parsed.

type Application

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

func New(name, help string) *Application

New creates a new Kingpin application instance.

func Struct

func Struct(v interface{}) *Application

Struct creates a command-line from a struct.

func UsageTemplate

func UsageTemplate(template string) *Application

UsageTemplate associates a template with a flag. The flag must be a Bool() and must already be defined.

func Version

func Version(version string) *Application

Version adds a flag for displaying the application version number.

func (*Application) Action

func (a *Application) Action(action Action) *Application

Action is an application-wide callback. It is used in two situations: first, with a nil "element" parameter when parsing is complete, and second whenever a command, argument or flag is encountered.

func (*Application) Author

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

Author sets the author name for usage templates.

func (*Application) CmdCompletion

func (c *Application) CmdCompletion(context *ParseContext) []string

CmdCompletion returns completion options for arguments, if that's where parsing left off, or commands if there aren't any unsatisfied args.

func (*Application) Command

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

Command adds a new top-level command.

func (*Application) DefaultEnvars

func (a *Application) DefaultEnvars() *Application

DefaultEnvars configures all flags (that do not already have an associated envar) to use a default environment variable in the form "<app>_<flag>".

For example, if the application is named "foo" and a flag is named "bar- waz" the environment variable: "FOO_BAR_WAZ".

func (*Application) EnvarSeparator

func (a *Application) EnvarSeparator(sep string) *Application

EnvarSeparator sets the string that is used for separating values in environment variables.

This defaults to the current OS's path list separator (typically : or ;).

func (*Application) Errorf

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

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

func (*Application) FatalIfError

func (a *Application) FatalIfError(err error, format string, args ...interface{})

FatalIfError prints an error and exits if err is not nil. The error is printed with the given formatted string, if any.

func (*Application) FatalUsage

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

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

func (*Application) FatalUsageContext

func (a *Application) FatalUsageContext(context *ParseContext, format string, args ...interface{})

FatalUsageContext writes a printf formatted error message to w, then usage information for the given ParseContext, before exiting.

func (*Application) Fatalf

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

Fatalf writes a formatted error to w then terminates with exit status 1.

func (*Application) FlagCompletion

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

PreAction adds a callback action to be executed after flag values are parsed but before any other processing, such as help, completion, etc.

It is called in two situations: first, with a nil "element" parameter, and second, whenever a command, argument or flag is encountered.

func (*Application) Resolver

func (a *Application) Resolver(resolvers ...Resolver) *Application

Resolver adds an ordered set of flag/argument resolvers.

Resolvers provide default flag/argument values, from environment variables, configuration files, etc. Multiple resolvers may be added, and they are processed in order.

The last Resolver to return a value always wins. Values returned from resolvers are not cumulative.

func (*Application) Struct

func (a *Application) Struct(v interface{}) error

Struct allows applications to define flags with struct tags.

Supported struct tags are: help, placeholder, default, short, long, required, hidden, env, enum, and arg.

The name of the flag will default to the CamelCase name transformed to camel-case. This can be overridden with the "long" tag.

All basic Go types are supported including floats, ints, strings, time.Duration, and slices of same.

For compatibility, also supports the tags used by https://github.com/jessevdk/go-flags

func (*Application) Terminate

func (a *Application) Terminate(terminate func(int)) *Application

Terminate specifies the termination handler. Defaults to os.Exit(status). If nil is passed, a no-op function will be used.

func (*Application) Usage

func (a *Application) Usage(args []string)

Usage writes application usage to Writer. It parses args to determine appropriate help context, such as which command to show help for.

func (*Application) UsageContext

func (a *Application) UsageContext(context *UsageContext) *Application

UsageContext specifies the UsageContext to use when displaying usage information via --help.

func (*Application) UsageForContext

func (a *Application) UsageForContext(context *ParseContext) error

UsageForContext displays usage information from a ParseContext (obtained from Application.ParseContext() or Action(f) callbacks).

func (*Application) UsageForContextWithTemplate

func (a *Application) UsageForContextWithTemplate(usageContext *UsageContext, parseContext *ParseContext) error

UsageForContextWithTemplate is for fine-grained control over usage messages. You generally don't need to use this.

func (*Application) UsageTemplate

func (a *Application) UsageTemplate(template string) *Application

UsageTemplate specifies the text template to use when displaying usage information via --help. The default is DefaultUsageTemplate.

func (*Application) Version

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

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

func (*Application) Writers

func (a *Application) Writers(out, err io.Writer) *Application

Writers specifies the writers to use for usage and errors. Defaults to os.Stderr.

type ApplicationModel

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

func (*ApplicationModel) AppSummary

func (a *ApplicationModel) AppSummary() string

func (*ApplicationModel) FindModelForCommand

func (a *ApplicationModel) FindModelForCommand(cmd *CmdClause) *CmdModel

type ArgGroupModel

type ArgGroupModel struct {
	Args []*ClauseModel
}

func (*ArgGroupModel) ArgSummary

func (a *ArgGroupModel) ArgSummary() string

type BoolFlag

type BoolFlag interface {
	// Specify if the flag is negatable (ie. supports both --no-<name> and --name).
	BoolFlagIsNegatable() bool
}

BoolFlag is an optional interface to specify that a flag is a boolean flag.

type Clause

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

A Clause represents a flag or an argument passed by the user.

func Arg

func Arg(name, help string) *Clause

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

func Flag

func Flag(name, help string) *Clause

Flag adds a new flag to the default parser.

func NewClause

func NewClause(name, help string) *Clause

func (*Clause) Action

func (c *Clause) Action(action Action) *Clause

Action adds a callback action to be executed after the command line is parsed and any non-terminating builtin actions have completed (eg. help, completion, etc.).

func (*Clause) Bool

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

Bool parses the next command-line value as bool.

func (*Clause) BoolList

func (p *Clause) BoolList(options ...AccumulatorOption) (target *[]bool)

BoolList accumulates bool values into a slice.

func (*Clause) BoolListVar

func (p *Clause) BoolListVar(target *[]bool, options ...AccumulatorOption)

func (*Clause) BoolVar

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

func (*Clause) Bytes

func (c *Clause) Bytes() (target *units.Base2Bytes)

Bytes parses numeric byte units. eg. 1.5KB

func (*Clause) BytesVar

func (c *Clause) BytesVar(target *units.Base2Bytes)

BytesVar parses numeric byte units. eg. 1.5KB

func (*Clause) Counter

func (c *Clause) Counter() (target *int)

Counter increments a number each time it is encountered.

func (*Clause) CounterVar

func (c *Clause) CounterVar(target *int)

func (*Clause) Default

func (c *Clause) Default(values ...string) *Clause

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

func (*Clause) Duration

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

Time duration.

func (*Clause) DurationList

func (p *Clause) DurationList(options ...AccumulatorOption) (target *[]time.Duration)

DurationList accumulates time.Duration values into a slice.

func (*Clause) DurationListVar

func (p *Clause) DurationListVar(target *[]time.Duration, options ...AccumulatorOption)

func (*Clause) DurationVar

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

func (*Clause) Enum

func (c *Clause) Enum(options ...string) (target *string)

Enum allows a value from a set of options.

func (*Clause) EnumVar

func (c *Clause) EnumVar(target *string, options ...string)

EnumVar allows a value from a set of options.

func (*Clause) Enums

func (c *Clause) Enums(options ...string) (target *[]string)

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

func (*Clause) EnumsVar

func (c *Clause) EnumsVar(target *[]string, options ...string)

EnumsVar allows a value from a set of options.

func (*Clause) Envar

func (c *Clause) Envar(name string) *Clause

Envar overrides the default value(s) for a flag from an environment variable, if it is set. Several default values can be provided by using new lines to separate them.

func (*Clause) ExistingDir

func (c *Clause) ExistingDir() (target *string)

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

func (*Clause) ExistingDirVar

func (c *Clause) ExistingDirVar(target *string)

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

func (*Clause) ExistingDirs

func (p *Clause) ExistingDirs(options ...AccumulatorOption) (target *[]string)

ExistingDirs accumulates string values into a slice.

func (*Clause) ExistingDirsVar

func (p *Clause) ExistingDirsVar(target *[]string, options ...AccumulatorOption)

func (*Clause) ExistingFile

func (c *Clause) ExistingFile() (target *string)

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

func (*Clause) ExistingFileOrDir

func (c *Clause) ExistingFileOrDir() (target *string)

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

func (*Clause) ExistingFileOrDirVar

func (c *Clause) ExistingFileOrDirVar(target *string)

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

func (*Clause) ExistingFileVar

func (c *Clause) ExistingFileVar(target *string)

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

func (*Clause) ExistingFiles

func (p *Clause) ExistingFiles(options ...AccumulatorOption) (target *[]string)

ExistingFiles accumulates string values into a slice.

func (*Clause) ExistingFilesOrDirs

func (p *Clause) ExistingFilesOrDirs(options ...AccumulatorOption) (target *[]string)

ExistingFilesOrDirs accumulates string values into a slice.

func (*Clause) ExistingFilesOrDirsVar

func (p *Clause) ExistingFilesOrDirsVar(target *[]string, options ...AccumulatorOption)

func (*Clause) ExistingFilesVar

func (p *Clause) ExistingFilesVar(target *[]string, options ...AccumulatorOption)

func (*Clause) Float

func (c *Clause) Float() (target *float64)

Float sets the parser to a float64 parser.

func (*Clause) Float32

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

Float32 parses the next command-line value as float32.

func (*Clause) Float32List

func (p *Clause) Float32List(options ...AccumulatorOption) (target *[]float32)

Float32List accumulates float32 values into a slice.

func (*Clause) Float32ListVar

func (p *Clause) Float32ListVar(target *[]float32, options ...AccumulatorOption)

func (*Clause) Float32Var

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

func (*Clause) Float64

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

Float64 parses the next command-line value as float64.

func (*Clause) Float64List

func (p *Clause) Float64List(options ...AccumulatorOption) (target *[]float64)

Float64List accumulates float64 values into a slice.

func (*Clause) Float64ListVar

func (p *Clause) Float64ListVar(target *[]float64, options ...AccumulatorOption)

func (*Clause) Float64Var

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

func (*Clause) FloatVar

func (c *Clause) FloatVar(target *float64)

Float sets the parser to a float64 parser.

func (*Clause) Help

func (c *Clause) Help(help string) *Clause

func (*Clause) HexBytes

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

Bytes as a hex string.

func (*Clause) HexBytesList

func (p *Clause) HexBytesList(options ...AccumulatorOption) (target *[][]byte)

HexBytesList accumulates []byte values into a slice.

func (*Clause) HexBytesListVar

func (p *Clause) HexBytesListVar(target *[][]byte, options ...AccumulatorOption)

func (*Clause) HexBytesVar

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

func (*Clause) Hidden

func (c *Clause) Hidden() *Clause

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

func (*Clause) HintAction

func (c *Clause) HintAction(action HintAction) *Clause

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

func (*Clause) HintOptions

func (c *Clause) HintOptions(options ...string) *Clause

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

func (*Clause) IP

func (c *Clause) IP() (target *net.IP)

IP provides a validated parsed *net.IP value.

func (*Clause) IPList

func (p *Clause) IPList(options ...AccumulatorOption) (target *[]net.IP)

IPList accumulates net.IP values into a slice.

func (*Clause) IPListVar

func (p *Clause) IPListVar(target *[]net.IP, options ...AccumulatorOption)

func (*Clause) IPVar

func (c *Clause) IPVar(target *net.IP)

IPVar provides a validated parsed *net.IP value.

func (*Clause) Int

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

Int parses the next command-line value as int.

func (*Clause) Int16

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

Int16 parses the next command-line value as int16.

func (*Clause) Int16List

func (p *Clause) Int16List(options ...AccumulatorOption) (target *[]int16)

Int16List accumulates int16 values into a slice.

func (*Clause) Int16ListVar

func (p *Clause) Int16ListVar(target *[]int16, options ...AccumulatorOption)

func (*Clause) Int16Var

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

func (*Clause) Int32

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

Int32 parses the next command-line value as int32.

func (*Clause) Int32List

func (p *Clause) Int32List(options ...AccumulatorOption) (target *[]int32)

Int32List accumulates int32 values into a slice.

func (*Clause) Int32ListVar

func (p *Clause) Int32ListVar(target *[]int32, options ...AccumulatorOption)

func (*Clause) Int32Var

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

func (*Clause) Int64

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

Int64 parses the next command-line value as int64.

func (*Clause) Int64List

func (p *Clause) Int64List(options ...AccumulatorOption) (target *[]int64)

Int64List accumulates int64 values into a slice.

func (*Clause) Int64ListVar

func (p *Clause) Int64ListVar(target *[]int64, options ...AccumulatorOption)

func (*Clause) Int64Var

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

func (*Clause) Int8

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

Int8 parses the next command-line value as int8.

func (*Clause) Int8List

func (p *Clause) Int8List(options ...AccumulatorOption) (target *[]int8)

Int8List accumulates int8 values into a slice.

func (*Clause) Int8ListVar

func (p *Clause) Int8ListVar(target *[]int8, options ...AccumulatorOption)

func (*Clause) Int8Var

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

func (*Clause) IntVar

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

func (*Clause) Ints

func (p *Clause) Ints(options ...AccumulatorOption) (target *[]int)

Ints accumulates int values into a slice.

func (*Clause) IntsVar

func (p *Clause) IntsVar(target *[]int, options ...AccumulatorOption)

func (*Clause) Model

func (f *Clause) Model() *ClauseModel

func (*Clause) NegatableBool

func (p *Clause) NegatableBool() (target *bool)

NegatableBool parses the next command-line value as bool.

func (*Clause) NegatableBoolList

func (p *Clause) NegatableBoolList(options ...AccumulatorOption) (target *[]bool)

NegatableBoolList accumulates bool values into a slice.

func (*Clause) NegatableBoolListVar

func (p *Clause) NegatableBoolListVar(target *[]bool, options ...AccumulatorOption)

func (*Clause) NegatableBoolVar

func (p *Clause) NegatableBoolVar(target *bool)

func (*Clause) NoEnvar

func (c *Clause) NoEnvar() *Clause

NoEnvar forces environment variable defaults to be disabled for this flag. Most useful in conjunction with PrefixedEnvarResolver.

func (*Clause) PlaceHolder

func (c *Clause) PlaceHolder(placeholder string) *Clause

PlaceHolder sets the place-holder string used for flag values in the help. The default behaviour is to use the value provided by Default() if provided, then fall back on the capitalized flag name.

func (*Clause) PreAction

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

PreAction adds a callback action to be executed after flag values are parsed but before any other processing, such as help, completion, etc.

func (*Clause) Regexp

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

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

func (*Clause) RegexpList

func (p *Clause) RegexpList(options ...AccumulatorOption) (target *[]*regexp.Regexp)

RegexpList accumulates *regexp.Regexp values into a slice.

func (*Clause) RegexpListVar

func (p *Clause) RegexpListVar(target *[]*regexp.Regexp, options ...AccumulatorOption)

func (*Clause) RegexpVar

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

func (*Clause) Required

func (c *Clause) Required() *Clause

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

func (*Clause) SetValue

func (c *Clause) SetValue(value Value)

func (*Clause) Short

func (c *Clause) Short(name rune) *Clause

Short sets the short flag name.

func (*Clause) String

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

String parses the next command-line value as string.

func (*Clause) StringMap

func (c *Clause) StringMap(options ...AccumulatorOption) (target *map[string]string)

StringMap provides key=value parsing into a map.

func (*Clause) StringMapVar

func (c *Clause) StringMapVar(target *map[string]string, options ...AccumulatorOption)

StringMap provides key=value parsing into a map.

func (*Clause) StringVar

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

func (*Clause) Strings

func (p *Clause) Strings(options ...AccumulatorOption) (target *[]string)

Strings accumulates string values into a slice.

func (*Clause) StringsVar

func (p *Clause) StringsVar(target *[]string, options ...AccumulatorOption)

func (*Clause) Time

func (p *Clause) Time(format string) (target *time.Time)

Time parses a time.Time.

Format is the layout as specified at https://golang.org/pkg/time/#Parse

func (*Clause) TimeList

func (p *Clause) TimeList(format string, options ...AccumulatorOption) (target *[]time.Time)

TimeList accumulates time.Time values into a slice.

func (*Clause) TimeListVar

func (p *Clause) TimeListVar(format string, target *[]time.Time, options ...AccumulatorOption)

func (*Clause) TimeVar

func (p *Clause) TimeVar(format string, target *time.Time)

func (*Clause) URL

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

URL parses the next command-line value as *url.URL.

func (*Clause) URLList

func (p *Clause) URLList(options ...AccumulatorOption) (target *[]*url.URL)

URLList accumulates *url.URL values into a slice.

func (*Clause) URLListVar

func (p *Clause) URLListVar(target *[]*url.URL, options ...AccumulatorOption)

func (*Clause) URLVar

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

func (*Clause) Uint

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

Uint parses the next command-line value as uint.

func (*Clause) Uint16

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

Uint16 parses the next command-line value as uint16.

func (*Clause) Uint16List

func (p *Clause) Uint16List(options ...AccumulatorOption) (target *[]uint16)

Uint16List accumulates uint16 values into a slice.

func (*Clause) Uint16ListVar

func (p *Clause) Uint16ListVar(target *[]uint16, options ...AccumulatorOption)

func (*Clause) Uint16Var

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

func (*Clause) Uint32

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

Uint32 parses the next command-line value as uint32.

func (*Clause) Uint32List

func (p *Clause) Uint32List(options ...AccumulatorOption) (target *[]uint32)

Uint32List accumulates uint32 values into a slice.

func (*Clause) Uint32ListVar

func (p *Clause) Uint32ListVar(target *[]uint32, options ...AccumulatorOption)

func (*Clause) Uint32Var

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

func (*Clause) Uint64

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

Uint64 parses the next command-line value as uint64.

func (*Clause) Uint64List

func (p *Clause) Uint64List(options ...AccumulatorOption) (target *[]uint64)

Uint64List accumulates uint64 values into a slice.

func (*Clause) Uint64ListVar

func (p *Clause) Uint64ListVar(target *[]uint64, options ...AccumulatorOption)

func (*Clause) Uint64Var

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

func (*Clause) Uint8

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

Uint8 parses the next command-line value as uint8.

func (*Clause) Uint8List

func (p *Clause) Uint8List(options ...AccumulatorOption) (target *[]uint8)

Uint8List accumulates uint8 values into a slice.

func (*Clause) Uint8ListVar

func (p *Clause) Uint8ListVar(target *[]uint8, options ...AccumulatorOption)

func (*Clause) Uint8Var

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

func (*Clause) UintVar

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

func (*Clause) Uints

func (p *Clause) Uints(options ...AccumulatorOption) (target *[]uint)

Uints accumulates uint values into a slice.

func (*Clause) UintsVar

func (p *Clause) UintsVar(target *[]uint, options ...AccumulatorOption)

func (*Clause) UsageAction

func (c *Clause) UsageAction(context *UsageContext) *Clause

UsageAction adds a PreAction() that will display the given UsageContext.

func (*Clause) UsageActionTemplate

func (c *Clause) UsageActionTemplate(template string) *Clause

type ClauseModel

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

func (*ClauseModel) FormatPlaceHolder

func (c *ClauseModel) FormatPlaceHolder() string

func (*ClauseModel) IsBoolFlag

func (c *ClauseModel) IsBoolFlag() bool

func (*ClauseModel) IsNegatable

func (c *ClauseModel) IsNegatable() bool

func (*ClauseModel) String

func (c *ClauseModel) String() string

type CmdClause

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

A CmdClause is a single top-level command. It encapsulates a set of flags and either subcommands or positional arguments.

func 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

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

func (c *CmdClause) FullCommand() string

FullCommand returns the fully qualified "path" to this command, including interspersed argument placeholders. Does not include trailing argument placeholders.

eg. "signup <username> <email>"

func (*CmdClause) Hidden

func (c *CmdClause) Hidden() *CmdClause

func (*CmdClause) Model

func (c *CmdClause) Model(parent *CmdModel) *CmdModel

func (*CmdClause) OptionalSubcommands

func (c *CmdClause) OptionalSubcommands() *CmdClause

OptionalSubcommands makes subcommands optional

func (*CmdClause) PreAction

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

func (*CmdClause) Struct

func (c *CmdClause) Struct(v interface{}) error

Struct allows applications to define flags with struct tags.

Supported struct tags are: help, placeholder, default, short, long, required, hidden, env, enum, and arg.

The name of the flag will default to the CamelCase name transformed to camel-case. This can be overridden with the "long" tag.

All basic Go types are supported including floats, ints, strings, time.Duration, and slices of same.

For compatibility, also supports the tags used by https://github.com/jessevdk/go-flags

func (*CmdClause) Validate

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

Validate sets a validation function to run when parsing.

type CmdClauseValidator

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
	Depth               int
	Hidden              bool
	Default             bool
	OptionalSubcommands bool
	Parent              *CmdModel
	*FlagGroupModel
	*ArgGroupModel
	*CmdGroupModel
}

func (*CmdModel) CmdSummary

func (c *CmdModel) CmdSummary() string

func (*CmdModel) FullCommand

func (c *CmdModel) FullCommand() string

FullCommand is the command path to this node, excluding positional arguments and flags.

func (*CmdModel) String

func (c *CmdModel) String() string

type FlagGroupModel

type FlagGroupModel struct {
	Flags []*ClauseModel
}

func (*FlagGroupModel) FlagByName

func (f *FlagGroupModel) FlagByName(name string) *ClauseModel

func (*FlagGroupModel) FlagSummary

func (f *FlagGroupModel) FlagSummary() string

type Getter

type Getter interface {
	Value
	Get() interface{}
}

Getter is an interface that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

type HintAction

type HintAction func() []string

HintAction is a function type who is expected to return a slice of possible command line arguments.

type OneOfClause

type OneOfClause struct {
	Flag *Clause
	Arg  *Clause
	Cmd  *CmdClause
}

type ParseContext

type ParseContext struct {
	Application     *Application // May be nil in tests.
	SelectedCommand *CmdClause

	// Flags, arguments and commands encountered and collected during parse.
	Elements ParseElements
	// contains filtered or unexported fields
}

ParseContext holds the current context of the parser. When passed to Action() callbacks Elements will be fully populated with *FlagClause, *ArgClause and *CmdClause values and their corresponding arguments (if any).

func (*ParseContext) Args

func (p *ParseContext) Args() []*Clause

func (*ParseContext) CombinedFlagsAndArgs

func (p *ParseContext) CombinedFlagsAndArgs() []*Clause

func (*ParseContext) EOL

func (p *ParseContext) EOL() bool

func (*ParseContext) Flags

func (p *ParseContext) Flags() []*Clause

func (*ParseContext) HasTrailingArgs

func (p *ParseContext) HasTrailingArgs() bool

HasTrailingArgs returns true if there are unparsed command-line arguments. This can occur if the parser can not match remaining arguments.

func (*ParseContext) LastCmd

func (p *ParseContext) LastCmd(element *ParseElement) bool

LastCmd returns true if the element is the last (sub)command being evaluated.

func (*ParseContext) Next

func (p *ParseContext) Next() *Token

Next token in the parse context.

func (*ParseContext) Peek

func (p *ParseContext) Peek() *Token

func (*ParseContext) Push

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

func (*ParseContext) String

func (p *ParseContext) String() string

type ParseElement

type ParseElement struct {
	// Clause associated with this element. Exactly one of these will be present.
	OneOf OneOfClause
	// Value is corresponding value for an argument or flag. For commands this value will be nil.
	Value *string
}

A ParseElement represents the parsers view of each element in the command-line argument slice.

type ParseElements

type ParseElements []*ParseElement

ParseElements represents each element in the command-line argument slice.

func (ParseElements) ArgMap

func (p ParseElements) ArgMap() map[string]*ParseElement

ArgMap collects all parsed positional arguments into a map keyed by long name.

func (ParseElements) FlagMap

func (p ParseElements) FlagMap() map[string]*ParseElement

FlagMap collects all parsed flags into a map keyed by long name.

type Resolver

type Resolver interface {
	// Resolve clause in the given parse context.
	//
	// A nil slice should be returned if the clause can not be resolved.
	Resolve(clause *ClauseModel, context *ParseContext) ([]string, error)
}

A Resolver retrieves flag/arg values from an external source, such as a configuration file or environment variables.

func DontResolve

func DontResolve(resolver Resolver, keys ...string) Resolver

DontResolve returns a Resolver that will never return values for the given keys, even if provided.

func JSONResolver

func JSONResolver(r io.Reader) (Resolver, error)

JSONResolver returns a Resolver that retrieves values from a JSON source.

func MapResolver

func MapResolver(values map[string][]string) Resolver

MapResolver resolves values from a static map.

func PrefixedEnvarResolver

func PrefixedEnvarResolver(prefix, separator string) Resolver

PrefixedEnvarResolver resolves any flag/argument via environment variables.

"prefix" is the common-prefix for the environment variables. "separator", is the character used to separate multiple values within a single envar (eg. ";")

With a prefix of APP_, flags in the form --some-flag will be transformed to APP_SOME_FLAG.

func RenamingResolver

func RenamingResolver(resolver Resolver, rename func(string) string) Resolver

RenamingResolver creates a resolver for remapping names for a child resolver.

This is useful if your configuration file uses a naming convention that does not map directly to flag names.

type ResolverFunc

type ResolverFunc func(clause *ClauseModel, context *ParseContext) ([]string, error)

ResolverFunc is a function that is also a Resolver.

func (ResolverFunc) Resolve

func (r ResolverFunc) Resolve(clause *ClauseModel, context *ParseContext) ([]string, error)

type Token

type Token struct {
	Index int
	Type  TokenType
	Value string
}

func (*Token) Equal

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

func (*Token) IsEOF

func (t *Token) IsEOF() bool

func (*Token) IsFlag

func (t *Token) IsFlag() bool

func (*Token) String

func (t *Token) String() string

type TokenType

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

Token types.

func (TokenType) String

func (t TokenType) String() string

type UsageContext

type UsageContext struct {
	// The text/template body to use.
	Template string
	// Indentation multiplier (defaults to 2 of omitted).
	Indent int
	// Width of wrap. Defaults wraps to the terminal.
	Width int
	// Funcs available in the template.
	Funcs template.FuncMap
	// Vars available in the template.
	Vars map[string]interface{}
}

UsageContext contains all of the context used to render a usage message.

type V

type V map[string]interface{}

V is a convenience alias for translation function variables. eg. T("Something {{.Arg0}}", V{"Arg0": "moo"})

type Value

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 *Clause) (target *http.Header) {
	target = new(http.Header)
	s.SetValue((*HTTPHeaderValue)(target))
	return
}

// This example ilustrates how to define custom parsers. HTTPHeader
// cumulatively parses each encountered --header flag into a http.Header struct.
func main() {
	var (
		curl    = New("curl", "transfer a URL")
		headers = HTTPHeader(curl.Flag("headers", "Add HTTP headers to the request.").Short('H').PlaceHolder("HEADER:VALUE"))
	)

	curl.Parse([]string{"-H Content-Type:application/octet-stream"})
	for key, value := range *headers {
		fmt.Printf("%s = %s\n", key, value)
	}
}
Output:

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