kingpin

package
v0.0.0-...-85711f0 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2021 License: Apache-2.0, MIT Imports: 24 Imported by: 0

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

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 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 Action

type Action func(app *Application, 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 the string value.

"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) 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 is an application-wide callback. It is in two situations: first, with a nil "element" parameter, and second, whenever a command, argument or flag is encountered.

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

Writer specifies the writer 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 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

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() (target *[]bool)

BoolList accumulates bool values into a slice.

func (*Clause) BoolListVar

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

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)

A 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() (target *[]time.Duration)

DurationList accumulates time.Duration values into a slice.

func (*Clause) DurationListVar

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

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)

EnumVar 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() (target *[]string)

ExistingDirs accumulates string values into a slice.

func (*Clause) ExistingDirsVar

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

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() (target *[]string)

ExistingFiles accumulates string values into a slice.

func (*Clause) ExistingFilesOrDirs

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

ExistingFilesOrDirs accumulates string values into a slice.

func (*Clause) ExistingFilesOrDirsVar

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

func (*Clause) ExistingFilesVar

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

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() (target *[]float32)

Float32List accumulates float32 values into a slice.

func (*Clause) Float32ListVar

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

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() (target *[]float64)

Float64List accumulates float64 values into a slice.

func (*Clause) Float64ListVar

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

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

func (c *Clause) GetEnvarValue() string

func (*Clause) GetSplitEnvarValue

func (c *Clause) GetSplitEnvarValue() []string

func (*Clause) HasEnvarValue

func (c *Clause) HasEnvarValue() bool

func (*Clause) HexBytes

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

Bytes as a hex string.

func (*Clause) HexBytesList

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

HexBytesList accumulates []byte values into a slice.

func (*Clause) HexBytesListVar

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

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) 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() (target *[]int16)

Int16List accumulates int16 values into a slice.

func (*Clause) Int16ListVar

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

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() (target *[]int32)

Int32List accumulates int32 values into a slice.

func (*Clause) Int32ListVar

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

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() (target *[]int64)

Int64List accumulates int64 values into a slice.

func (*Clause) Int64ListVar

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

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() (target *[]int8)

Int8List accumulates int8 values into a slice.

func (*Clause) Int8ListVar

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

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() (target *[]int)

Ints accumulates int values into a slice.

func (*Clause) IntsVar

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

func (*Clause) Model

func (f *Clause) Model() *ClauseModel

func (*Clause) NoEnvar

func (c *Clause) NoEnvar() *Clause

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

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 callback executed

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() (target *[]*regexp.Regexp)

RegexpList accumulates *regexp.Regexp values into a slice.

func (*Clause) RegexpListVar

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

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() (target *map[string]string)

StringMap provides key=value parsing into a map.

func (*Clause) StringMapVar

func (c *Clause) StringMapVar(target *map[string]string)

StringMap provides key=value parsing into a map.

func (*Clause) StringVar

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

func (*Clause) Strings

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

Strings accumulates string values into a slice.

func (*Clause) StringsVar

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

func (*Clause) URL

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

URL provides a valid, parsed url.URL.

func (*Clause) URLList

func (c *Clause) URLList() (target *[]*url.URL)

URLList provides a parsed list of url.URL values.

func (*Clause) URLListVar

func (c *Clause) URLListVar(target *[]*url.URL)

URLListVar provides a parsed list of url.URL values.

func (*Clause) URLVar

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

URL provides a valid, parsed 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() (target *[]uint16)

Uint16List accumulates uint16 values into a slice.

func (*Clause) Uint16ListVar

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

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() (target *[]uint32)

Uint32List accumulates uint32 values into a slice.

func (*Clause) Uint32ListVar

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

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() (target *[]uint64)

Uint64List accumulates uint64 values into a slice.

func (*Clause) Uint64ListVar

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

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() (target *[]uint8)

Uint8List accumulates uint8 values into a slice.

func (*Clause) Uint8ListVar

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

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() (target *[]uint)

Uints accumulates uint values into a slice.

func (*Clause) UintsVar

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

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
	Envar       string
	PlaceHolder string
	Required    bool
	Hidden      bool
	Value       Value
	Cumulative  bool
}

func (*ClauseModel) FormatPlaceHolder

func (c *ClauseModel) FormatPlaceHolder() string

func (*ClauseModel) IsBoolFlag

func (c *ClauseModel) IsBoolFlag() 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) 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 {
	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) 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) 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 Settings

type Settings interface {
	SetValue(value Value)
}

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.

Jump to

Keyboard shortcuts

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