cli

package
v0.0.0-...-dc64ae7 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2021 License: CC0-1.0 Imports: 9 Imported by: 0

Documentation

Overview

Package cli provides an easy way to build command line applications.

If the value for a subcommand is nil, it is treated as if the command didn't even exist. This is useful for disabling the builtin subcommands like completion and help.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidArg = errors.New("cli: invalid command line argument")

ErrInvalidArg indicates that there was an invalid command line argument. It can be used as the target to errors.Is to test if the returned error from Run calls was as a result of mistyped command line arguments.

Functions

func AutoEnv

func AutoEnv(c *Context)

AutoEnv enables the automatic derivation of environment variable names from the exported field names of Command structs. By default, the program name will be converted to SCREAMING_CASE with a trailing underscore, and used as a prefix for all generated environment variables. This can be controlled using the EnvPrefix Option.

func EnvPrefix

func EnvPrefix(s string) func(*Context)

EnvPrefix enables AutoEnv and overrides the default prefix of the program name when automatically deriving environment variables. Use an empty string if the environment variables should be unprefixed.

This function will panic if the given prefix is not empty or is invalid, i.e. not made up of uppercase letters and underscores. Non-empty values must not have a trailing underscore. One will be appended automatically.

func NoValidate

func NoValidate(c *Context)

NoValidate disables the automatic validation of all commands and subcommands. Validation adds to the startup time, and can be instead done by calling the Validate function from within tests.

func Run

func Run(name string, cmd Command, args []string, opts ...Option) error

Run processes the command line arguments in the context of the given Command. The given program name will be used to auto-generate help text and error messages.

func RunThenExit

func RunThenExit(name string, cmd Command, opts ...Option)

RunThenExit provides a utility function that:

* Calls Run with os.Args.

* If Run returns an error, prints the error as long as it's not InvalidArg related.

* Exits with a status code of 0 on success, 2 on InvalidArg, and 1 otherwise.

The function will use process.Exit instead of os.Exit so that any registered exit handlers will run.

func ShowEnvHelp

func ShowEnvHelp(c *Context)

ShowEnvHelp emits the associated environment variable names when auto-generating help text.

func Validate

func Validate(name string, cmd Command, opts ...Option) error

Validate ensures that the given Command and all descendants have compliant struct tags and command names. Without this, validation only happens for the specific commands when they are executed on the command line.

Types

type Command

type Command interface {
	About() *Info
}

Command specifies the basic interface that a command needs to implement. For more fine-grained control, commands can also implement any of the Completer, Helper, InvalidArgHelper, and Runner interfaces.

func FromFunc

func FromFunc(run func(c *Context) error, info string) Command

FromFunc will define a new Command from the given run function and short info string. It's useful for defining commands where there's no need to handle any command line flags.

type Completer

type Completer interface {
	Complete(c *Context) Completion
}

Completer defines the interface that a command should implement if it wants to provide custom autocompletion on command line arguments.

type Completion

type Completion struct {
}

type Context

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

Context provides a way to access processed command line info at specific points within the command hierarchy.

func (*Context) Args

func (c *Context) Args() []string

Args returns the command line arguments for the current context.

func (*Context) ChildContext

func (c *Context) ChildContext(subcommand string) (*Context, error)

ChildContext tries to create a child Context for a subcommand.

func (*Context) Command

func (c *Context) Command() Command

Command returns the Command associated with the current context. By doing a type assertion on the returned value, this can be used to access field values of the parent or root context.

func (*Context) Flags

func (c *Context) Flags() []*Flag

Flags returns the command line flags for the current context.

func (*Context) FullName

func (c *Context) FullName() string

FullName returns the space separated sequence of command names, all the way from the root to the current context.

func (*Context) Help

func (c *Context) Help() string

Help returns the help text for a command. Commands wishing to override the auto-generated help text, must implement the Helper interface.

func (*Context) InvalidArg

func (c *Context) InvalidArg(typ InvalidArgType, arg string, flag *Flag, err error) error

func (*Context) Name

func (c *Context) Name() string

Name returns the command name for the current context.

func (*Context) Parent

