Documentation
¶
Overview ¶
Package cmd provides a modern command-line library for Go.
The package is centered around App and Command. It supports recursive subcommands, global and command-local flags, positional argument schemas, environment and config binding, shell completion, machine-readable specs, generated documentation, lifecycle hooks, middleware, observer events, normalized CLI errors, and a built-in REPL that reuses the same command tree.
The simplest usage relies on the default application instance:
cmd.SetFlags(func(f *cmd.FlagSet) {
f.BoolVar(&verbose, "verbose", false, "enable verbose output", "v")
})
cmd.AddCommands(&cmd.Command{
Name: "version",
UsageLine: "app version",
Short: "print version",
Run: func(ctx context.Context, c *cmd.Command, args []string) error {
fmt.Println(version)
return nil
},
})
cmd.Execute()
For larger applications, create an explicit App with NewApp, attach commands, configure flags and config support, and call Run directly.
When an application needs both CLI and interactive usage, define the command tree once and enable the built-in REPL on the same App. CLI execution, REPL execution, completion, and inline REPL hints all share the same parser and command model. Terminal REPL sessions support editable input, history navigation, completion, dynamic prompts, and optional history load/append hooks.
Runtime helpers are also available so applications can choose explicit CLI or REPL entrypoints, or let the library automatically select an appropriate runtime for the current invocation.
Internally, both CLI args and REPL lines flow through the same Registry, Resolver, and Dispatcher pipeline. That shared pipeline keeps help, completion, spec export, docs generation, and command execution aligned on the same effective command tree while still isolating runtime flag state for each invocation.
See README.md for the full usage guide, including config precedence, completion, REPL configuration, runtime helpers, spec export, documentation generation, hooks, middleware, observers, and custom extensions.
Index ¶
- Constants
- Variables
- func AddCommands(cmds ...*Command)
- func Arg(i int) string
- func Args() []string
- func BindConfig(name string, configKeys ...string)
- func BindEnv(name string, envVars ...string)
- func Bool(name string, value bool, usage string, shorthand string) *bool
- func BoolFunc(name, usage string, fn func(string) error, shorthand string)
- func BoolVar(p *bool, name string, value bool, usage string, shorthand string)
- func Duration(name string, value time.Duration, usage string, shorthand string) *time.Duration
- func DurationVar(p *time.Duration, name string, value time.Duration, usage string, ...)
- func Execute()
- func Float64(name string, value float64, usage string, shorthand string) *float64
- func Float64Var(p *float64, name string, value float64, usage string, shorthand string)
- func Func(name, usage string, fn func(string) error, shorthand string)
- func Int(name string, value int, usage string, shorthand string) *int
- func Int64(name string, value int64, usage string, shorthand string) *int64
- func Int64Var(p *int64, name string, value int64, usage string, shorthand string)
- func IntVar(p *int, name string, value int, usage string, shorthand string)
- func LexLine(line string) ([]string, error)
- func LexLineForCompletion(line string) ([]string, string, error)
- func LoadJSONConfig(path string) (map[string]any, error)
- func Main(app *App)
- func MainWithContext(ctx context.Context, app *App)
- func MarkDeprecated(name, message string)
- func MarkHidden(name string)
- func MarkRepeatable(name string)
- func MarkRequired(name string)
- func NArg() int
- func NFlag() int
- func Parse()
- func Parsed() bool
- func PrintDefaults()
- func Set(name, value string) error
- func SetCategory(name, category string)
- func SetCompletion(name string, fn CompletionFunc)
- func SetCompletionKey(name, key string)
- func SetEnum(name string, values ...string)
- func SetExample(name, example string)
- func SetFlags(f func(f *FlagSet))
- func SetID(name, id string)
- func SetKind(name, kind string)
- func SetSurface(name string, surface Surface, override FlagSurface)
- func SetUsageTemplate(usageTemplate string)
- func SplitLine(line string) ([]string, error)
- func SplitLineForCompletion(line string) (args []string, current string, err error)
- func String(name string, value string, usage string, shorthand string) *string
- func StringVar(p *string, name string, value string, usage string, shorthand string)
- func SuggestCommands(name string, commands Commands) []string
- func TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, ...)
- func Uint(name string, value uint, usage string, shorthand string) *uint
- func Uint64(name string, value uint64, usage string, shorthand string) *uint64
- func Uint64Var(p *uint64, name string, value uint64, usage string, shorthand string)
- func UintVar(p *uint, name string, value uint, usage string, shorthand string)
- func UnknownCommandError(name string, commands Commands) error
- func UnknownSubcommandError(command string, target string, subcommands Commands) error
- func UnquoteUsage(flag *Flag) (name string, usage string)
- func UsageError(usageLine string) error
- func Var(value Value, name string, usage string, shorthand string)
- func VisibleCommandNames(commands Commands) []string
- func Visit(fn func(*Flag))
- func VisitAll(fn func(*Flag))
- type AfterHook
- type App
- func (a *App) AddCommands(cmds ...*Command)
- func (a *App) AddObserver(observers ...Observer)
- func (a *App) AvailableSurfaces() []Surface
- func (a *App) CompleteLine(line string, cursor int) []string
- func (a *App) CompleteLineDetailed(line string, cursor int) []CompletionResult
- func (a *App) ConfigureFlags(f func(f *FlagSet))
- func (a *App) ConfigureREPL(fn func(cfg *REPLConfig))
- func (a *App) DefaultRuntime(args []string) Runtime
- func (a *App) EnableConfigSupport()
- func (a *App) EnableREPL()
- func (a *App) Execute(args []string) error
- func (a *App) ExitStatus() int
- func (a *App) Main(ctx context.Context, runtime Runtime) int
- func (a *App) MainAuto(ctx context.Context, args []string) int
- func (a *App) MainDefault(ctx context.Context, args []string) int
- func (a *App) MustRun(ctx context.Context, runtime Runtime)
- func (a *App) MustRunAuto(ctx context.Context, args []string)
- func (a *App) MustRunDefault(ctx context.Context, args []string)
- func (a *App) Run(ctx context.Context, args []string) error
- func (a *App) RunAuto(ctx context.Context, args []string) error
- func (a *App) RunDefault(ctx context.Context, args []string) error
- func (a *App) RunLine(ctx context.Context, line string) error
- func (a *App) RunREPL(ctx context.Context, in io.Reader, out io.Writer) error
- func (a *App) RunWith(ctx context.Context, runtime Runtime) error
- func (a *App) SetExtension(key string, value any)
- func (a *App) SetRootCommand(root *Command)
- func (a *App) Spec() AppSpec
- func (a *App) SpecFor(surface Surface) AppSpec
- func (a *App) Usage()
- func (a *App) Use(middlewares ...Middleware)
- func (a *App) UseUsageTemplate(usageTemplate string)
- type AppSpec
- type AutoRuntime
- type BasicREPLDriver
- type BeforeHook
- type BuiltinHandler
- type CLIError
- type CLIRuntime
- type CapabilitySpec
- type Command
- func (c *Command) AddObserver(observers ...Observer)
- func (c *Command) GetAlias() string
- func (c *Command) Runnable() bool
- func (c *Command) SetExtension(key string, value any)
- func (c *Command) SetSurface(surface Surface, override CommandSurface)
- func (c *Command) Usage()
- func (c *Command) Use(middlewares ...Middleware)
- type CommandSpec
- type CommandSurface
- type Commands
- type CompletionContext
- type CompletionFunc
- type CompletionResult
- type ConfigFlagOptions
- type ConfigLoader
- type ConfigRuntimeSpec
- type DetailedLineCompleter
- type Dispatcher
- type ErrorHandling
- type ErrorHook
- type Event
- type EventType
- type Flag
- type FlagSet
- func (f *FlagSet) ApplyConfig(data map[string]any) error
- func (f *FlagSet) ApplyEnv() error
- func (f *FlagSet) Arg(i int) string
- func (f *FlagSet) Args() []string
- func (f *FlagSet) BindConfig(name string, configKeys ...string)
- func (f *FlagSet) BindEnv(name string, envVars ...string)
- func (f *FlagSet) Bool(name string, value bool, usage string, shorthand string) *bool
- func (f *FlagSet) BoolFunc(name, usage string, fn func(string) error, shorthand string)
- func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string, shorthand string)
- func (f *FlagSet) Duration(name string, value time.Duration, usage string, shorthand string) *time.Duration
- func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string, ...)
- func (f *FlagSet) ErrorHandling() ErrorHandling
- func (f *FlagSet) Float64(name string, value float64, usage string, shorthand string) *float64
- func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string, shorthand string)
- func (f *FlagSet) Func(name, usage string, fn func(string) error, shorthand string)
- func (f *FlagSet) Init(name string, errorHandling ErrorHandling)
- func (f *FlagSet) Int(name string, value int, usage string, shorthand string) *int
- func (f *FlagSet) Int64(name string, value int64, usage string, shorthand string) *int64
- func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string, shorthand string)
- func (f *FlagSet) IntVar(p *int, name string, value int, usage string, shorthand string)
- func (f *FlagSet) IsSet(name string) bool
- func (f *FlagSet) Lookup(name string) (*Flag, bool)
- func (f *FlagSet) LookupShort(shorthand string) (*Flag, bool)
- func (f *FlagSet) MarkDeprecated(name, message string)
- func (f *FlagSet) MarkHidden(name string)
- func (f *FlagSet) MarkRepeatable(name string)
- func (f *FlagSet) MarkRequired(name string)
- func (f *FlagSet) NArg() int
- func (f *FlagSet) NFlag() int
- func (f *FlagSet) Name() string
- func (f *FlagSet) Output() io.Writer
- func (f *FlagSet) Parse(arguments []string) error
- func (f *FlagSet) Parsed() bool
- func (f *FlagSet) PrintDefaults()
- func (f *FlagSet) Set(name, value string) error
- func (f *FlagSet) SetCategory(name, category string)
- func (f *FlagSet) SetCompletion(name string, fn CompletionFunc)
- func (f *FlagSet) SetCompletionKey(name, key string)
- func (f *FlagSet) SetEnum(name string, values ...string)
- func (f *FlagSet) SetExample(name, example string)
- func (f *FlagSet) SetExtension(name, key string, value any) error
- func (f *FlagSet) SetID(name, id string)
- func (f *FlagSet) SetKind(name, kind string)
- func (f *FlagSet) SetOutput(output io.Writer)
- func (f *FlagSet) SetSurface(name string, surface Surface, override FlagSurface)
- func (f *FlagSet) String(name string, value string, usage string, shorthand string) *string
- func (f *FlagSet) StringVar(p *string, name string, value string, usage string, shorthand string)
- func (f *FlagSet) TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, ...)
- func (f *FlagSet) Uint(name string, value uint, usage string, shorthand string) *uint
- func (f *FlagSet) Uint64(name string, value uint64, usage string, shorthand string) *uint64
- func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string, shorthand string)
- func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string, shorthand string)
- func (f *FlagSet) Validate() error
- func (f *FlagSet) Var(value Value, name string, usage string, shorthand string)
- func (f *FlagSet) Visit(fn func(*Flag))
- func (f *FlagSet) VisitAll(fn func(*Flag))
- func (f *FlagSet) WarnDeprecated()
- type FlagSpec
- type FlagSurface
- type Getter
- type HookContext
- type HookSpec
- type Invocation
- type InvocationKind
- type LineCompleter
- type Middleware
- type MiddlewareContext
- type NextFunc
- type Observer
- type ObserverFunc
- type PositionalArg
- type PositionalSpec
- type PositionalSurface
- type REPL
- type REPLConfig
- type REPLDriver
- type REPLHistoryHooks
- type REPLRuntime
- type Registry
- type Resolver
- type Runtime
- type Surface
- type TerminalREPLDriver
- type Value
Constants ¶
const ( ErrorKindInvalidArguments = "invalid_arguments" ErrorKindNotFound = "not_found" ErrorKindCanceled = "canceled" ErrorKindInternal = "internal" ErrorKindRuntime = "runtime" )
Variables ¶
var ( ErrNotFound = errors.New("not found") DefaultApp = NewApp(filepath.Base(os.Args[0])) )
var ErrHelp = errors.New("flag: help requested")
ErrHelp is the error returned if the -help or -h flag is invoked but no such flag is defined.
var Usage = func() { fmt.Fprintf(CommandLine.Output(), "Usage of %s:\n", os.Args[0]) PrintDefaults() }
Usage prints a usage message documenting all defined command-line flags to CommandLine's output, which by default is os.Stderr. It is called when an error occurs while parsing flags. The function is a variable that may be changed to point to a custom function. By default it prints a simple header and calls PrintDefaults; for details about the format of the output and how to control it, see the documentation for PrintDefaults. Custom usage functions may choose to exit the program; by default exiting happens anyway as the command line's error handling strategy is set to ExitOnError.
Functions ¶
func Arg ¶ added in v0.1.7
Arg returns the i'th command-line argument. Arg(0) is the first remaining argument after flags have been processed. Arg returns an empty string if the requested element does not exist.
func BindConfig ¶ added in v0.1.8
func Bool ¶ added in v0.1.7
Bool defines a bool flag with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the flag.
func BoolFunc ¶ added in v0.1.7
BoolFunc defines a flag with the specified name and usage string without requiring values. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.
func BoolVar ¶ added in v0.1.7
BoolVar defines a bool flag with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the flag.
func Duration ¶ added in v0.1.7
Duration defines a time.Duration flag with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the flag. The flag accepts a value acceptable to time.ParseDuration.
func DurationVar ¶ added in v0.1.7
func DurationVar(p *time.Duration, name string, value time.Duration, usage string, shorthand string)
DurationVar defines a time.Duration flag with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the flag. The flag accepts a value acceptable to time.ParseDuration.
func Float64 ¶ added in v0.1.7
Float64 defines a float64 flag with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the flag.
func Float64Var ¶ added in v0.1.7
Float64Var defines a float64 flag with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the flag.
func Func ¶ added in v0.1.7
Func defines a flag with the specified name and usage string. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.
func Int ¶ added in v0.1.7
Int defines an int flag with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the flag.
func Int64 ¶ added in v0.1.7
Int64 defines an int64 flag with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the flag.
func Int64Var ¶ added in v0.1.7
Int64Var defines an int64 flag with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the flag.
func IntVar ¶ added in v0.1.7
IntVar defines an int flag with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the flag.
func LexLineForCompletion ¶ added in v0.2.0
LexLineForCompletion tokenizes a partial REPL line for cursor-aware completion.
func MainWithContext ¶ added in v0.2.0
func MarkDeprecated ¶ added in v0.1.8
func MarkDeprecated(name, message string)
func MarkHidden ¶ added in v0.1.8
func MarkHidden(name string)
func MarkRepeatable ¶ added in v0.2.0
func MarkRepeatable(name string)
func MarkRequired ¶ added in v0.1.8
func MarkRequired(name string)
func NArg ¶ added in v0.1.7
func NArg() int
NArg is the number of arguments remaining after flags have been processed.
func NFlag ¶ added in v0.1.7
func NFlag() int
NFlag returns the number of command-line flags that have been set.
func Parse ¶ added in v0.1.7
func Parse()
Parse parses the command-line flags from os.Args[1:]. Must be called after all flags are defined and before flags are accessed by the program.
func Parsed ¶ added in v0.1.7
func Parsed() bool
Parsed reports whether the command-line flags have been parsed.
func PrintDefaults ¶ added in v0.1.7
func PrintDefaults()
PrintDefaults prints, to standard error unless configured otherwise, a usage message showing the default settings of all defined command-line flags. For an integer valued flag x, the default output has the form
-x int usage-message-for-x (default 7)
The usage message will appear on a separate line for anything but a bool flag with a one-byte name. For bool flags, the type is omitted and if the flag name is one byte the usage message appears on the same line. The parenthetical default is omitted if the default is the zero value for the type. The listed type, here int, can be changed by placing a back-quoted name in the flag's usage string; the first such item in the message is taken to be a parameter name to show in the message and the back quotes are stripped from the message when displayed. For instance, given
flag.String("I", "", "search `directory` for include files")
the output will be
-I directory search directory for include files.
To change the destination for flag messages, call CommandLine.SetOutput.
func SetCategory ¶ added in v0.1.8
func SetCategory(name, category string)
func SetCompletion ¶ added in v0.1.8
func SetCompletion(name string, fn CompletionFunc)
func SetCompletionKey ¶ added in v0.2.0
func SetCompletionKey(name, key string)
func SetExample ¶ added in v0.1.8
func SetExample(name, example string)
func SetSurface ¶ added in v0.2.0
func SetSurface(name string, surface Surface, override FlagSurface)
func SetUsageTemplate ¶
func SetUsageTemplate(usageTemplate string)
SetUsageTemplate set value to usageTemplate
func SplitLineForCompletion ¶ added in v0.1.10
SplitLineForCompletion splits a partial REPL line into completed args and the current token.
func String ¶ added in v0.1.7
String defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.
func StringVar ¶ added in v0.1.7
StringVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.
func SuggestCommands ¶ added in v0.2.0
func TextVar ¶ added in v0.1.7
func TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string, shorthand string)
TextVar defines a flag with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the flag, and p must implement encoding.TextUnmarshaler. If the flag is used, the flag value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p.
func Uint ¶ added in v0.1.7
Uint defines a uint flag with specified name, default value, and usage string. The return value is the address of a uint variable that stores the value of the flag.
func Uint64 ¶ added in v0.1.7
Uint64 defines a uint64 flag with specified name, default value, and usage string. The return value is the address of a uint64 variable that stores the value of the flag.
func Uint64Var ¶ added in v0.1.7
Uint64Var defines a uint64 flag with specified name, default value, and usage string. The argument p points to a uint64 variable in which to store the value of the flag.
func UintVar ¶ added in v0.1.7
UintVar defines a uint flag with specified name, default value, and usage string. The argument p points to a uint variable in which to store the value of the flag.
func UnknownCommandError ¶ added in v0.2.0
func UnknownSubcommandError ¶ added in v0.2.0
func UnquoteUsage ¶ added in v0.1.7
UnquoteUsage extracts a back-quoted name from the usage string for a flag and returns it and the un-quoted usage. Given "a `name` to show" it returns ("name", "a name to show"). If there are no back quotes, the name is an educated guess of the type of the flag's value, or the empty string if the flag is boolean.
func UsageError ¶ added in v0.2.0
func Var ¶ added in v0.1.7
Var defines a flag with the specified name and usage string. The type and value of the flag are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a flag that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.
func VisibleCommandNames ¶ added in v0.2.0
Types ¶
type AfterHook ¶ added in v0.1.8
type AfterHook func(ctx HookContext)
type App ¶ added in v0.1.8
type App struct {
Name string
Short string
Long string
Root *Command
Commands Commands
REPL REPLConfig
UsageTemplate string
Out io.Writer
Err io.Writer
SetFlags func(f *FlagSet)
ConfigEnabled bool
ConfigLoader ConfigLoader
ConfigFlag ConfigFlagOptions
BeforeRun BeforeHook
AfterRun AfterHook
OnError ErrorHook
Middlewares []Middleware
Observers []Observer
// Extensions carries custom metadata for integrations and tooling.
// Slice and map values are cloned when the library copies metadata, but
// opaque pointer or custom object payloads are shared by reference. Callers
// that need full isolation should store immutable values or clone payloads
// themselves before attaching them here.
Extensions map[string]any
// contains filtered or unexported fields
}
App is the main application container
func (*App) AddCommands ¶ added in v0.1.10
AddCommands appends top-level commands to the app.
func (*App) AddObserver ¶ added in v0.1.8
func (*App) AvailableSurfaces ¶ added in v0.2.0
func (*App) CompleteLine ¶ added in v0.1.10
func (*App) CompleteLineDetailed ¶ added in v0.1.10
func (a *App) CompleteLineDetailed(line string, cursor int) []CompletionResult
func (*App) ConfigureFlags ¶ added in v0.1.10
ConfigureFlags sets the app-level global flag registration function.
func (*App) ConfigureREPL ¶ added in v0.2.0
func (a *App) ConfigureREPL(fn func(cfg *REPLConfig))
func (*App) DefaultRuntime ¶ added in v0.2.0
func (*App) EnableConfigSupport ¶ added in v0.1.8
func (a *App) EnableConfigSupport()
func (*App) EnableREPL ¶ added in v0.2.0
func (a *App) EnableREPL()
func (*App) ExitStatus ¶ added in v0.1.8
func (*App) MainDefault ¶ added in v0.2.0
func (*App) MustRunAuto ¶ added in v0.2.0
func (*App) MustRunDefault ¶ added in v0.2.0
func (*App) RunDefault ¶ added in v0.2.0
func (*App) SetExtension ¶ added in v0.1.8
func (*App) SetRootCommand ¶ added in v0.1.10
SetRootCommand assigns the app root command.
func (*App) Use ¶ added in v0.1.8
func (a *App) Use(middlewares ...Middleware)
func (*App) UseUsageTemplate ¶ added in v0.1.10
UseUsageTemplate replaces the app usage template.
type AppSpec ¶ added in v0.1.8
type AppSpec struct {
SchemaVersion string `json:"schema_version"`
Name string `json:"name"`
Short string `json:"short"`
Surface string `json:"surface,omitempty"`
AvailableSurfaces []string `json:"available_surfaces,omitempty"`
Builtins []string `json:"builtins,omitempty"`
Capabilities CapabilitySpec `json:"capabilities"`
Config ConfigRuntimeSpec `json:"config"`
Hooks HookSpec `json:"hooks,omitempty"`
HasMiddleware bool `json:"has_middleware,omitempty"`
HasObservers bool `json:"has_observers,omitempty"`
Extensions map[string]any `json:"extensions,omitempty"`
Root *CommandSpec `json:"root,omitempty"`
GlobalFlags []FlagSpec `json:"global_flags,omitempty"`
Commands []CommandSpec `json:"commands"`
}
type AutoRuntime ¶ added in v0.2.0
type BasicREPLDriver ¶ added in v0.2.0
type BasicREPLDriver struct{}
type BeforeHook ¶ added in v0.1.8
type BeforeHook func(ctx HookContext) error
type BuiltinHandler ¶ added in v0.2.0
type CLIRuntime ¶ added in v0.2.0
type CLIRuntime struct {
Args []string
}
type CapabilitySpec ¶ added in v0.1.8
type CapabilitySpec struct {
GlobalFlags bool `json:"global_flags"`
InterspersedFlags bool `json:"interspersed_flags"`
EnvBinding bool `json:"env_binding"`
ConfigBinding bool `json:"config_binding"`
ShellCompletion bool `json:"shell_completion"`
SpecExport bool `json:"spec_export"`
DocsExport bool `json:"docs_export"`
ValueCompletion bool `json:"value_completion"`
Positionals bool `json:"positionals"`
SurfaceOverrides bool `json:"surface_overrides"`
StableIDs bool `json:"stable_ids"`
SemanticKinds bool `json:"semantic_kinds"`
RepeatableFlags bool `json:"repeatable_flags"`
CompletionKeys bool `json:"completion_keys"`
LifecycleHooks bool `json:"lifecycle_hooks"`
Middleware bool `json:"middleware"`
Observers bool `json:"observers"`
ErrorNormalization bool `json:"error_normalization"`
}
type Command ¶
type Command struct {
Name string
ID string
HandlerID string
Aliases []string
UsageLine string
Short string
Long string
Group string
Examples []string
Positionals []PositionalArg
Deprecated string
Hidden bool
BeforeRun BeforeHook
AfterRun AfterHook
OnError ErrorHook
Middlewares []Middleware
Observers []Observer
// Extensions carries custom metadata for integrations and tooling.
// Slice and map values are cloned when the library copies metadata, but
// opaque pointer or custom object payloads are shared by reference. Callers
// that need full isolation should store immutable values or clone payloads
// themselves before attaching them here.
Extensions map[string]any
Surfaces map[Surface]CommandSurface
Run func(ctx context.Context, cmd *Command, args []string) error
SetFlags func(f *FlagSet)
SubCommands Commands
// contains filtered or unexported fields
}
Command struct
func (*Command) AddObserver ¶ added in v0.1.8
func (*Command) SetExtension ¶ added in v0.1.8
func (*Command) SetSurface ¶ added in v0.2.0
func (c *Command) SetSurface(surface Surface, override CommandSurface)
func (*Command) Use ¶ added in v0.1.8
func (c *Command) Use(middlewares ...Middleware)
type CommandSpec ¶ added in v0.1.8
type CommandSpec struct {
ID string `json:"id,omitempty"`
HandlerID string `json:"handler_id,omitempty"`
Path []string `json:"path,omitempty"`
Name string `json:"name"`
Aliases []string `json:"aliases,omitempty"`
UsageLine string `json:"usage_line,omitempty"`
Short string `json:"short,omitempty"`
Long string `json:"long,omitempty"`
Group string `json:"group,omitempty"`
Deprecated string `json:"deprecated,omitempty"`
Hidden bool `json:"hidden,omitempty"`
Runnable bool `json:"runnable,omitempty"`
Examples []string `json:"examples,omitempty"`
Hooks HookSpec `json:"hooks,omitempty"`
HasMiddleware bool `json:"has_middleware,omitempty"`
HasObservers bool `json:"has_observers,omitempty"`
Extensions map[string]any `json:"extensions,omitempty"`
Positionals []PositionalSpec `json:"positionals,omitempty"`
Flags []FlagSpec `json:"flags,omitempty"`
SubCommands []CommandSpec `json:"subcommands,omitempty"`
}
type CommandSurface ¶ added in v0.2.0
type CompletionContext ¶ added in v0.1.8
type CompletionFunc ¶ added in v0.1.8
type CompletionFunc func(ctx CompletionContext) []string
type CompletionResult ¶ added in v0.1.10
type ConfigFlagOptions ¶ added in v0.1.8
type ConfigRuntimeSpec ¶ added in v0.1.8
type DetailedLineCompleter ¶ added in v0.1.10
type DetailedLineCompleter interface {
CompleteLineDetailed(line string, cursor int) []CompletionResult
}
type Dispatcher ¶ added in v0.2.0
type Dispatcher struct {
App *App
}
func (*Dispatcher) Dispatch ¶ added in v0.2.0
func (d *Dispatcher) Dispatch(ctx context.Context, invocation *Invocation) error
type ErrorHandling ¶ added in v0.1.7
type ErrorHandling int
ErrorHandling defines how FlagSet.Parse behaves if the parse fails.
const ( ContinueOnError ErrorHandling = iota // Return a descriptive error. ExitOnError // Call os.Exit(2) or for -h/-help Exit(0). PanicOnError // Call panic with a descriptive error. )
These constants cause FlagSet.Parse to behave as described if the parse fails.
type ErrorHook ¶ added in v0.1.8
type ErrorHook func(ctx HookContext)
type Flag ¶ added in v0.1.7
type Flag struct {
Name string // name as it appears on command line
Shorthand string // single-letter shorthand name
Usage string // help message
Value Value // value as set
DefValue string // default value (as text); for usage message
ID string
Kind string
Category string // logical help group
EnvVars []string
ConfigKeys []string
Enum []string
Required bool
Repeatable bool
Hidden bool
Deprecated string
Example string
CompletionKey string
Completion CompletionFunc
// Extensions carries custom metadata for integrations and tooling.
// Slice and map values are cloned when the library copies metadata, but
// opaque pointer or custom object payloads are shared by reference. Callers
// that need full isolation should store immutable values or clone payloads
// themselves before attaching them here.
Extensions map[string]any
Surfaces map[Surface]FlagSurface
// contains filtered or unexported fields
}
A Flag represents the state of a flag.
func Lookup ¶ added in v0.1.7
Lookup returns the Flag structure of the named command-line flag, returning nil if none exists.
func LookupShort ¶ added in v0.1.7
LookupShort returns the Flag structure of the named shorthand command-line flag, returning nil if none exists.
type FlagSet ¶ added in v0.1.7
type FlagSet struct {
// Usage is the function called when an error occurs while parsing flags.
// The field is a function (not a method) that may be changed to point to
// a custom error handler. What happens after Usage is called depends
// on the ErrorHandling setting; for the command line, this defaults
// to ExitOnError, which exits the program after calling Usage.
Usage func()
// contains filtered or unexported fields
}
A FlagSet represents a set of defined flags. The zero value of a FlagSet has no name and has ContinueOnError error handling.
Flag names must be unique within a FlagSet. An attempt to define a flag whose name is already in use will cause a panic.
var CommandLine *FlagSet
CommandLine is the default set of command-line flags, parsed from os.Args. The top-level functions such as BoolVar, Arg, and so on are wrappers for the methods of CommandLine.
func NewFlagSet ¶ added in v0.1.7
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet
NewFlagSet returns a new, empty flag set with the specified name and error handling property. If the name is not empty, it will be printed in the default usage message and in error messages.
func (*FlagSet) ApplyConfig ¶ added in v0.1.8
func (*FlagSet) Arg ¶ added in v0.1.7
Arg returns the i'th argument. Arg(0) is the first remaining argument after flags have been processed. Arg returns an empty string if the requested element does not exist.
func (*FlagSet) BindConfig ¶ added in v0.1.8
func (*FlagSet) Bool ¶ added in v0.1.7
Bool defines a bool flag with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the flag.
func (*FlagSet) BoolFunc ¶ added in v0.1.7
BoolFunc defines a flag with the specified name and usage string without requiring values. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.
func (*FlagSet) BoolVar ¶ added in v0.1.7
BoolVar defines a bool flag with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the flag.
func (*FlagSet) Duration ¶ added in v0.1.7
func (f *FlagSet) Duration(name string, value time.Duration, usage string, shorthand string) *time.Duration
Duration defines a time.Duration flag with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the flag. The flag accepts a value acceptable to time.ParseDuration.
func (*FlagSet) DurationVar ¶ added in v0.1.7
func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string, shorthand string)
DurationVar defines a time.Duration flag with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the flag. The flag accepts a value acceptable to time.ParseDuration.
func (*FlagSet) ErrorHandling ¶ added in v0.1.7
func (f *FlagSet) ErrorHandling() ErrorHandling
ErrorHandling returns the error handling behavior of the flag set.
func (*FlagSet) Float64 ¶ added in v0.1.7
Float64 defines a float64 flag with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the flag.
func (*FlagSet) Float64Var ¶ added in v0.1.7
func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string, shorthand string)
Float64Var defines a float64 flag with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the flag.
func (*FlagSet) Func ¶ added in v0.1.7
Func defines a flag with the specified name and usage string. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.
func (*FlagSet) Init ¶ added in v0.1.7
func (f *FlagSet) Init(name string, errorHandling ErrorHandling)
Init sets the name and error handling property for a flag set. By default, the zero FlagSet uses an empty name and the ContinueOnError error handling policy.
func (*FlagSet) Int ¶ added in v0.1.7
Int defines an int flag with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the flag.
func (*FlagSet) Int64 ¶ added in v0.1.7
Int64 defines an int64 flag with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the flag.
func (*FlagSet) Int64Var ¶ added in v0.1.7
Int64Var defines an int64 flag with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the flag.
func (*FlagSet) IntVar ¶ added in v0.1.7
IntVar defines an int flag with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the flag.
func (*FlagSet) LookupShort ¶ added in v0.1.7
LookupShort returns the Flag structure of the named shorthand flag, returning nil if none exists.
func (*FlagSet) MarkDeprecated ¶ added in v0.1.8
func (*FlagSet) MarkHidden ¶ added in v0.1.8
func (*FlagSet) MarkRepeatable ¶ added in v0.2.0
func (*FlagSet) MarkRequired ¶ added in v0.1.8
func (*FlagSet) NArg ¶ added in v0.1.7
NArg is the number of arguments remaining after flags have been processed.
func (*FlagSet) Output ¶ added in v0.1.7
Output returns the destination for usage and error messages. os.Stderr is returned if output was not set or was set to nil.
func (*FlagSet) Parse ¶ added in v0.1.7
Parse parses flag definitions from the argument list, which should not include the command name. Must be called after all flags in the FlagSet are defined and before flags are accessed by the program. The return value will be ErrHelp if -help or -h were set but not defined.
func (*FlagSet) PrintDefaults ¶ added in v0.1.7
func (f *FlagSet) PrintDefaults()
PrintDefaults prints, to standard error unless configured otherwise, the default values of all defined command-line flags in the set. See the documentation for the global function PrintDefaults for more information.
func (*FlagSet) SetCategory ¶ added in v0.1.8
func (*FlagSet) SetCompletion ¶ added in v0.1.8
func (f *FlagSet) SetCompletion(name string, fn CompletionFunc)
func (*FlagSet) SetCompletionKey ¶ added in v0.2.0
func (*FlagSet) SetExample ¶ added in v0.1.8
func (*FlagSet) SetExtension ¶ added in v0.1.8
func (*FlagSet) SetOutput ¶ added in v0.1.7
SetOutput sets the destination for usage and error messages. If output is nil, os.Stderr is used.
func (*FlagSet) SetSurface ¶ added in v0.2.0
func (f *FlagSet) SetSurface(name string, surface Surface, override FlagSurface)
func (*FlagSet) String ¶ added in v0.1.7
String defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.
func (*FlagSet) StringVar ¶ added in v0.1.7
StringVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.
func (*FlagSet) TextVar ¶ added in v0.1.7
func (f *FlagSet) TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string, shorthand string)
TextVar defines a flag with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the flag, and p must implement encoding.TextUnmarshaler. If the flag is used, the flag value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p.
func (*FlagSet) Uint ¶ added in v0.1.7
Uint defines a uint flag with specified name, default value, and usage string. The return value is the address of a uint variable that stores the value of the flag.
func (*FlagSet) Uint64 ¶ added in v0.1.7
Uint64 defines a uint64 flag with specified name, default value, and usage string. The return value is the address of a uint64 variable that stores the value of the flag.
func (*FlagSet) Uint64Var ¶ added in v0.1.7
Uint64Var defines a uint64 flag with specified name, default value, and usage string. The argument p points to a uint64 variable in which to store the value of the flag.
func (*FlagSet) UintVar ¶ added in v0.1.7
UintVar defines a uint flag with specified name, default value, and usage string. The argument p points to a uint variable in which to store the value of the flag.
func (*FlagSet) Var ¶ added in v0.1.7
Var defines a flag with the specified name and usage string. The type and value of the flag are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a flag that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.
func (*FlagSet) Visit ¶ added in v0.1.7
Visit visits the flags in lexicographical order, calling fn for each. It visits only those flags that have been set.
func (*FlagSet) VisitAll ¶ added in v0.1.7
VisitAll visits the flags in lexicographical order, calling fn for each. It visits all flags, even those not set.
func (*FlagSet) WarnDeprecated ¶ added in v0.1.8
func (f *FlagSet) WarnDeprecated()
type FlagSpec ¶ added in v0.1.8
type FlagSpec struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Shorthand string `json:"shorthand,omitempty"`
Type string `json:"type,omitempty"`
Kind string `json:"kind,omitempty"`
Usage string `json:"usage,omitempty"`
Default string `json:"default,omitempty"`
Category string `json:"category,omitempty"`
EnvVars []string `json:"env_vars,omitempty"`
ConfigKeys []string `json:"config_keys,omitempty"`
SourceOrder []string `json:"source_order,omitempty"`
Enum []string `json:"enum,omitempty"`
Required bool `json:"required,omitempty"`
Repeatable bool `json:"repeatable,omitempty"`
Hidden bool `json:"hidden,omitempty"`
Deprecated string `json:"deprecated,omitempty"`
Example string `json:"example,omitempty"`
CompletionKey string `json:"completion_key,omitempty"`
SupportsCompletion bool `json:"supports_completion,omitempty"`
Extensions map[string]any `json:"extensions,omitempty"`
}
type FlagSurface ¶ added in v0.2.0
type Getter ¶ added in v0.1.7
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, except the type used by Func.
type HookContext ¶ added in v0.1.8
type Invocation ¶ added in v0.2.0
type Invocation struct {
App *App
Registry *Registry
Root *Command
CommandPath []*Command
Command *Command
RawArgs []string
Args []string
FlagSet *FlagSet
Positionals []string
InheritedFlags []parsedFlagValue
Builtin string
IsREPL bool
Kind InvocationKind
}
Invocation is the shared intermediate representation between CLI/REPL input and execution.
type InvocationKind ¶ added in v0.2.0
type InvocationKind string
const ( InvocationNoop InvocationKind = "noop" InvocationUsage InvocationKind = "usage" InvocationHelp InvocationKind = "help" InvocationBuiltin InvocationKind = "builtin" InvocationCommand InvocationKind = "command" )
type LineCompleter ¶ added in v0.1.10
type Middleware ¶ added in v0.1.8
type Middleware func(ctx MiddlewareContext, next NextFunc) error
type MiddlewareContext ¶ added in v0.1.8
type ObserverFunc ¶ added in v0.1.8
type ObserverFunc func(event Event)
func (ObserverFunc) HandleEvent ¶ added in v0.1.8
func (f ObserverFunc) HandleEvent(event Event)
type PositionalArg ¶ added in v0.1.8
type PositionalArg struct {
Name string
Usage string
Required bool
Variadic bool
Enum []string
Example string
ID string
Kind string
CompletionKey string
Completion CompletionFunc
// Extensions carries custom metadata for integrations and tooling.
// Slice and map values are cloned when the library copies metadata, but
// opaque pointer or custom object payloads are shared by reference. Callers
// that need full isolation should store immutable values or clone payloads
// themselves before attaching them here.
Extensions map[string]any
Surfaces map[Surface]PositionalSurface
}
func (*PositionalArg) SetExtension ¶ added in v0.1.8
func (p *PositionalArg) SetExtension(key string, value any)
func (*PositionalArg) SetSurface ¶ added in v0.2.0
func (p *PositionalArg) SetSurface(surface Surface, override PositionalSurface)
type PositionalSpec ¶ added in v0.1.8
type PositionalSpec struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Usage string `json:"usage,omitempty"`
Required bool `json:"required,omitempty"`
Variadic bool `json:"variadic,omitempty"`
Kind string `json:"kind,omitempty"`
Enum []string `json:"enum,omitempty"`
Example string `json:"example,omitempty"`
CompletionKey string `json:"completion_key,omitempty"`
SupportsCompletion bool `json:"supports_completion,omitempty"`
Extensions map[string]any `json:"extensions,omitempty"`
}
type PositionalSurface ¶ added in v0.2.0
type REPL ¶ added in v0.1.10
type REPLConfig ¶ added in v0.2.0
type REPLConfig struct {
Enabled bool
Prompt string
PromptFunc func(ctx context.Context, repl *REPL) string
Welcome string
Driver REPLDriver
History *REPLHistoryHooks
}
type REPLDriver ¶ added in v0.2.0
type REPLHistoryHooks ¶ added in v0.2.1
type REPLRuntime ¶ added in v0.2.0
type Registry ¶ added in v0.2.0
type Registry struct {
App *App
Root *Command
ByPath map[string]*Command
Aliases map[string]*Command
Builtins map[string]BuiltinHandler
// contains filtered or unexported fields
}
Registry is a read-only index over the shared command tree.
func (*Registry) Builtin ¶ added in v0.2.0
func (r *Registry) Builtin(name string) (BuiltinHandler, bool)
func (*Registry) ResolveCommand ¶ added in v0.2.0
func (*Registry) VisibleBuiltins ¶ added in v0.2.0
type Resolver ¶ added in v0.2.0
func (*Resolver) ResolveCompletion ¶ added in v0.2.0
type Runtime ¶ added in v0.2.0
func DefaultRuntime ¶ added in v0.2.0
type TerminalREPLDriver ¶ added in v0.2.0
type TerminalREPLDriver struct{}
type Value ¶ added in v0.1.7
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.
Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.