cli

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 15 Imported by: 0

README

cli

CI CodeQL Coverage Mutation Documentation Go Reference Release Go License

cli is an explicit, typed Go command framework for developer tools, distributable binaries, CI, containers, ECS tasks, migrations, imports, backfills, diagnostics, and repair commands.

It provides immutable command trees, typed input, deterministic parsing, lifecycle middleware, cancellation, stable errors and exits, human/JSON/quiet output, generated help and references, shell completion, and an in-process test harness. It deliberately does not provide a service container, reflection-based discovery, global registration, configuration loading, prompts, logging, or telemetry exporters.

Install

go get github.com/faustbrian/go-cli

Go 1.25 or newer is required.

Minimal command

package main

import (
	"context"
	"os"

	cli "github.com/faustbrian/go-cli"
)

func run(ctx context.Context, argv []string) int {
	name := cli.StringArgument("name").Description("person to greet")
	root := cli.NewCommand(
		"hello",
		cli.WithArguments(name),
		cli.WithHandler(func(_ context.Context, invocation cli.Invocation) error {
			return invocation.Output().SetData("Hello, " + name.Get(invocation.Input()) + "!")
		}),
	)
	application, err := cli.Compile(root)
	if err != nil {
		return 70
	}
	result := application.Run(ctx, cli.Request{
		Args: argv, Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr,
	})

	return result.ExitCode
}

func main() {
	os.Exit(run(context.Background(), os.Args[1:]))
}

Service processes that deliberately do not publish shell completion may call RunCommand instead. It preserves normal command, help, version, typed input, lifecycle, output, and exit behavior while treating the hidden completion protocol as an ordinary command token.

One-binary services that need only direct commands, command-local typed options, help, version, stable errors, and bounded output can use CompileCommandSet. This avoids linking argument, nested-command, lifecycle-hook, completion, and reference-generation machinery that the process does not expose:

application, err := cli.CompileCommandSet(cli.CommandSet{
	Name:    "postal",
	Version: "1.2.3",
	Commands: []cli.CommandSpec{{
		Name:    "serve",
		Summary: "serve Postal requests",
		Handler: serve,
	}},
})

CommandSpec.Options uses the same typed option bindings and parser contract as Command, while deliberately excluding persistent options and option groups from the bounded service-process surface.

os.Exit stays in main; handlers and library code return errors. Dependencies are ordinary constructor parameters or captured closures:

func NewRepairCommand(repository *Repository) *cli.Command {
	return cli.NewCommand("repair", cli.WithHandler(
		func(ctx context.Context, invocation cli.Invocation) error {
			return repository.Repair(ctx)
		},
	))
}

Typed input

Arguments and options are bindings captured by handlers, not string keys:

limit := cli.IntOption("limit").Default(100)
format := cli.EnumOption("format", "human", "json").Default("human")
source := cli.StringArgument("source")

command := cli.NewCommand("import",
	cli.WithOptions(limit, format),
	cli.WithArguments(source),
	cli.WithHandler(func(ctx context.Context, invocation cli.Invocation) error {
		input := invocation.Input()
		return importFile(ctx, source.Get(input), limit.Get(input), format.Get(input))
	}),
)

State distinguishes omitted, defaulted, and explicit values, including explicit empty strings, zero, and false. Custom domain types use TypedOption or TypedArgument; parser implementation types never cross the public boundary.

Execution modes

Set Request.Output.Mode to OutputHuman, OutputJSON, or OutputQuiet. JSON writes one deterministic cli/v1 success or error envelope to stdout. Human and quiet errors go to stderr. Request.NonInteractive prevents commands declared with InteractionRequired from reaching side effects.

Help, completion, and references

plain, _ := application.Help([]string{"import"}, cli.HelpOptions{Width: 80})
markdown, _ := application.Markdown()
manifest, _ := application.ManifestJSON()
bash, _ := application.Completion(cli.ShellBash)

Bash, Zsh, Fish, and PowerShell scripts are returned as data. The package never edits shell configuration. Dynamic candidates require an explicit provider and are bounded and cancellation-aware.

Testing

execution := clitest.Run(t, application, []string{"import", "fixture.csv"})
execution.AssertSuccess(t)
execution.AssertStdout(t, "imported\n")

The harness does not mutate os.Args, process streams, the environment, working directory, signal handlers, terminal state, or global registries.

Documentation

Security note