func (c *Context) Parent() *Context

Parent returns the parent of the current context.

func (*Context) PrintHelp

func (c *Context) PrintHelp()

PrintHelp outputs the command's help text to stdout.

func (*Context) Program

func (c *Context) Program() string

Program returns the program name, i.e. the command name for the root context.

func (*Context) Root

func (c *Context) Root() *Context

Root returns the root context.

type Default

type Default struct {
	Info        *Info `cli:"-"`
	Subcommands Subcommands
}

Default makes it super easy to create tools with subcommands. Just instantiate the struct, with the relevant Info, Subcommands, and pass it to RunThenExit.

func (*Default) About

func (d *Default) About() *Info

type Flag

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

Flag defines a command line flag derived from a Command struct.

func (*Flag) Env

func (f *Flag) Env() []string

Env returns the environment variables associated with the flag.

func (*Flag) Help

func (f *Flag) Help() string

Help returns the help info for the flag.

func (*Flag) Hidden

func (f *Flag) Hidden() bool

Hidden returns whether the flag should be hidden from help output.

func (*Flag) Label

func (f *Flag) Label() string

Label returns the descriptive label for the flag option. This is primarily used to generate the help text, e.g.

--input-file path

Boolean flags will always result in an empty string as the label. For all other types, the following sources are used in priority order:

- Any non-empty value set using the "label" struct tag on the field.

- Any labels that can be extracted from the help info by looking for the first non-whitespace separated set of characters enclosed within {braces} within the "help" struct tag on the field.

- The field type, e.g. string, int, duration, etc. For non-builtin types, this will simply state "value".

func (*Flag) LongFlags

func (f *Flag) LongFlags() []string

LongFlags returns the associated long flags.

func (*Flag) Multi

func (f *Flag) Multi() bool

Multi returns whether the flag can be set multiple times.

func (*Flag) Required

func (f *Flag) Required() bool

Required returns whether the flag has been marked as required.

func (*Flag) ShortFlags

func (f *Flag) ShortFlags() []string

ShortFlags returns the associated short flags.

type Helper

type Helper interface {
	Help(c *Context) string
}

Helper defines the interface that a command should implement if it wants fine-grained control over the help text. Otherwise, the text is auto-generated from the command name, About() output, and struct fields.

type Info

type Info struct {
	Short string
}

Info

type InvalidArg

type InvalidArg struct {
	Arg     string
	Context *Context
	Err     error
	Flag    *Flag
	Type    InvalidArgType
}

InvalidArg

func (*InvalidArg) Details

func (i *InvalidArg) Details() string

func (*InvalidArg) Error

func (i *InvalidArg) Error() string

func (*InvalidArg) Is

func (i *InvalidArg) Is(target error) bool

type InvalidArgHelper

type InvalidArgHelper interface {
	InvalidArg(ia *InvalidArg) string
}

InvalidArgHelper defines the interface that a command should implement to control the error output when an invalid command line argument is encountered.

The returned string is assumed to be contextual help based on the InvalidArg, and will be emitted to stdout. Non-empty strings will have a newline appended to them if they don't already include one.

If this interface isn't implemented, commands will default to printing an error about the invalid argument to stderr, followed by auto-generated contextual help text.

type InvalidArgType

type InvalidArgType int
const (
	UnspecifiedInvalidArg InvalidArgType = iota
	InvalidEnv
	InvalidFlag
	InvalidValue
	MissingFlag
	MissingValue
	RepeatedFlag
	UnknownSubcommand
)

Invalid argument types.

func (InvalidArgType) String

func (i InvalidArgType) String() string

type Option

type Option func(c *Context)

Option configures the root context.

type Runner

type Runner interface {
	Run(c *Context) error
}

Runner defines the interface that a command should implement to handle command line arguments.

type Subcommands

type Subcommands map[string]Command

Subcommands defines the field type for defining subcommands on a struct.

type Version

type Version string

Version provides a default implementation to use as a subcommand to output version info.

func (Version) About

func (v Version) About() *Info

func (Version) Run

func (v Version) Run(c *Context) error

Jump to

Keyboard shortcuts

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