cmdr

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2017 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EX_OK          = 0  // successful termination
	EX_USAGE       = 64 // command line usage error
	EX_DATAERR     = 65 // data format error
	EX_NOINPUT     = 66 // cannot open input
	EX_NOUSER      = 67 // addressee unknown
	EX_NOHOST      = 68 // host name unknown
	EX_UNAVAILABLE = 69 // service unavailable
	EX_SOFTWARE    = 70 // internal software error
	EX_OSERR       = 71 // system error (e.g., can't fork)
	EX_OSFILE      = 72 // critical OS file missing
	EX_CANTCREAT   = 73 // can't create (user) output file
	EX_IOERR       = 74 // input/output error
	EX_TEMPFAIL    = 75 // temp failure; user is invited to retry
	EX_PROTOCOL    = 76 // remote error in protocol
	EX_NOPERM      = 77 // permission denied
	EX_CONFIG      = 78 // configuration error
)
View Source
const (
	// DefaultIndentString is the default indent to use when writing
	// procedurally to the CLI outputs. It is set to two consecutive spaces,
	// matching default output from the flag package.
	DefaultIndentString = "  "
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AddsFlags

type AddsFlags interface {
	// AddFlags will be passed a flag.FlagSet already named correctly for
	// this command. All you need to do is add whatever flag definitions
	// apply to this command.
	AddFlags(*flag.FlagSet)
}

AddsFlags means this command has flags to add. These flags will be available not only to this command, but will still be read, and have impact on this command, even if the user applies them to deeper subcommands.

type CLI

type CLI struct {
	// Root is the root command to execute.
	Root Command
	// Out is an *Output, defaults to a plain os.Stdout writer if left nil.
	Out,

	Err *Output
	// Env is a map of environment variable names to their values.
	Env map[string]string
	// Hooks allow you to perform pre and post processing on Commands at
	// various points in their lifecycle.
	Hooks Hooks
	// HelpCommand tells the user how to get help. It should be a command
	// they can type in to get help.
	HelpCommand string
	// GlobalFlagSetFuncs allow global flags to be added to the CLI.
	GlobalFlagSetFuncs []func(*flag.FlagSet)
	// IndentString is the default indent to use for indenting command
	// output when Output.Indent() is called inside a command. If left
	// empty, defaults to DefaultIndentString.
	IndentString string
}

CLI encapsulates a command line interface, and knows how to execute commands and their subcommands and parse flags.

func (*CLI) Help

func (cli *CLI) Help(cmd Command, cmdArgs []string) (string, error)

Help collects information about a subcommand and its arguments, descends the path down the command tree provided by cmdArgs, finds the lowest subcommand on that path, and returns the help text for that subcommand.

func (*CLI) Invoke

func (c *CLI) Invoke(args []string) Result

Invoke begins invoking the CLI starting with the base command, and handles all command output. It then returns the result for further processing.

func (*CLI) InvokeAndExit

func (c *CLI) InvokeAndExit(args []string)

InvokeAndExit calls Invoke, and exits with the returned exit code.

func (*CLI) InvokeWithoutPrinting

func (c *CLI) InvokeWithoutPrinting(args []string) Result

InvokeWithoutPrinting invokes the CLI without printing the results.

func (*CLI) IsSuccess added in v0.0.2

func (c *CLI) IsSuccess(result Result) bool

IsSuccess checks if a Result is a success

func (*CLI) ListSubcommands

func (c *CLI) ListSubcommands(base Command) []string

ListSubcommands returns a slice of strings with the names of each subcommand as they need to be entered by the user, arranged alphabetically.

func (*CLI) OutputResult added in v0.0.2

func (c *CLI) OutputResult(result Result)

OutputResult formats and outputs a cmdr.Result - handles tips when the result is an error, etc. returns true if the result was a success

func (*CLI) Prepare

func (c *CLI) Prepare(args []string) (*PreparedExecution, error)

Prepare sets up a command for execution, resolving subcommands and flags, and forwarding flags from lower commands to higher ones. This means that flags defined on the base command are also defined by default all its nested subcommands, which is usually a nicer user experience than having to remember strictly which subcommand a flag is applicable to.

func (*CLI) SetVerbosity

func (c *CLI) SetVerbosity(v Verbosity)

SetVerbosity sets the verbosity.

type Command

type Command interface {
	// Help is the help message for a command. To be a command, all you need
	// is a help message.
	// Help messages must follow this convention:
	// The first line must be 50 characters or fewer, and describe
	// succinctly what the command does.
	// The second line must be blank.
	// The remainder of the string is free-form text.
	Help() string
}

Command is a command that can be invoked.

type Commands

type Commands map[string]Command

Commands is a mapping of strings (the command name) to commands.

func (Commands) SortedKeys

func (cs Commands) SortedKeys() []string

SortedKeys returns the names of the commands in alphabetical order.

type ErrorResult

type ErrorResult interface {
	error
	Result
	WithTip(string) ErrorResult
	WithUnderlyingError(error) ErrorResult
	Tipper
}

An ErrorResult is both an error and a result, and has a tip for the user.

func EnsureErrorResult

func EnsureErrorResult(err error) ErrorResult

EnsureErrorResult takes an error, and if it is not already also a Result, makes it into an ErrorResult. It tries to wrap well-known errors intelligently, and eventially falls back to UnknownErr if no sensible ErrorResult exists for that error.

type Executor

type Executor interface {
	Execute(args []string) Result
}

Executor is a command can itself be executed to do something.

type ExitCode

type ExitCode int

type Hooks

type Hooks struct {
	// Startup is run at the beginning of every invocation
	Startup func(*CLI) error
	// Parsed is run on a command when it's found on the command line
	Parsed func(Command) error
	// PreExecute is run on a command before it executes.
	PreExecute func(Command) error
	// PreFail is run just before a command exits with an error.
	// Is is passed the error, and must return the final ErrorResult.
	PreFail func(error) ErrorResult
}

Hooks is a collection of command hooks. If a hook returns a non-nil error it cancels execution and the error is displayed to the user.

type IOErr

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

IOErr signifies that something went wrong with io, to files, or across the network, for example.

func IOErrorf

func IOErrorf(format string, v ...interface{}) IOErr

func (IOErr) Error

func (e IOErr) Error() string

func (IOErr) ExitCode

func (e IOErr) ExitCode() int

func (IOErr) UnderlyingError

func (e IOErr) UnderlyingError() error

func (IOErr) UserTip

func (e IOErr) UserTip() string

func (IOErr) WithTip

func (e IOErr) WithTip(tip string) ErrorResult

func (IOErr) WithUnderlyingError

func (e IOErr) WithUnderlyingError(err error) ErrorResult

type InternalErr

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

InternalErr signifies programmer error. The user only sees these when we mess up.

func InternalErrorf

func InternalErrorf(format string, v ...interface{}) InternalErr

func (InternalErr) Error

func (e InternalErr) Error() string

func (InternalErr) ExitCode

func (e InternalErr) ExitCode() int

func (InternalErr) UnderlyingError

func (e InternalErr) UnderlyingError() error

func (InternalErr) UserTip

func (e InternalErr) UserTip() string

func (InternalErr) WithTip

func (e InternalErr) WithTip(tip string) ErrorResult

func (InternalErr) WithUnderlyingError

func (e InternalErr) WithUnderlyingError(err error) ErrorResult

type OSErr

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

OSErr signifies that something went wrong starting a process, or performing some other os-level operation.

func OSErrorf

func OSErrorf(format string, v ...interface{}) OSErr

func (OSErr) Error

func (e OSErr) Error() string

func (OSErr) ExitCode

func (e OSErr) ExitCode() int

func (OSErr) UnderlyingError

func (e OSErr) UnderlyingError() error

func (OSErr) UserTip

func (e OSErr) UserTip() string

func (OSErr) WithTip

func (e OSErr) WithTip(tip string) ErrorResult

func (OSErr) WithUnderlyingError

func (e OSErr) WithUnderlyingError(err error) ErrorResult

type Output

type Output struct {
	// Verbosity is the verbosity of this output.
	Verbosity Verbosity
	// Errors contains any errors this output has encountered whilst
	// writing to Writer.
	Errors []error
	// contains filtered or unexported fields
}

Output is a convenience wrapper around an io.Writer that provides extra features for formatting text, such as indentation and the ability to emit tables. It is designed to be used sequentially, writing and changing context on each call to one of its methods.

func NewOutput

func NewOutput(w io.Writer, configFunc ...func(*Output)) *Output

NewOutput creates a new Output, you may optionally pass any number of functions, each of which will be called on the Output before it is returned. You can use this to create and configure an output in a single statement.

func (*Output) Printf

func (o *Output) Printf(format string, v ...interface{})

func (*Output) Printfln

func (o *Output) Printfln(format string, v ...interface{})

Printfln is similar to Println, except it takes a format string.

func (*Output) Println

func (o *Output) Println(v ...interface{})

Println prints a line, respecting current indentation.

func (*Output) Write

func (o *Output) Write(b []byte) (int, error)

func (*Output) WriteString

func (o *Output) WriteString(s string)

type PreparedExecution

type PreparedExecution struct {
	Cmd  Executor
	Args []string
}

A PreparedExecution collects all the information needed to execute a command

type Result

type Result interface {
	// ExitCode is the exit code the program should exit with based on this
	// result.
	ExitCode() int
}

Result is a result of a CLI invokation.

func Successf

func Successf(format string, v ...interface{}) Result

type Subcommander

type Subcommander interface {
	// Subcommands returns a map of command names to Commands.
	Subcommands() Commands
}

Subcommander means this command has subcommands.

type SuccessResult

type SuccessResult struct {
	// Data is the real return value of this function, it will be printed to
	// stdout by default, for consumption by other commands/pipelines etc.
	Data []byte
}

SuccessResult is a successful result.

func Success

func Success(v ...interface{}) SuccessResult

func SuccessData

func SuccessData(d []byte) SuccessResult

func (SuccessResult) ExitCode

func (s SuccessResult) ExitCode() int

func (SuccessResult) String

func (s SuccessResult) String() string

type Tipper

type Tipper interface {
	UserTip() string
}

type UnknownErr

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

UnknownErr is the error of last resort, only to be used if none of the other error types is applicable.

func UnknownErrorf

func UnknownErrorf(format string, v ...interface{}) UnknownErr

func (UnknownErr) Error

func (e UnknownErr) Error() string

func (UnknownErr) ExitCode

func (e UnknownErr) ExitCode() int

func (UnknownErr) UnderlyingError

func (e UnknownErr) UnderlyingError() error

func (UnknownErr) UserTip

func (e UnknownErr) UserTip() string

func (UnknownErr) WithTip

func (e UnknownErr) WithTip(tip string) ErrorResult

func (UnknownErr) WithUnderlyingError

func (e UnknownErr) WithUnderlyingError(err error) ErrorResult

type UsageErr

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

UsageErr signifies that the user made a mistake with the invocation.

func UsageErrorf

func UsageErrorf(format string, v ...interface{}) UsageErr

func (UsageErr) Error

func (e UsageErr) Error() string

func (UsageErr) ExitCode

func (e UsageErr) ExitCode() int

func (UsageErr) UnderlyingError

func (e UsageErr) UnderlyingError() error

func (UsageErr) UserTip

func (e UsageErr) UserTip() string

func (UsageErr) WithTip

func (e UsageErr) WithTip(tip string) ErrorResult

func (UsageErr) WithUnderlyingError

func (e UsageErr) WithUnderlyingError(err error) ErrorResult

type Verbosity

type Verbosity int

Verbosity represents the level of output detail a CLI should give to the user.

const (

	// Silent means output absolutely no error or warning messsages, but still
	// output the result of a command, if it has a real result.
	Silent Verbosity = iota
	// Quiet is similar to silent, but will echo error messages if the command
	// cannot be completed successfully.
	Quiet
	// Normal is the default verbosity, and is similar to quiet, but will
	// additionally output tips and warnings to the user. For long-running
	// commands, Normal may additionally output status updates, progress meters,
	// and other information to let the user know it's still working.
	Normal
	// Loud is similar to Normal, but outputs additional information.
	Loud
	// Debug is similar to Loud, but additionally outputs detailed internal
	// operations, helpful in debugging problems.
	Debug
)

func (Verbosity) String

func (v Verbosity) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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