Command-line secrets can be visible in process listings, shell history, CI metadata, and orchestration APIs. Mark secret bindings with Secret() for framework redaction, but prefer stdin, files with application-owned policy, or an explicit secret provider. See the security guide.

Why explicit commands?

Commands remain visible in the application composition root. There is no package-global registry, reflection-driven discovery, hidden dependency injection, environment lookup, working-directory lookup, shell evaluation, or background command goroutine. The resulting graph can be validated before any handler runs and can be read concurrently for help and completion.

License

MIT

Ecosystem

Use the Golib documentation portal to choose companion packages, supported stacks, recipes, and operations guidance.

Documentation

Overview

Package cli builds explicit, typed, composable command-line applications.

Applications construct commands in their composition root, compile immutable metadata, and execute already-tokenized argv with caller-owned context and IO. Bounded one-binary service processes can compile a direct CommandSet without linking features they do not publish. The dependency-free parser is internal and does not appear in public contracts.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrHelp matches an explicit help request.
	ErrHelp = errors.New("cli help requested")
	// ErrVersion matches an explicit version request.
	ErrVersion = errors.New("cli version requested")
	// ErrUnknownCommand matches an unknown command token.
	ErrUnknownCommand = errors.New("cli unknown command")
	// ErrUnknownOption matches an unknown option token.
	ErrUnknownOption = errors.New("cli unknown option")
	// ErrMissingValue matches an option without its required value.
	ErrMissingValue = errors.New("cli missing option value")
	// ErrUsage matches malformed argv and invalid typed input.
	ErrUsage = errors.New("cli usage error")
	// ErrMalformedValue matches failed typed conversion.
	ErrMalformedValue = errors.New("cli malformed value error")
	// ErrCommand matches command execution failures.
	ErrCommand = errors.New("cli command error")
	// ErrValidation matches application validation failures.
	ErrValidation = errors.New("cli validation error")
	// ErrCleanup matches resource cleanup failures.
	ErrCleanup = errors.New("cli cleanup error")
	// ErrOutput matches rendering and writer failures.
	ErrOutput = errors.New("cli output error")
	// ErrCompletion matches dynamic completion provider failures.
	ErrCompletion = errors.New("cli completion error")
	// ErrCanceled matches canceled execution.
	ErrCanceled = errors.New("cli execution canceled")
	// ErrDeadline matches deadline expiration.
	ErrDeadline = errors.New("cli execution deadline exceeded")
	// ErrInternal matches framework failures.
	ErrInternal = errors.New("cli internal error")
)
View Source
var ErrSignal = errors.New("shutdown signal received")

ErrSignal is the default cancellation cause when no signal cause is supplied.

Functions

This section is empty.

Types

type Application

type Application struct {
	// contains filtered or unexported fields
}

Application is an immutable compiled command graph safe for concurrent metadata reads.

func Compile

func Compile(root *Command, options ...CompileOption) (*Application, error)

Compile validates and snapshots an explicit command graph.

func (*Application) Complete

func (application *Application) Complete(
	ctx context.Context,
	argv []string,
) ([]CompletionCandidate, error)

Complete returns bounded candidates for already shell-tokenized partial argv.

func (*Application) Completion

func (application *Application) Completion(shell Shell) (string, error)

Completion returns a deterministic completion script without side effects.

func (*Application) Help

func (application *Application) Help(path []string, options HelpOptions) (string, error)

Help renders deterministic plain-text help for a canonical or alias path.

func (*Application) ManifestJSON

func (application *Application) ManifestJSON() ([]byte, error)

ManifestJSON returns an indented deterministic machine manifest.

func (*Application) Markdown

func (application *Application) Markdown() (string, error)

Markdown returns a deterministic command reference.

func (*Application) Root

func (application *Application) Root() CommandMetadata

Root returns a read-only view of the root command.

func (*Application) Run

func (application *Application) Run(ctx context.Context, request Request) Result

Run parses and executes one invocation without changing process-global state.

Example
package main

import (
	"bytes"
	"context"
	"fmt"

	cli "github.com/faustbrian/go-cli"
)

func main() {
	name := cli.StringArgument("name")
	application, err := cli.Compile(cli.NewCommand(
		"hello",
		cli.WithArguments(name),
		cli.WithHandler(func(_ context.Context, invocation cli.Invocation) error {
			return invocation.Output().SetData("hello " + name.Get(invocation.Input()))
		}),
	))
	if err != nil {
		panic(err)
	}
	stdout := new(bytes.Buffer)
	result := application.Run(context.Background(), cli.Request{
		Args: []string{"Brian"}, Stdout: stdout,
	})
	fmt.Print(stdout.String())
	fmt.Println(result.ExitCode)
}
Output:
hello Brian
0
Example (Json)
package main

