xli

package module
v0.0.0-...-4ce270c Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: Apache-2.0 Imports: 22 Imported by: 19 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

xli

Build your CLI like a middleware.

xli is a small, opinionated CLI framework for Go. Commands form a tree, each command is a middleware that decides whether to descend into its subcommand, and context is nested as you go down the tree.

Status: pre-1.0, API not yet frozen. See ROADMAP.md for the path to a stable release.

Features

  • Middleware handlers — every command receives a next function and chooses if/when to invoke its subcommand, so cross-cutting setup (auth, config, tracing) lives in parent commands.
  • Nested context — each subcommand nests context.Context; values flow down the tree.
  • Strict flag/arg positioning — a command owns only its own flags and args; flags must come before args. This keeps parsing unambiguous across deep trees.
  • Typed flags and arguments — string, bool (switch), int/uint families, float32/float64, time.Duration, and choices (enums), plus variadic arguments and repeatable ([]string) flags.
  • Defaults, required & mutually exclusive flags — a clear contract between the configured default and the value the user actually provided.
  • Helpful errors — usage errors name the command they occurred on and suggest close matches ("did you mean …?").
  • Generated help, shell completion (zsh, bash, fish), and Markdown / man page generation. Commands and flags can be hidden from all three.
  • Help an AI agent reads in one call — --help-all prints the help of every command below as well, and an agent gets it from --help when it fits.
  • Configuration (optional) — the cfg module loads your own struct from a YAML file, the environment and bound flags, records where every value came from, re-reads rotated secret files and reloads the file (cfg/DESIGN.md).
  • Testing helpers — the xlitest package runs a command against in-memory IO and decodes completion output, so tests assert on results, not wiring.

Install

go get github.com/lesomnus/xli

Requires Go 1.24+.

Quick start

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/lesomnus/xli"
	"github.com/lesomnus/xli/arg"
	"github.com/lesomnus/xli/flg"
)

