Documentation
¶
Overview ¶
Package xli builds command-line interfaces as a tree of commands whose handlers are middleware.
A Command declares its name, its flg.Flags, its arg.Args and its subcommands. Command.Run parses a command line against the tree, stores what it parsed in the flags and arguments, and calls the handlers of the commands on the path, from the root down:
root := &xli.Command{
Name: "app",
Flags: flg.Flags{&flg.Switch{Name: "verbose", Alias: 'v'}},
Commands: xli.Commands{
{
Name: "greet",
Args: arg.Args{&arg.String{Name: "NAME"}},
Handler: xli.OnRun(func(ctx context.Context, cmd *xli.Command, next xli.Next) error {
cmd.Printf("hello, %s\n", arg.MustGet[string](cmd, "NAME"))
return next(ctx)
}),
},
},
Handler: xli.RequireSubcommand(),
}
err := root.Run(ctx, os.Args[1:])
What is intended, and easy to trip on ¶
The following are by design, and each is a surprise if it is not known.
A handler is middleware. It is given next, and the subcommand runs only if the handler calls next(ctx): Run does not call it on the handler's behalf. A parent sets up what its subcommands share -- a configuration, a client, a span -- before next, and acts on the result after it; one that returns without calling next ends the run there. A command with no handler calls next, and Chain puts several handlers on one command, each of which calls the next in turn.
The handler of every command on the path runs, in a mode that says why: mode.Run for the command named last, mode.Run with mode.Pass for the commands on the way to it, and mode.Help and mode.Tab for --help and shell completion, which walk the same tree. OnRun, OnRunPass, OnHelp and OnTab call a function in their mode and next in any other.
Positions are strict. A command's flags and arguments are its own: they are not given to its parent or to its subcommand, and its flags come before its arguments. In `app --verbose deploy --force web`, --verbose is app's and --force and web are deploy's; `app deploy web --force` is ErrFlagAfterArg. It is what keeps a deep tree unambiguous.
A tree is run once. Run writes into the tree it is given: the values it parses into the flags and arguments, each command's parent, and the IO a subcommand inherits. Build the tree once per process, as a command line is run once per process; a test that runs two command lines builds two trees.
A flag's Default and Value are not the same thing. Default is the value you configured, and the framework never writes it; Value is what the user gave, and only the framework writes it. flg.Get and arg.Get report whether the user gave a value; flg.MustGet and arg.MustGet return it, or else the Default, and panic if there is neither.
An AI agent gets more from --help than a person does. --help-all prints the help of the command and of every command below it, and when the environment says an agent runs the command -- AI_AGENT, or an agent's own variable such as CLAUDECODE, CODEX_CI or GEMINI_CLI -- --help and -h print that too: a person reads one command's help and asks for the next, and an agent would ask one level at a time down a tree it can be given whole. A tree of hundreds of commands is more than an agent takes in at once, so past 16 KiB they print the command's own help and a map of every command below it, a line for each shape of them -- "app {user,team} {get,ls}" -- and the agent asks the one it wants. XLI_AGENT=0 says no agent runs the command and XLI_AGENT=1 says one does; a test of what the help says sets it, since an agent may be what runs the test.
More ¶
The guides under docs/ in the repository cover commands, flags, arguments, completion and testing. Package github.com/lesomnus/xli/xlitest runs a command line in a test, and the optional module github.com/lesomnus/xli/cfg reads a configuration struct from a file, the environment and these flags.
Index ¶
- Variables
- func Into(ctx context.Context, cmd *Command) context.Context
- func WriteMan(w io.Writer, c *Command, section int) error
- func WriteMarkdown(w io.Writer, c *Command) error
- type ArgError
- type Command
- func (c *Command) GetArgs() arg.Args
- func (c *Command) GetFlags() flg.Flags
- func (c *Command) GetName() string
- func (c *Command) HasParent() bool
- func (c *Command) Parent() *Command
- func (c *Command) Print(vs ...any) (int, error)
- func (c *Command) PrintHelp(w io.Writer) error
- func (c *Command) Printf(format string, vs ...any) (int, error)
- func (c *Command) Println(vs ...any) (int, error)
- func (c *Command) Root() *Command
- func (c *Command) Run(ctx context.Context, args []string) error
- func (c *Command) Scan(vs ...any) (int, error)
- func (c *Command) Scanf(format string, vs ...any) (int, error)
- func (c *Command) Scanln(vs ...any) (int, error)
- func (c *Command) String() string
- func (c *Command) Tree() []*Command
- type Commands
- type FlagError
- type Handler
- func Chain(hs ...Handler) Handler
- func Handle(f HandlerFunc) Handler
- func On(m mode.Mode, f HandlerFunc) Handler
- func OnExact(m mode.Mode, f HandlerFunc) Handler
- func OnF(f func(m mode.Mode) bool, a HandlerFunc) Handler
- func OnHelp(f HandlerFunc) Handler
- func OnHelpPass(f HandlerFunc) Handler
- func OnRun(f HandlerFunc) Handler
- func OnRunPass(f HandlerFunc) Handler
- func OnTab(f HandlerFunc) Handler
- func OnTabPass(f HandlerFunc) Handler
- func RequireSubcommand() Handler
- type HandlerFunc
- type Next
- type UsageError
Constants ¶
This section is empty.
Variables ¶
var ( // ErrUnknownFlag is a flag the command does not declare. A flag of a // parent or a subcommand is unknown to this one: positions are strict. ErrUnknownFlag = errors.New("unknown flag") // ErrNoFlagValue is a flag that takes a value given none. ErrNoFlagValue = errors.New("no value is given") // ErrFlagRequired is a flag declared Required that was not given. ErrFlagRequired = errors.New("required flag not set") // ErrFlagConflict is two flags of one of the command's Exclusive groups // given together. ErrFlagConflict = errors.New("flags cannot be used together") // ErrFlagAfterArg is a flag given after an argument of the same command. ErrFlagAfterArg = errors.New("flag must come before arguments") // ErrUnknownCmd is a word that is neither an argument nor the name of a // subcommand. ErrUnknownCmd = errors.New("unknown subcommand") // ErrTooManyArgs is an argument more than the command declares. ErrTooManyArgs = errors.New("too many arguments") // ErrNeedArgs is a required argument not given. ErrNeedArgs = errors.New("required argument not given") // ErrNeedCmd is a command run without the subcommand it requires; see // [RequireSubcommand]. ErrNeedCmd = errors.New("subcommand is required") )
What can be wrong with a command line. Run returns them wrapped in a UsageError that names the command, and a mistake about one token also in a FlagError or an ArgError that names it, so they are matched with errors.Is.
Functions ¶
Types ¶
type ArgError ¶
type ArgError struct {
// contains filtered or unexported fields
}
ArgError is a mistake about one word of the command line that is not a flag: an argument, or a subcommand that is not there, with the ones it may have been meant to be.
func (*ArgError) Error ¶
Error is the word as it was written, what is wrong with it, and what it may have been meant to be.
func (*ArgError) Unwrap ¶
Unwrap is what is wrong with the word, such as ErrUnknownCmd.
type Command ¶
type Command struct {
// Category groups the command under a heading in its parent's help and
// completion.
Category string
// Name is the word that selects the command on the command line, and
// Aliases are other words that do.
Name string
Aliases []string
// Brief is a line saying what the command does, shown beside its name;
// Synop is the longer description its own help shows.
Brief string
Synop string
// Examples are command lines that use the command, each with a comment
// above it if it needs one. They end its help and are in the generated
// documentation. The blank lines around them and the indentation they all
// share are not part of them, so a raw string can be indented with the
// code around it.
Examples string
// Flags are the command's own flags, and Args its arguments, in order.
// Neither is given to its parent or its subcommands.
Flags flg.Flags
Args arg.Args
// Commands are the commands below this one.
Commands Commands
// Exclusive lists groups of flag names of which at most one may be given,
// e.g. {{"json", "yaml"}}. Run returns ErrFlagConflict otherwise.
Exclusive [][]string
// Handler is the command's middleware; nil is one that calls next.
Handler Handler
// Hidden omits the command from its parent's help and completion; it can
// still be run by name.
Hidden bool
// The command's input and outputs. Run sets the root's to os.Stdin,
// os.Stdout and os.Stderr where they are nil, and a subcommand's to its
// parent's where they are nil.
io.ReadCloser
io.Writer
ErrWriter io.Writer
// contains filtered or unexported fields
}
Command is a node of the command tree: what it is called, what it takes, the commands below it, and the handler that runs on the way through it. A tree is built once and run once; see the package documentation.
func NewCmdCompletion ¶
func NewCmdCompletion() *Command
NewCmdCompletion returns a "completion" command whose subcommands ("zsh", "bash", "fish") print the completion script for the root command.
func (*Command) GetName ¶
GetName is Name. GetName, GetFlags and GetArgs are what the frm package knows of a command; see xmd.Command.
func (*Command) HasParent ¶
HasParent reports whether the command is below another in the run: Run sets the parent of each command on the path it takes.
func (*Command) Parent ¶
Parent is the command above this one in the run, or nil for the root or a command not on the path of a run.
func (*Command) PrintHelp ¶
PrintHelp writes the command's help to w: its usage line, its description, its arguments and flags, the commands below it by category, and its examples. The help is xli's; there is no template to replace it with (ROADMAP, Phase 3).
func (*Command) Run ¶
Run runs the command line args -- usually os.Args[1:] -- against the tree below c.
It parses the whole line first, into the flags and arguments of every command on the path -- calling their handlers -- and returns a UsageError for what does not fit before any command's handler runs. Then it calls c's handler, and a subcommand's handler runs only when its parent's calls next: Run does not call it on the handler's behalf. With --help or -h on the line it runs in help mode, and the help of the command it was given to is printed when that command's handler calls next. --help-all prints the help of every command below it as well, and so do --help and -h when an AI agent runs the command and that is not more than it takes in at once; see the package documentation. A line from a generated completion script runs in completion mode.
Run writes into the tree: the values it parses, each command's parent, and the IO a subcommand inherits. A tree is run once.
type Commands ¶
type Commands []*Command
Commands are the commands below one command.
func (Commands) ByCategory ¶
ByCategory is cs grouped by Category, each group in the order its first command appears.
func (Commands) Get ¶
Get is the command called name, by its name or an alias; nil if there is none.
type FlagError ¶
type FlagError struct {
// contains filtered or unexported fields
}
FlagError is a mistake about one flag, saying it as it was written, with the flags it may have been meant to be.
func (*FlagError) Error ¶
Error is the flag as it was written, what is wrong with it, and what it may have been meant to be.
func (*FlagError) Unwrap ¶
Unwrap is what is wrong with the flag, such as ErrUnknownFlag.
type Handler ¶
Handler is a command's middleware. Run calls the handler of every command on the path from the root, each through the next its parent's handler calls; see the package documentation.
func Chain ¶
Chain is hs as one handler: each is called with a next that calls the one after it, and the last with the command's next. A handler in the chain that does not call next ends the run there, as one alone would.
func Handle ¶
func Handle(f HandlerFunc) Handler
Handle is f as a Handler, in every mode. Most handlers want one mode, and OnRun and the other On functions are those.
func On ¶
func On(m mode.Mode, f HandlerFunc) Handler
On calls f when the mode of the run has every bit of m set -- On(mode.Run, f) in mode.Run and in mode.Run|mode.Pass -- and next otherwise.
func OnExact ¶
func OnExact(m mode.Mode, f HandlerFunc) Handler
OnExact calls f when the mode of the run is m, and next otherwise.
func OnF ¶
func OnF(f func(m mode.Mode) bool, a HandlerFunc) Handler
OnF calls a when f reports true for the mode of the run, and next otherwise. When a is called, it is a that calls next.
func OnHelp ¶
func OnHelp(f HandlerFunc) Handler
OnHelp calls f when --help is given to the command, and next otherwise.
func OnHelpPass ¶
func OnHelpPass(f HandlerFunc) Handler
OnHelpPass calls f when --help is given to a command below this one, and next otherwise.
func OnRun ¶
func OnRun(f HandlerFunc) Handler
OnRun calls f when the command is the one the command line names last, and so the one being run; on the way to a subcommand, and for help and completion, it calls next.
func OnRunPass ¶
func OnRunPass(f HandlerFunc) Handler
OnRunPass calls f when the command is on the way to the one being run -- where a parent sets up what its subcommands share -- and next otherwise.
func OnTab ¶
func OnTab(f HandlerFunc) Handler
OnTab calls f when the shell asks the command for completions, and next otherwise; the candidates go to tab.From of the context.
func OnTabPass ¶
func OnTabPass(f HandlerFunc) Handler
OnTabPass calls f when the shell asks a command below this one for completions, and next otherwise.
func RequireSubcommand ¶
func RequireSubcommand() Handler
RequireSubcommand is a handler for a command that does nothing of its own: run with no subcommand, it returns a UsageError of ErrNeedCmd, and otherwise it calls next.
type HandlerFunc ¶
HandlerFunc is a handler as a function: cmd is the command it is the handler of, and next is the rest of the run, which it calls when, and if, the run is to go on.
type Next ¶
Next runs what comes after a handler: the command's next handler, if it was given several with Chain, or else the subcommand. The context it is called with is the one the rest of the run sees. A handler that does not call it ends the run there.
type UsageError ¶
type UsageError struct {
// Cmd is the command whose flags, arguments, or subcommands were misused.
Cmd *Command
Err error
}
UsageError reports that the command line does not match what a command declares: an unknown flag or subcommand, a missing or malformed value, a missing required flag or argument, and so on. It identifies the command the mistake was made on, so callers can point the user at that command's help:
var ue *xli.UsageError
if errors.As(err, &ue) {
ue.Cmd.PrintHelp(os.Stderr)
}
Errors returned by flag handlers are treated as invalid flag values and reported as UsageErrors too. Errors returned by command handlers are passed through as is.
func (*UsageError) Error ¶
func (e *UsageError) Error() string
Error is the path of the command and what is wrong.
func (*UsageError) Path ¶
func (e *UsageError) Path() string
Path returns the space-separated command path from the root to Cmd, e.g. "app deploy".
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package arg is the positional arguments of an xli command: typed, declared in order on the command they belong to, and read back by name.
|
Package arg is the positional arguments of an xli command: typed, declared in order on the command they belong to, and read back by name. |
|
cfg
module
|
|
|
Package flg is the flags of an xli command: typed, declared on the command they belong to, and read back by name.
|
Package flg is the flags of an xli command: typed, declared on the command they belong to, and read back by name. |
|
Package frm is the path of a run, as frames: one for each command from the root to the one being run, which a handler finds in its context.
|
Package frm is the path of a run, as frames: one for each command from the root to the one being run, which a handler finds in its context. |
|
internal
|
|
|
comp
Package comp holds the wire protocol shared between xli's completion machinery and its shell integration: the argv tag that switches a normal run into the completion path, the field separator used on each emitted line, and the Writer that emits them.
|
Package comp holds the wire protocol shared between xli's completion machinery and its shell integration: the argv tag that switches a normal run into the completion path, the field separator used on each emitted line, and the Writer that emits them. |
|
examples/completion
command
|
|
|
suggest
Package suggest finds likely intended names for a mistyped one.
|
Package suggest finds likely intended names for a mistyped one. |
|
Package mode is why a command line is run: to run a command, to print its help, or to complete it in a shell.
|
Package mode is why a command line is run: to run a command, to print its help, or to complete it in a shell. |
|
Package tab is where completion candidates go: a handler running for shell completion finds a Tab in its context and offers values to it.
|
Package tab is where completion candidates go: a handler running for shell completion finds a Tab in its context and offers values to it. |
|
Package xlitest provides helpers for testing commands built with xli.
|
Package xlitest provides helpers for testing commands built with xli. |
|
Package xmd is what the frm package knows of a command, so that frm need not import xli, which imports it.
|
Package xmd is what the frm package knows of a command, so that frm need not import xli, which imports it. |