import (
	"bytes"
	"context"
	"fmt"

	cli "github.com/faustbrian/go-cli"
)

func main() {
	application, err := cli.Compile(cli.NewCommand(
		"status",
		cli.WithInteraction(cli.InteractionForbidden),
		cli.WithHandler(func(_ context.Context, invocation cli.Invocation) error {
			return invocation.Output().SetData(map[string]string{"status": "ok"})
		}),
	))
	if err != nil {
		panic(err)
	}
	stdout := new(bytes.Buffer)
	application.Run(context.Background(), cli.Request{
		Stdout:         stdout,
		Output:         cli.OutputPolicy{Mode: cli.OutputJSON, NoColor: true},
		NonInteractive: true,
	})
	fmt.Print(stdout.String())
}
Output:
{"schema":"go-cli/v1","ok":true,"data":{"status":"ok"}}

func (*Application) RunCommand

func (application *Application) RunCommand(
	ctx context.Context,
	request Request,
) Result

RunCommand parses and executes a normal command invocation without recognizing the hidden shell-completion protocol. Help and version requests remain available. Service processes that do not publish shell completion can use this narrower runtime surface.

type Argument

type Argument[T any] struct {
	// contains filtered or unexported fields
}

Argument is a typed positional argument binding.

func DurationArgument

func DurationArgument(name string) *Argument[time.Duration]

DurationArgument creates a time.Duration argument.

func EnumArgument

func EnumArgument(name string, values ...string) *Argument[string]

EnumArgument creates a string argument constrained to supplied values.

func FloatArgument

func FloatArgument(name string) *Argument[float64]

FloatArgument creates a 64-bit floating-point argument.

func IntArgument

func IntArgument(name string) *Argument[int64]

IntArgument creates a signed 64-bit integer argument.

func StringArgument

func StringArgument(name string) *Argument[string]

StringArgument creates a required string argument.

func StringsArgument

func StringsArgument(name string) *Argument[[]string]

StringsArgument creates a repeated string argument.

func TimeArgument

func TimeArgument(name, layout string) *Argument[time.Time]

TimeArgument creates a time.Time argument parsed with the supplied layout.

func TypedArgument

func TypedArgument[T any](name, valueType string, parser Parser[T]) *Argument[T]

TypedArgument creates an engine-independent custom scalar argument.

func UintArgument

func UintArgument(name string) *Argument[uint64]

UintArgument creates an unsigned 64-bit integer argument.

func (*Argument[T]) Completion

func (argument *Argument[T]) Completion(provider CompletionProvider) *Argument[T]

Completion declares an explicit dynamic completion provider.

func (*Argument[T]) Description

func (argument *Argument[T]) Description(description string) *Argument[T]

Description documents the argument in help and generated references.

func (*Argument[T]) Get

func (argument *Argument[T]) Get(input Input) T

Get returns the typed value or its zero value when omitted.

func (*Argument[T]) Optional

func (argument *Argument[T]) Optional() *Argument[T]

Optional makes a scalar argument optional.

func (*Argument[T]) Remainder

func (argument *Argument[T]) Remainder() *Argument[T]

Remainder consumes all remaining positional tokens without option parsing.

func (*Argument[T]) Secret

func (argument *Argument[T]) Secret() *Argument[T]

Secret marks values as sensitive for diagnostics and observability.

func (*Argument[T]) State

func (argument *Argument[T]) State(input Input) ValueState

State distinguishes omitted, defaulted, and explicit input.

type ArgumentCardinality

type ArgumentCardinality uint8

ArgumentCardinality defines how many positional tokens an argument accepts.

const (
	// ArgumentRequired consumes exactly one token.
	ArgumentRequired ArgumentCardinality = iota + 1
	// ArgumentOptional consumes zero or one token.
	ArgumentOptional
	// ArgumentRepeated consumes zero or more tokens and must be final.
	ArgumentRepeated
	// ArgumentRemainder consumes every remaining token and must be final.
	ArgumentRemainder
)

type ArgumentDefinition

type ArgumentDefinition interface {
	// contains filtered or unexported methods
}

ArgumentDefinition is a typed positional declaration accepted by commands.

type Command

type Command struct {
	// contains filtered or unexported fields
}