func main() {
	greeting := "Hello"
	cmd := &xli.Command{
		Name:  "greet",
		Brief: "greet someone",
		Flags: flg.Flags{
			&flg.String{Name: "greeting", Alias: 'g', Brief: "the greeting to use", Default: &greeting},
		},
		Args: arg.Args{
			&arg.String{Name: "NAME", Brief: "who to greet"},
		},
		Handler: xli.OnRun(func(ctx context.Context, cmd *xli.Command, next xli.Next) error {
			g := flg.MustGet[string](cmd, "greeting")
			name := arg.MustGet[string](cmd, "NAME")
			cmd.Printf("%s, %s!\n", g, name)
			return next(ctx)
		}),
	}

	if err := cmd.Run(context.Background(), os.Args[1:]); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
$ greet World
Hello, World!
$ greet --greeting=Hi World
Hi, World!
$ greet --help

Documentation

  • docs/commands.md — the command tree, middleware handlers, execution modes, strict positioning, and completion.
  • docs/flags.md — flag types, the default/parsed contract, required flags, categories, and value completion.
  • docs/arguments.md — positional/variadic arguments, the default/parsed contract, and value completion.
  • docs/completion.md — shell completion: setup, the tab.Tab sink (values, descriptions, groups, file/dir completion), and OnTab handlers.
  • docs/testing.md — testing your commands with the xlitest package: running, asserting output/errors/parsed values, stdin, and decoding shell completion.
  • cfg/DESIGN.md — the optional configuration module (github.com/lesomnus/xli/cfg): layers and precedence, names, references and secrets, binding flags, origins, validation and reload.

Concepts

Handlers are middleware

A Handler receives the command and a next function. To run a subcommand you must call next(ctx); this is what makes parent commands behave like middleware.

root := &xli.Command{
	Name: "app",
	// Runs while passing through `app` on the way to a subcommand.
	Handler: xli.OnRunPass(func(ctx context.Context, cmd *xli.Command, next xli.Next) error {
		ctx = withConfig(ctx) // set up shared state...
		return next(ctx)      // ...then descend into the subcommand.
	}),
	Commands: xli.Commands{
		subCmd(),
	},
}

Compose handlers with xli.Chain(...).

Execution modes

The same command tree is walked for different purposes. Handlers are gated on the mode so you only do work when it is relevant:

Helper Runs when
OnRun executing this command as the target
OnRunPass passing through on the way to a subcommand
OnHelp rendering --help
OnTab producing shell completions

There are matching helpers in the flg and arg packages for flag/argument handlers (e.g. flg.OnTab to provide completion candidates for a flag value, optionally grouped with tab.Group).

Flags and arguments

Declare typed flags and positional arguments; read them back with Get/MustGet (or VisitP, Find for the parent chain).

Flags: flg.Flags{
	&flg.Switch{Name: "verbose", Alias: 'v'},
	&flg.Int{Name: "retries", Default: &three},
	&flg.String{Name: "token", Required: true},
},
Args: arg.Args{
	&arg.String{Name: "SRC"},
	&arg.RestStrings{Name: "DST"}, // variadic
},

Default vs. provided value. Default is the configured fallback and is never modified by the framework; Value holds what the user actually passed.

  • Get / VisitP / Find report whether the user provided the flag.
  • MustGet / MustFind return the provided value, else the default, else panic.
if v, ok := flg.Get[string](cmd, "token"); ok {
	// the user explicitly passed --token
}
token := flg.MustGet[string](cmd, "token") // provided value or default

A Required flag that is absent makes Run return ErrFlagRequired (help and completion are exempt).

Help and completion

--help / -h render a generated help message (usage line, arguments, flags with defaults, subcommands grouped by category, and the command's Examples). --help-all prints it for every command below as well, and so does --help when an AI agent runs the command and it is not too long (see below).

Add shell completion by mounting the completion command and sourcing its script:

Commands: xli.Commands{
	xli.NewCmdCompletion(),
},
source <(app completion zsh)    # zsh  (~/.zshrc)
source <(app completion bash)   # bash (~/.bashrc)
app completion fish | source    # fish (~/.config/fish/config.fish)
By design

Five things are deliberate, and each is a surprise if it is not known:

  • next is yours to call. Run does not run a subcommand on a handler's behalf: a handler that returns without calling next(ctx) ends the run there. A command with no handler calls next.
  • Positions are strict. A command's flags and arguments are its own, 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.
  • A tree is run once. Run writes into the tree: the values it parses, each command's parent, and the IO a subcommand inherits. Build the tree once per process; a test that runs two command lines builds two trees.
  • A flag's handler runs while the line is parsed, before any command's handler, in the mode its command's handler will see: flg.OnRun for a flag of the command being run, flg.OnRunPass for one of a command on the way to it.
  • An AI agent gets more from --help. 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 what --help-all does, the help of every command below too, so that an agent learns a tree in one call rather than one per level. When that is more than 16 KiB, they print the command's own help and a map of every command below it, with commands whose commands below have the same names on one line (app {user,team} {get,ls}). XLI_AGENT=0 says no agent runs the command, and XLI_AGENT=1 says one does.

License

See the repository for license details.

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

Constants

This section is empty.

Variables

View Source
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

func Into

func Into(ctx context.Context, cmd *Command) context.Context

Into is ctx carrying cmd, for From.

func WriteMan

func WriteMan(w io.Writer, c *Command, section int) error

WriteMan writes a man page in roff format for c, documenting c and all of its visible subcommands. section is the manual section, usually 1. Hidden commands and flags are left out.

func WriteMarkdown

func WriteMarkdown(w io.Writer, c *Command) error

WriteMarkdown writes a Markdown reference for c and all of its visible subcommands: one section per command with its usage, description, arguments, options, examples, and subcommands. Hidden commands and flags are left out.

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

func (e *ArgError) Error() string

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

func (e *ArgError) Unwrap() error

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 From

func From(ctx context.Context) *Command

From is the command ctx carries, or an empty Command if it carries none.

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

func (c *Command) GetArgs() arg.Args

GetArgs is Args.

func (*Command) GetFlags

func (c *Command) GetFlags() flg.Flags

GetFlags is Flags.

func (*Command) GetName

func (c *Command) GetName() string

GetName is Name. GetName, GetFlags and GetArgs are what the frm package knows of a command; see xmd.Command.

func (*Command) HasParent

func (c *Command) HasParent() bool

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

func (c *Command) Parent() *Command

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

func (c *Command) Print(vs ...any) (int, error)

Print writes to the command's Writer as fmt.Fprint does.

func (*Command) PrintHelp

func (c *Command) PrintHelp(w io.Writer) error

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

func (c *Command) Printf(format string, vs ...any) (int, error)

Printf writes to the command's Writer as fmt.Fprintf does.

func (*Command) Println

func (c *Command) Println(vs ...any) (int, error)

Println writes to the command's Writer as fmt.Fprintln does.

func (*Command) Root

func (c *Command) Root() *Command

Root is the command at the top of the run.

func (*Command) Run

func (c *Command) Run(ctx context.Context, args []string) error

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.

func (*Command) Scan

func (c *Command) Scan(vs ...any) (int, error)

Scan reads from the command's ReadCloser as fmt.Fscan does.

func (*Command) Scanf

func (c *Command) Scanf(format string, vs ...any) (int, error)

Scanf reads from the command's ReadCloser as fmt.Fscanf does.

func (*Command) Scanln

func (c *Command) Scanln(vs ...any) (int, error)

Scanln reads from the command's ReadCloser as fmt.Fscanln does.

func (*Command) String

func (c *Command) String() string

String is the command's name and aliases, separated by commas.

func (*Command) Tree

func (c *Command) Tree() []*Command

Tree is the path of the run from the root to this command, the root first.

type Commands

type Commands []*Command

Commands are the commands below one command.

func (Commands) ByCategory

func (cs Commands) ByCategory() []Commands

ByCategory is cs grouped by Category, each group in the order its first command appears.

func (Commands) Get

func (cs Commands) Get(name string) *Command

Get is the command called name, by its name or an alias; nil if there is none.

func (Commands) Visible

func (cs Commands) Visible() Commands

Visible returns the commands that are not hidden.

func (Commands) WithCategory

func (cs Commands) WithCategory(name string, vs ...*Command) Commands

WithCategory is cs with vs appended, each put in the category name.

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

func (e *FlagError) Error() string

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

func (e *FlagError) Unwrap() error

Unwrap is what is wrong with the flag, such as ErrUnknownFlag.

type Handler

type Handler interface {
	Handle(ctx context.Context, cmd *Command, next Next) error
}

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

func Chain(hs ...Handler) Handler

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

type HandlerFunc func(ctx context.Context, cmd *Command, next Next) error

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

type Next func(ctx context.Context) error

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".

func (*UsageError) Unwrap

func (e *UsageError) Unwrap() error

Unwrap is what is wrong.

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.
lex
suggest
Package suggest finds likely intended names for a mistyped one.
Package suggest finds likely intended names for a mistyped one.
x
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.

Jump to

Keyboard shortcuts

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