cli

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 21 Imported by: 1 module, 0 packages

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.

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

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

func CommandPath(ctx context.Context) string

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

func Flags(ctx context.Context) *pflag.FlagSet

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

func Group(parent *cobra.Command, name, short string) *cobra.Command

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

func IdentityOf(cmd *cobra.Command) identity.Identity

IdentityOf returns the identity the tree's root was made with; the zero Identity for a tree not made by Root.

func ReadSecret

func ReadSecret(ctx context.Context, prompt string) (string, error)

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

func Root(id identity.Identity, opts ...Option) *cobra.Command

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.

func Stderr

func Stderr(ctx context.Context) io.Writer

Stderr returns the error stream Execute was given, for a runner's prompts, progress and diagnostics; stdout stays the result. Outside Execute it is os.Stderr.

func Stdin

func Stdin(ctx context.Context) io.Reader

Stdin returns the input stream Execute was given, for a runner that reads its input; the ctx is the runner's. Outside Execute it is os.Stdin.

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.

const (
	JSON  Format = "json"
	JSONL Format = "jsonl"
	Text  Format = "text"
)

The formats of contract.md section 9.2.

type Option

type Option func(*cobra.Command)

Option configures Root.

func Long

func Long(text string) Option

Long sets the description shown by `tool --help` instead of Short.

func Short

func Short(text string) Option

Short sets the one-line description shown at the top of the root's help.

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.

type Runner

type Runner func(ctx context.Context, args []string, out Output) error

Runner is a leaf's function: args are the positional arguments after Cobra parsed the flags; out writes the result in the selected format. The error it returns is classed by failure and becomes the envelope and the exit code.

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.

Jump to

Keyboard shortcuts

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