Command is a mutable construction node. Compile publishes an immutable copy and later changes to a Command do not affect an Application.

func NewCommand

func NewCommand(name string, options ...CommandOption) *Command

NewCommand creates an explicit command construction node.

func (*Command) AddSubcommands

func (command *Command) AddSubcommands(children ...*Command) error

AddSubcommands appends subcommands in registration order.

type CommandMetadata

type CommandMetadata struct {
	// contains filtered or unexported fields
}

CommandMetadata is an immutable view of a compiled command.

func (CommandMetadata) Aliases

func (metadata CommandMetadata) Aliases() []string

Aliases returns a copy of alternate command tokens.

func (CommandMetadata) Children

func (metadata CommandMetadata) Children() []CommandMetadata

Children returns immutable child views in registration order.

func (CommandMetadata) Deprecated

func (metadata CommandMetadata) Deprecated() string

Deprecated returns the deprecation message.

func (CommandMetadata) Description

func (metadata CommandMetadata) Description() string

Description returns the long description.

func (CommandMetadata) Documentation

func (metadata CommandMetadata) Documentation() string

Documentation returns the related documentation link.

func (CommandMetadata) Examples

func (metadata CommandMetadata) Examples() []string

Examples returns a copy of complete examples.

func (CommandMetadata) Experimental

func (metadata CommandMetadata) Experimental() bool

Experimental reports whether compatibility is not yet stable.

func (CommandMetadata) Hidden

func (metadata CommandMetadata) Hidden() bool

Hidden reports whether discovery surfaces omit the command.

func (CommandMetadata) Name

func (metadata CommandMetadata) Name() string

Name returns the stable command token.

func (CommandMetadata) Options

func (metadata CommandMetadata) Options() []OptionMetadata

Options returns local options in registration order.

func (CommandMetadata) Replacement

func (metadata CommandMetadata) Replacement() string

Replacement returns the preferred replacement command path.

func (CommandMetadata) Summary

func (metadata CommandMetadata) Summary() string

Summary returns the one-line summary.

type CommandOption

type CommandOption func(*Command)

CommandOption configures a command construction node.

func WithAliases

func WithAliases(aliases ...string) CommandOption

WithAliases declares alternate command tokens.

func WithArguments

func WithArguments(arguments ...ArgumentDefinition) CommandOption

WithArguments registers positional arguments in parse order.

func WithCleanup

func WithCleanup(hooks ...Handler) CommandOption

WithCleanup appends cleanup behavior. Cleanup runs in reverse order.

func WithDeprecated

func WithDeprecated(message string) CommandOption

WithDeprecated records a deprecation message.

func WithDescription

func WithDescription(description string) CommandOption

WithDescription declares the long command description.

func WithDocumentation

func WithDocumentation(documentation string) CommandOption

WithDocumentation links the command to additional documentation.

func WithExamples

func WithExamples(examples ...string) CommandOption

WithExamples declares complete command examples in display order.

func WithExperimental

func WithExperimental(experimental bool) CommandOption

WithExperimental marks a command whose compatibility is not yet stable.

func WithHandler

func WithHandler(handler Handler) CommandOption

WithHandler declares the command execution handler.

func WithHidden

func WithHidden(hidden bool) CommandOption

WithHidden controls whether generated discovery surfaces omit the command.

func WithInteraction

func WithInteraction(interaction Interaction) CommandOption

WithInteraction declares the command's interactive capability.

func WithMiddleware

func WithMiddleware(middlewares ...Middleware) CommandOption

WithMiddleware appends lifecycle middleware in outer-to-inner order.

func WithMutuallyExclusive

func WithMutuallyExclusive(options ...OptionDefinition) CommandOption

WithMutuallyExclusive requires at most one grouped option to resolve.

func WithOptions

func WithOptions(options ...OptionDefinition) CommandOption

WithOptions registers command options in display order.

func WithPostRun

func WithPostRun(hooks ...Handler) CommandOption

WithPostRun appends behavior that runs after a successful command handler.

func WithPreRun

func WithPreRun(hooks ...Handler) CommandOption

WithPreRun appends behavior that runs before the command handler.

func WithReplacement

func WithReplacement(path string) CommandOption

WithReplacement records the preferred replacement command path.

func WithRequiredTogether

func WithRequiredTogether(options ...OptionDefinition) CommandOption

WithRequiredTogether requires all grouped options when any one resolves.

func WithSubcommands

func WithSubcommands(children ...*Command) CommandOption

