Documentation
¶
Overview ¶
Package cli builds the Cobra tree of a tool by contract.md section 9.2: Root makes the root with the persistent --format flag and the doctor subcommand, Group makes a command that only holds subcommands, Command makes a leaf. Execute runs the tree with injected streams: each leaf runs inside work.Command, so one command.run line ends the run; a returned error or a panic becomes the error envelope on stderr; the classed error comes back to the caller so lifecycle.Run exits with its code.
func main() {
id := identity.New("myapp")
root := cli.Root(id, cli.Short("Messages from the terminal"))
msg := cli.Group(root, "messages", "Read and search messages")
cli.Command(msg, "search [query]", "Search messages", search, cli.Formats(cli.JSON, cli.JSONL, cli.Text))
lifecycle.Run(id, func(ctx context.Context, _ *slog.Logger) error {
return cli.Execute(ctx, root, os.Args[1:], os.Stdin, os.Stdout, os.Stderr)
}, lifecycle.Heartbeat(false))
}
The second argument of Command is the Use line: the name, then the argument synopsis. stdout carries the result and nothing else. Help, the error envelope and the app's prompts and progress go to stderr; the runner reaches the streams through Stdin, Stderr and ReadSecret, its flags through Flags and its own path through CommandPath, all from ctx. Log lines go where logging sends them (section 5).
Index ¶
- Constants
- func Command(parent *cobra.Command, use, short string, run Runner, opts ...CommandOption) *cobra.Command
- func CommandPath(ctx context.Context) string
- func Execute(ctx context.Context, root *cobra.Command, args []string, stdin io.Reader, ...) error
- func Flags(ctx context.Context) *pflag.FlagSet
- func Group(parent *cobra.Command, name, short string) *cobra.Command
- func IdentityOf(cmd *cobra.Command) identity.Identity
- func ReadSecret(ctx context.Context, prompt string) (string, error)
- func Root(id identity.Identity, opts ...Option) *cobra.Command
- func Stderr(ctx context.Context) io.Writer
- func Stdin(ctx context.Context) io.Reader
- type CommandOption
- type Format
- type Option
- type Output
- type Runner
Constants ¶
const FormatFlag = "format"
FormatFlag is the name of the persistent output flag.
Variables ¶
This section is empty.
Functions ¶
func Command ¶
func Command(parent *cobra.Command, use, short string, run Runner, opts ...CommandOption) *cobra.Command
Command makes a leaf under parent and returns it; flags, Long, Example and Args are set on the returned command. use is Cobra's Use line, the name followed by the argument synopsis ("set-key [provider]"); the command's name is its first word. Execute runs run inside work.Command, with the selected format checked against the declaration.
func CommandPath ¶
CommandPath returns the full path of the leaf whose runner holds ctx, with the tool's name ("myapp auth set-key"), for a next step that names the command to run. Outside a runner it is "".
func Execute ¶
func Execute(ctx context.Context, root *cobra.Command, args []string, stdin io.Reader, stdout, stderr io.Writer) error
Execute runs the tree once with the given streams and arguments (os.Args[1:] in main). The result goes to stdout; help and the error envelope go to stderr. It returns nil on success, else the classed error after writing the envelope: main returns it from the function lifecycle.Run runs, and Run exits with failure.ExitCode of it. The logger comes from ctx (logging.FromContext); Run puts it there. A cancelled ctx ends the command with the class cancelled (exit 130) once the runner returns ctx.Err(). A Cobra error before any runner ran (unknown command or flag, wrong argument count) is a usage error with Cobra's message. Every envelope carries details.command, the path below the root as command.run has it, unless the error set its own. A tree runs once, because Cobra keeps the flag values and the leaf contexts of a run in the tree: a second Execute on the same root panics; tests build a tree per run.
func Flags ¶
Flags returns the flag set of the leaf whose runner holds ctx, for Changed, GetString and the rest, so a runner needs no reference to its own command. Outside a runner it is nil.
func Group ¶
Group makes a command that only holds subcommands, at any depth. Run without one of them it is a usage error that lists them.
func IdentityOf ¶
IdentityOf returns the identity the tree's root was made with; the zero Identity for a tree not made by Root.
func ReadSecret ¶
ReadSecret reads one line from stdin without echo, for a key or a password. When stdin is a terminal it writes prompt to Stderr(ctx), turns echo off while the line is typed, restores the terminal and writes a newline, since Enter printed none. When stdin is not a terminal it returns the first line of stdin, without a prompt. The newline is not part of the result. A cancelled ctx ends the read with ctx.Err() and the terminal restored, so a prompt under lifecycle.Run ends on Ctrl+C. End of input before any byte is a usage failure.
func Root ¶
Root makes the root command of a tool from its identity: the tool's name is id.Name. It carries the persistent --format flag, the doctor subcommand and the help command; Cobra's completion command is off. Run with no subcommand is a usage error that lists the commands, and so is `help` with a command that does not exist.
Types ¶
type CommandOption ¶
type CommandOption func(*commandOptions)
CommandOption configures Command.
func Formats ¶
func Formats(formats ...Format) CommandOption
Formats declares the formats a command accepts; the first is its default. Without it a command accepts json only. It panics on an empty list or a repeated format.
type Format ¶
type Format string
Format is an output format a command declares and the user selects with --format.
type Option ¶
Option configures Root.
type Output ¶
type Output interface {
// Format is the format the user selected, or the command's default.
Format() Format
// JSON writes v as one compact JSON object followed by a newline. A second call is an
// internal failure: a json result is one object.
JSON(v any) error
// JSONL writes v as one JSON line.
JSONL(v any) error
// Text writes fmt.Sprintf(format, args...) as one write.
Text(format string, args ...any) error
}
Output is what a runner writes its result through. Every write goes to stdout at once; nothing else writes there. The runner reads Format and uses the matching method.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package clitest runs a tree made with cli in a test: one call gives the exit code, stdout and stderr of a command, and Lines gives the log lines it wrote.
|
Package clitest runs a tree made with cli in a test: one call gives the exit code, stdout and stderr of a command, and Lines gives the log lines it wrote. |