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 ¶
- Variables
- type Application
- func (application *Application) Complete(ctx context.Context, argv []string) ([]CompletionCandidate, error)
- func (application *Application) Completion(shell Shell) (string, error)
- func (application *Application) Help(path []string, options HelpOptions) (string, error)
- func (application *Application) ManifestJSON() ([]byte, error)
- func (application *Application) Markdown() (string, error)
- func (application *Application) Root() CommandMetadata
- func (application *Application) Run(ctx context.Context, request Request) Result
- func (application *Application) RunCommand(ctx context.Context, request Request) Result
- type Argument
- func DurationArgument(name string) *Argument[time.Duration]
- func EnumArgument(name string, values ...string) *Argument[string]
- func FloatArgument(name string) *Argument[float64]
- func IntArgument(name string) *Argument[int64]
- func StringArgument(name string) *Argument[string]
- func StringsArgument(name string) *Argument[[]string]
- func TimeArgument(name, layout string) *Argument[time.Time]
- func TypedArgument[T any](name, valueType string, parser Parser[T]) *Argument[T]
- func UintArgument(name string) *Argument[uint64]
- func (argument *Argument[T]) Completion(provider CompletionProvider) *Argument[T]
- func (argument *Argument[T]) Description(description string) *Argument[T]
- func (argument *Argument[T]) Get(input Input) T
- func (argument *Argument[T]) Optional() *Argument[T]
- func (argument *Argument[T]) Remainder() *Argument[T]
- func (argument *Argument[T]) Secret() *Argument[T]
- func (argument *Argument[T]) State(input Input) ValueState
- type ArgumentCardinality
- type ArgumentDefinition
- type Command
- type CommandMetadata
- func (metadata CommandMetadata) Aliases() []string
- func (metadata CommandMetadata) Children() []CommandMetadata
- func (metadata CommandMetadata) Deprecated() string
- func (metadata CommandMetadata) Description() string
- func (metadata CommandMetadata) Documentation() string
- func (metadata CommandMetadata) Examples() []string
- func (metadata CommandMetadata) Experimental() bool
- func (metadata CommandMetadata) Hidden() bool
- func (metadata CommandMetadata) Name() string
- func (metadata CommandMetadata) Options() []OptionMetadata
- func (metadata CommandMetadata) Replacement() string
- func (metadata CommandMetadata) Summary() string
- type CommandOption
- func WithAliases(aliases ...string) CommandOption
- func WithArguments(arguments ...ArgumentDefinition) CommandOption
- func WithCleanup(hooks ...Handler) CommandOption
- func WithDeprecated(message string) CommandOption
- func WithDescription(description string) CommandOption
- func WithDocumentation(documentation string) CommandOption
- func WithExamples(examples ...string) CommandOption
- func WithExperimental(experimental bool) CommandOption
- func WithHandler(handler Handler) CommandOption
- func WithHidden(hidden bool) CommandOption
- func WithInteraction(interaction Interaction) CommandOption
- func WithMiddleware(middlewares ...Middleware) CommandOption
- func WithMutuallyExclusive(options ...OptionDefinition) CommandOption
- func WithOptions(options ...OptionDefinition) CommandOption
- func WithPostRun(hooks ...Handler) CommandOption
- func WithPreRun(hooks ...Handler) CommandOption
- func WithReplacement(path string) CommandOption
- func WithRequiredTogether(options ...OptionDefinition) CommandOption
- func WithSubcommands(children ...*Command) CommandOption
- func WithSummary(summary string) CommandOption
- func WithValidation(validations ...Validation) CommandOption
- func WithVersion(version string) CommandOption
- type CommandSet
- type CommandSetApplication
- type CommandSpec
- type CompileOption
- type CompletionCandidate
- type CompletionProvider
- type CompletionRequest
- type Error
- type ErrorKind
- type ExitCodePolicy
- type Handler
- type HelpOptions
- type IO
- type Input
- type Interaction
- type Invocation
- type Limits
- type Manifest
- type ManifestArgument
- type ManifestCommand
- type ManifestOption
- type Middleware
- type Next
- type Option
- func BoolOption(name string) *Option[bool]
- func DurationOption(name string) *Option[time.Duration]
- func EnumOption(name string, values ...string) *Option[string]
- func FloatOption(name string) *Option[float64]
- func IntOption(name string) *Option[int64]
- func KeyValuesOption(name string) *Option[map[string]string]
- func StringOption(name string) *Option[string]
- func StringsOption(name string) *Option[[]string]
- func TimeOption(name, layout string) *Option[time.Time]
- func TypedOption[T any](name, valueType string, parser Parser[T]) *Option[T]
- func UintOption(name string) *Option[uint64]
- func (option *Option[T]) Completion(provider CompletionProvider) *Option[T]
- func (option *Option[T]) Default(value T) *Option[T]
- func (option *Option[T]) Description(description string) *Option[T]
- func (option *Option[T]) Get(input Input) T
- func (option *Option[T]) Persistent() *Option[T]
- func (option *Option[T]) Required() *Option[T]
- func (option *Option[T]) Secret() *Option[T]
- func (option *Option[T]) Short(short rune) *Option[T]
- func (option *Option[T]) State(input Input) ValueState
- type OptionDefinition
- type OptionMetadata
- func (metadata OptionMetadata) AllowedValues() []string
- func (metadata OptionMetadata) Format() string
- func (metadata OptionMetadata) Name() string
- func (metadata OptionMetadata) Persistent() bool
- func (metadata OptionMetadata) Secret() bool
- func (metadata OptionMetadata) Short() rune
- func (metadata OptionMetadata) ValueType() string
- type Output
- type OutputMode
- type OutputPolicy
- type Parser
- type Request
- type Result
- type Shell
- type ShutdownAction
- type ShutdownController
- type Validation
- type ValueState
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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") )
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 ¶
DurationArgument creates a time.Duration argument.
func EnumArgument ¶
EnumArgument creates a string argument constrained to supplied values.
func FloatArgument ¶
FloatArgument creates a 64-bit floating-point argument.
func IntArgument ¶
IntArgument creates a signed 64-bit integer argument.
func StringArgument ¶
StringArgument creates a required string argument.
func StringsArgument ¶
StringsArgument creates a repeated string argument.
func TimeArgument ¶
TimeArgument creates a time.Time argument parsed with the supplied layout.
func TypedArgument ¶
TypedArgument creates an engine-independent custom scalar argument.
func UintArgument ¶
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 ¶
Description documents the argument in help and generated references.
func (*Argument[T]) Remainder ¶
Remainder consumes all remaining positional tokens without option parsing.
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 ¶
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 ¶
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.
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 ¶
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 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 Option ¶
type Option[T any] struct { // contains filtered or unexported fields }
Option is a typed named-option binding.
func DurationOption ¶
DurationOption creates a time.Duration option.
func EnumOption ¶
EnumOption creates a string option constrained to the supplied values.
func FloatOption ¶
FloatOption creates a 64-bit floating-point option.
func KeyValuesOption ¶
KeyValuesOption creates a repeatable key/value option.
func StringOption ¶
StringOption creates a string option.
func StringsOption ¶
StringsOption creates a repeatable string-slice option.
func TimeOption ¶
TimeOption creates a time.Time option parsed with the supplied layout.
func TypedOption ¶
TypedOption creates an engine-independent custom scalar option.
func UintOption ¶
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]) Description ¶
Description documents the option in help and generated references.
func (*Option[T]) Persistent ¶
Persistent makes an option available to all descendant commands.
func (*Option[T]) Required ¶
Required rejects execution when the option is omitted and has no default.
func (*Option[T]) Secret ¶
Secret marks option values as sensitive for diagnostics and observability.
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.
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 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 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 ¶
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 )
Source Files
¶
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. |