WithSubcommands registers children in deterministic display order.

func WithSummary

func WithSummary(summary string) CommandOption

WithSummary declares a one-line command summary.

func WithValidation

func WithValidation(validations ...Validation) CommandOption

WithValidation appends input validation in execution order.

func WithVersion

func WithVersion(version string) CommandOption

WithVersion declares command version metadata, normally on the root.

type CommandSet

type CommandSet struct {
	// Name is the stable root command token.
	Name string
	// Version is the optional version rendered by --version and version.
	Version string
	// Commands are the direct executable children in help order.
	Commands []CommandSpec
}

CommandSet declares a bounded root command with direct executable children. It is intended for one-binary service processes that expose only command-local typed options and do not expose positional arguments, aliases, nested commands, lifecycle hooks, or shell completion.

type CommandSetApplication

type CommandSetApplication struct {
	// contains filtered or unexported fields
}

CommandSetApplication is an immutable command set safe for concurrent invocation.

func CompileCommandSet

func CompileCommandSet(
	set CommandSet,
	options ...CompileOption,
) (*CommandSetApplication, error)

CompileCommandSet validates and snapshots a bounded command set.

func (*CommandSetApplication) RunCommand

func (application *CommandSetApplication) RunCommand(
	ctx context.Context,
	request Request,
) Result

RunCommand validates, selects, and executes one command-set invocation.

type CommandSpec

type CommandSpec struct {
	// Name is the stable command token.
	Name string
	// Summary is the one-line help description.
	Summary string
	// Options are typed command-local named values.
	Options []OptionDefinition
	// Handler executes the selected command.
	Handler Handler
}

CommandSpec declares one direct command in a CommandSet.

type CompileOption

type CompileOption func(*compileConfiguration) error

CompileOption configures immutable application compilation.

func WithExitCodePolicy

func WithExitCodePolicy(policy ExitCodePolicy) CompileOption

WithExitCodePolicy configures application-specific portable exit statuses.

func WithLimits

func WithLimits(limits Limits) CompileOption

WithLimits overrides non-zero fields in the auditable default limits.

type CompletionCandidate

type CompletionCandidate struct {
	Value       string
	Description string
}

CompletionCandidate is one bounded shell completion value.

type CompletionProvider

type CompletionProvider func(context.Context, CompletionRequest) ([]CompletionCandidate, error)

CompletionProvider supplies deliberate application-owned dynamic values.

type CompletionRequest

type CompletionRequest struct {
	Command CommandMetadata
	Partial string
}

CompletionRequest contains only safe metadata and hostile partial input.

type Error

type Error struct {
	// contains filtered or unexported fields
}

Error retains a stable classification and an optional underlying cause.

func (*Error) Error

func (err *Error) Error() string

Error returns the safe public diagnostic.

func (*Error) Is

func (err *Error) Is(target error) bool

Is supports stable classification through errors.Is.

func (*Error) Kind

func (err *Error) Kind() ErrorKind

Kind returns the stable error classification.

func (*Error) Unwrap

func (err *Error) Unwrap() error

Unwrap exposes the retained cause to errors.Is and errors.As.

type ErrorKind

type ErrorKind string

ErrorKind is a stable framework error classification.

const (
	// ErrorKindHelp identifies an explicit help request.
	ErrorKindHelp ErrorKind = "help"
	// ErrorKindVersion identifies an explicit version request.
	ErrorKindVersion ErrorKind = "version"
	// ErrorKindUnknownCommand identifies an unknown command token.
	ErrorKindUnknownCommand ErrorKind = "unknown_command"
	// ErrorKindUnknownOption identifies an unknown long or short option.
	ErrorKindUnknownOption ErrorKind = "unknown_option"
	// ErrorKindMissingValue identifies an option without its required value.
	ErrorKindMissingValue ErrorKind = "missing_value"
	// ErrorKindUsage identifies malformed argv or invalid typed input.
	ErrorKindUsage ErrorKind = "usage"
	// ErrorKindMalformedValue identifies failed typed conversion.
	ErrorKindMalformedValue ErrorKind = "malformed_value"
	// ErrorKindCommand identifies a handler failure.
	ErrorKindCommand ErrorKind = "command"
	// ErrorKindValidation identifies application input validation failure.
	ErrorKindValidation ErrorKind = "validation"
	// ErrorKindCleanup identifies resource cleanup failure.
	ErrorKindCleanup ErrorKind = "cleanup"
	// ErrorKindOutput identifies rendering or writer failure.
	ErrorKindOutput ErrorKind = "output"
	// ErrorKindCompletion identifies dynamic completion provider failure.
	ErrorKindCompletion ErrorKind = "completion"
	// ErrorKindCanceled identifies cancellation.
	ErrorKindCanceled ErrorKind = "canceled"
	// ErrorKindDeadline identifies deadline expiration.
	ErrorKindDeadline ErrorKind = "deadline"
	// ErrorKindInternal identifies invalid framework construction or state.
	ErrorKindInternal ErrorKind = "internal"
)

type ExitCodePolicy

type ExitCodePolicy struct {
	Usage    int
	Command  int
	Canceled int
	Deadline int
	Internal int
}

ExitCodePolicy maps stable terminal classifications to portable statuses. Zero fields retain the documented defaults.

type Handler

type Handler func(context.Context, Invocation) error

Handler receives parsed input, caller context, and request-owned IO.

type HelpOptions

type HelpOptions struct {
	Width int
}

HelpOptions controls plain-text help rendering.

type IO

type IO struct {
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
}

IO contains streams owned by one invocation.

type Input

type Input struct {
	// contains filtered or unexported fields
}

Input is an immutable invocation-local typed value set.

type Interaction

type Interaction uint8

Interaction declares whether a command may require an interactive terminal.

const (
	// InteractionOptional allows an application to add optional prompts.
	InteractionOptional Interaction = iota
	// InteractionRequired rejects explicit non-interactive execution.
	InteractionRequired
	// InteractionForbidden declares that the command must never prompt.
	InteractionForbidden
)

type Invocation

type Invocation struct {
	// contains filtered or unexported fields
}

Invocation supplies parsed input and explicit IO to a handler.

func (Invocation) IO

func (invocation Invocation) IO() IO

IO returns the caller-owned streams for this invocation.

func (Invocation) Input

func (invocation Invocation) Input() Input

Input returns invocation-local typed values.

func (Invocation) Interactive

func (invocation Invocation) Interactive() bool

Interactive reports whether application-provided prompting is permitted.

func (Invocation) Output

func (invocation Invocation) Output() *Output

Output returns the invocation-local bounded output collector.

type Limits

type Limits struct {
	MaximumCommandDepth        int
	MaximumCommands            int
	MaximumOptionsPerCommand   int
	MaximumArgumentsPerCommand int
	MaximumArguments           int
	MaximumArgvBytes           int
	MaximumMetadataBytes       int
	MaximumCompletionResults   int
	MaximumCompletionBytes     int
}

Limits bounds hostile construction, argv, completion, and generation work.

type Manifest

type Manifest struct {
	Schema   string            `json:"schema"`
	Name     string            `json:"name"`
	Version  string            `json:"version,omitempty"`
	Root     ManifestCommand   `json:"root"`
	Commands []ManifestCommand `json:"commands,omitempty"`
}

Manifest is the stable machine-readable command model.

type ManifestArgument

type ManifestArgument struct {
	Name          string              `json:"name"`
	Type          string              `json:"type"`
	Cardinality   ArgumentCardinality `json:"cardinality"`
	Description   string              `json:"description,omitempty"`
	Secret        bool                `json:"secret,omitempty"`
	AllowedValues []string            `json:"allowed_values,omitempty"`
	Format        string              `json:"format,omitempty"`
}

ManifestArgument describes a positional argument.

type ManifestCommand

type ManifestCommand struct {
	Name             string             `json:"name"`
	Path             string             `json:"path"`
	Aliases          []string           `json:"aliases,omitempty"`
	Summary          string             `json:"summary,omitempty"`
	Description      string             `json:"description,omitempty"`
	Examples         []string           `json:"examples,omitempty"`
	Documentation    string             `json:"documentation,omitempty"`
	Hidden           bool               `json:"hidden,omitempty"`
	Experimental     bool               `json:"experimental,omitempty"`
	Deprecated       string             `json:"deprecated,omitempty"`
	Replacement      string             `json:"replacement,omitempty"`
	Arguments        []ManifestArgument `json:"arguments,omitempty"`
	Options          []ManifestOption   `json:"options,omitempty"`
	InheritedOptions []ManifestOption   `json:"inherited_options,omitempty"`
	Commands         []ManifestCommand  `json:"commands,omitempty"`
}

ManifestCommand describes one command and its descendants.

type ManifestOption

type ManifestOption struct {
	Name          string   `json:"name"`
	Short         string   `json:"short,omitempty"`
	Type          string   `json:"type"`
	Description   string   `json:"description,omitempty"`
	Persistent    bool     `json:"persistent,omitempty"`
	Secret        bool     `json:"secret,omitempty"`
	Defaulted     bool     `json:"defaulted,omitempty"`
	Required      bool     `json:"required,omitempty"`
	Source        string   `json:"source,omitempty"`
	AllowedValues []string `json:"allowed_values,omitempty"`
	Format        string   `json:"format,omitempty"`
}

ManifestOption describes a local or inherited option.

type Middleware

type Middleware func(context.Context, CommandMetadata, Next) error

Middleware observes safe command metadata and controls lifecycle execution.

type Next

type Next func(context.Context) error

Next continues an explicit middleware chain with the supplied context.

type Option

type Option[T any] struct {
	// contains filtered or unexported fields
}

Option is a typed named-option binding.

func BoolOption

func BoolOption(name string) *Option[bool]

BoolOption creates a boolean option.

func DurationOption

func DurationOption(name string) *Option[time.Duration]

DurationOption creates a time.Duration option.

func EnumOption

func EnumOption(name string, values ...string) *Option[string]

EnumOption creates a string option constrained to the supplied values.

func FloatOption

func FloatOption(name string) *Option[float64]

FloatOption creates a 64-bit floating-point option.

func IntOption

func IntOption(name string) *Option[int64]

IntOption creates a signed 64-bit integer option.

func KeyValuesOption

func KeyValuesOption(name string) *Option[map[string]string]

KeyValuesOption creates a repeatable key/value option.

func StringOption

func StringOption(name string) *Option[string]

StringOption creates a string option.

func StringsOption

func StringsOption(name string) *Option[[]string]

StringsOption creates a repeatable string-slice option.

func TimeOption

func TimeOption(name, layout string) *Option[time.Time]

TimeOption creates a time.Time option parsed with the supplied layout.

func TypedOption

func TypedOption[T any](name, valueType string, parser Parser[T]) *Option[T]

TypedOption creates an engine-independent custom scalar option.

func UintOption

func UintOption(name string) *Option[uint64]

UintOption creates an unsigned 64-bit integer option.

func (*Option[T]) Completion

func (option *Option[T]) Completion(provider CompletionProvider) *Option[T]

Completion declares an explicit dynamic completion provider.

func (*Option[T]) Default

func (option *Option[T]) Default(value T) *Option[T]

Default supplies a value when the option is omitted.

func (*Option[T]) Description

func (option *Option[T]) Description(description string) *Option[T]

Description documents the option in help and generated references.

func (*Option[T]) Get

func (option *Option[T]) Get(input Input) T

Get returns the typed value or its zero value when omitted.

func (*Option[T]) Persistent

func (option *Option[T]) Persistent() *Option[T]

Persistent makes an option available to all descendant commands.

func (*Option[T]) Required

func (option *Option[T]) Required() *Option[T]

Required rejects execution when the option is omitted and has no default.

func (*Option[T]) Secret

func (option *Option[T]) Secret() *Option[T]

Secret marks option values as sensitive for diagnostics and observability.

func (*Option[T]) Short

func (option *Option[T]) Short(short rune) *Option[T]

Short declares a single ASCII shorthand token.

func (*Option[T]) State

func (option *Option[T]) State(input Input) ValueState

State distinguishes omitted, defaulted, and explicit input.

type OptionDefinition

type OptionDefinition interface {
	// contains filtered or unexported methods
}

OptionDefinition is a typed named option accepted by commands and groups.

type OptionMetadata

type OptionMetadata struct {
	// contains filtered or unexported fields
}

OptionMetadata is an immutable view of a compiled option.

func (OptionMetadata) AllowedValues

func (metadata OptionMetadata) AllowedValues() []string

AllowedValues returns a copy of the declared enum values, if any.

func (OptionMetadata) Format

func (metadata OptionMetadata) Format() string

Format returns the declared time layout, if any.

func (OptionMetadata) Name

func (metadata OptionMetadata) Name() string

Name returns the long option name without leading dashes.

func (OptionMetadata) Persistent

func (metadata OptionMetadata) Persistent() bool

Persistent reports whether descendants inherit the option.

func (OptionMetadata) Secret

func (metadata OptionMetadata) Secret() bool

Secret reports whether values require redaction.

func (OptionMetadata) Short

func (metadata OptionMetadata) Short() rune

Short returns the shorthand rune or zero when none is configured.

func (OptionMetadata) ValueType

func (metadata OptionMetadata) ValueType() string

ValueType returns the stable manifest name of the option value type.

type Output

type Output struct {
	// contains filtered or unexported fields
}

Output buffers bounded invocation output until terminal success is known.

func (*Output) Info

func (output *Output) Info(message string) error

Info records a bounded informational line.

func (*Output) SetData

func (output *Output) SetData(value any) error

SetData records one success value for human or JSON rendering.

type OutputMode

type OutputMode uint8

OutputMode selects a stable presentation contract.

const (
	// OutputHuman emits plain text for people and pipes.
	OutputHuman OutputMode = iota
	// OutputJSON emits a versioned JSON envelope on stdout.
	OutputJSON
	// OutputQuiet suppresses successful informational output.
	OutputQuiet
)

type OutputPolicy

type OutputPolicy struct {
	Mode    OutputMode
	NoColor bool
	Width   int
}

OutputPolicy controls one invocation's presentation contract.

type Parser

type Parser[T any] func(string) (T, error)

Parser converts one exact argv token into an application-owned type.

type Request

type Request struct {
	Args   []string
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
	// NonInteractive prevents commands from requiring terminal input.
	NonInteractive bool
	Output         OutputPolicy
}

Request describes one already-tokenized invocation.

type Result

type Result struct {
	ExitCode int
	Err      error
	Command  CommandMetadata
}

Result is the terminal outcome of one in-process invocation.

type Shell

type Shell string

Shell identifies a supported completion script target.

const (
	// ShellBash generates Bash completion.
	ShellBash Shell = "bash"
	// ShellZsh generates Zsh completion.
	ShellZsh Shell = "zsh"
	// ShellFish generates Fish completion.
	ShellFish Shell = "fish"
	// ShellPowerShell generates PowerShell completion.
	ShellPowerShell Shell = "powershell"
)

type ShutdownAction

type ShutdownAction uint8

ShutdownAction describes a caller-owned signal policy transition.

const (
	// ShutdownGraceful means the first signal canceled the graceful context.
	ShutdownGraceful ShutdownAction = iota + 1
	// ShutdownForced means a repeated signal requested forced termination.
	ShutdownForced
	// ShutdownAlreadyForced means forced termination was already requested.
	ShutdownAlreadyForced
)

type ShutdownController

type ShutdownController struct {
	// contains filtered or unexported fields
}

ShutdownController translates caller-delivered signals without registering process signal handlers or starting goroutines. The application remains responsible for signal.Notify and signal.Stop ownership.

func NewShutdownController

func NewShutdownController(parent context.Context) (*ShutdownController, error)

NewShutdownController derives a cancelable context from the caller context.

func (*ShutdownController) Close

func (controller *ShutdownController) Close()

Close releases the derived context when signal handling is no longer needed.

func (*ShutdownController) Context

func (controller *ShutdownController) Context() context.Context

Context returns the graceful cancellation context.

func (*ShutdownController) Forced

func (controller *ShutdownController) Forced() <-chan struct{}

Forced closes after the second delivered signal.

func (*ShutdownController) Signal

func (controller *ShutdownController) Signal(cause error) ShutdownAction

Signal applies graceful-then-forced policy to one caller-delivered signal.

type Validation

type Validation func(context.Context, Input) error

Validation checks parsed input before lifecycle middleware or side effects.

type ValueState

type ValueState uint8

ValueState identifies where a resolved value came from.

const (
	// ValueOmitted means no token or declared default supplied the value.
	ValueOmitted ValueState = iota
	// ValueDefaulted means the declared default supplied the value.
	ValueDefaulted
	// ValueExplicit means argv supplied the value, including an empty value.
	ValueExplicit
)

Directories

Path Synopsis
Package clitest provides parallel-safe in-process command execution helpers.
Package clitest provides parallel-safe in-process command execution helpers.
cmd
generate-reference command
Command generate-reference reproduces checked-in command documentation.
Command generate-reference reproduces checked-in command documentation.
process-fixture command
Command process-fixture proves the narrow executable integration boundary.
Command process-fixture proves the narrow executable integration boundary.
internal
engine
Package engine contains the dependency-free argv parsing boundary.
Package engine contains the dependency-free argv parsing boundary.
referenceapp
Package referenceapp defines the canonical generated-document fixture.
Package referenceapp defines the canonical generated-document fixture.

Jump to

Keyboard shortcuts

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