Documentation
¶
Index ¶
- Constants
- func ApplyActionArgs(action *Action, args []string)
- func ApplyMeta(spec *Spec, meta *FlagMeta)
- func GenerateBash(g *Generator) (string, error)
- func GenerateElvish(g *Generator) (string, error)
- func GenerateFish(g *Generator) (string, error)
- func GenerateNu(g *Generator) (string, error)
- func GeneratePwsh(g *Generator) (string, error)
- func GenerateZsh(g *Generator) (string, error)
- func HandleAction(a Action, gen *Generator, handler Handler, quiet bool) (bool, error)
- func NegatableSpecs(spec Spec, positiveDesc, negativeDesc, inversePrefix string) (Spec, Spec)
- func ParseCompleteTag(tag string) (string, bool, []string)
- func RegisterShell(name string, fn ShellFunc)
- func ValidateGenerator(g *Generator) error
- func ValidateShellSafe(s, label string) error
- func ValidateSpecs(specs []Spec) error
- func ValidateSubs(subs []SubSpec) error
- func WriteIndented(sb *strings.Builder, indent, block string)
- type Action
- type CompletionFlags
- type FlagMeta
- type Generator
- type Handler
- type Option
- type Order
- type PreflightOption
- type ShellFunc
- type Spec
- type SubSpec
- type ValueDesc
Constants ¶
const ( HintCommand = "command" HintDir = "dir" HintEmail = "email" HintFile = "file" HintHost = "host" HintURL = "url" HintUser = "user" )
Value hint constants for completion.
const ( FlagComplete = "@complete" // dynamic completion requests FlagShell = "@shell" // shell type for completions FlagInstallCompletion = "install-completion" // install shell completions FlagUninstallCompletion = "uninstall-completion" // uninstall shell completions FlagPrintCompletion = "print-completion" // print completion script )
Hidden flag names used by the completion system. The @ prefix avoids clashing with user-defined flags.
Variables ¶
This section is empty.
Functions ¶
func ApplyActionArgs ¶
ApplyActionArgs supplements action with completion flags parsed from args. Existing action fields are only updated when the corresponding flag is present.
func ApplyMeta ¶
ApplyMeta populates spec fields from a FlagMeta's completion-related annotations (Complete, Extension, ValueHint, Terse, Enum).
func GenerateBash ¶
GenerateBash generates a bash shell completion script.
func GenerateElvish ¶
GenerateElvish generates an Elvish completion script.
Elvish arg-completers receive the whole command line as @words rather than a pre-tokenized prior list, so the generated script resolves a canonical "app;sub;subsub" command path itself (canonicalizing aliases at every depth), then branches on that path to emit candidates. Flag values are completed by inspecting the token preceding the cursor. Elvish applies its own prefix matcher to whatever the completer emits, so the script never filters by the seed word the way bash does.
func GenerateFish ¶
GenerateFish generates a fish shell completion script.
func GenerateNu ¶
GenerateNu generates a Nushell completion script.
Nushell completions are declarative: every command is described by an `extern` signature whose flags and positionals carry optional `@"nu-complete …"` custom-completer attributes. Unlike the bash/zsh/fish/pwsh/elvish generators - each of which emits a single dispatcher that resolves the command path at runtime - this generator leans on Nushell's own parser to select the matching `extern`, and only emits helper closures for the cases Nushell cannot express declaratively: dynamic predictors (which shell out to `<app> --@complete=…`), comma-separated value lists, positional dynamic args, and forwarded context flags. File and directory value hints map to Nushell's native `path` and `directory` shapes.
func GeneratePwsh ¶
GeneratePwsh generates a PowerShell completion script.
PowerShell native completers receive the raw command-line AST rather than a pre-tokenized word list, so the generated script walks $commandAst itself: it first resolves a canonical "app;sub;subsub" command path (canonicalizing aliases at every depth), then switches on that path to emit candidates. Flag values are completed by inspecting the token preceding the cursor.
func GenerateZsh ¶
GenerateZsh generates a zsh shell completion script.
func HandleAction ¶
HandleAction dispatches the given completion action against gen. Returns true if an action was handled (caller should exit).
func NegatableSpecs ¶
NegatableSpecs returns the positive and negative Spec pair for a negatable flag. It rewrites spec.Terse using automatic prefix detection (e.g. "Enable X" → "Disable X") and creates a --<inversePrefix><name> variant. An empty inversePrefix defaults to "no-". Explicit positiveDesc / negativeDesc override the auto-derived text.
func ParseCompleteTag ¶
ParseCompleteTag parses the complete struct tag value. Format: comma-separated parts of "predictor=<name>", "comma", and/or "values=<space-separated values>".
func RegisterShell ¶
RegisterShell registers a shell completion generator. Shell subpackages call this from init().
func ValidateGenerator ¶
ValidateGenerator validates shell-sensitive fields in g.
func ValidateShellSafe ¶
ValidateShellSafe checks that s contains only shell-safe characters (alphanumeric, hyphens, underscores, dots, and @). It returns an error if s is empty or contains unsafe characters.
func ValidateSpecs ¶
ValidateSpecs validates shell-sensitive fields in specs.
func ValidateSubs ¶
ValidateSubs recursively validates shell-sensitive subcommand fields.
func WriteIndented ¶
WriteIndented writes each non-empty line of block to sb, prefixed with indent.
Types ¶
type Action ¶
type Action struct {
Args []string // preceding positional args from the shell
Complete string // dynamic completion type (--@complete value)
InstallCompletion bool
PrintCompletion bool
Shell string // resolved shell name
UnknownFlags []string
UninstallCompletion bool
}
Action describes which completion action was requested.
type CompletionFlags ¶
type CompletionFlags struct {
Complete string
Shell string
InstallCompletion bool
UnknownFlags []string
UninstallCompletion bool
PrintCompletion bool
}
CompletionFlags provides standalone completion flags for pre-parse handling. Use Preflight to populate this struct from os.Args before the CLI parser runs.
func Preflight ¶
func Preflight() (CompletionFlags, []string, bool)
Preflight scans os.Args for completion flags, allowing completion to be handled before the CLI parser. This is useful for subcommand-based CLIs where the parser requires a subcommand but completion flags are standalone.
Returns a populated CompletionFlags, any positional args found after "--", and true if a completion flag was found. When ok is false, the caller should proceed with normal CLI parsing.
func (*CompletionFlags) Handle ¶
func (f *CompletionFlags) Handle( gen *Generator, handler Handler, opts ...PreflightOption, ) (bool, error)
Handle checks whether a completion action was requested and executes it. Returns true if a completion action was handled (caller should exit). The handler callback is invoked for --@complete=<type> requests; it receives the completion type and resolved shell name.
type FlagMeta ¶
type FlagMeta struct {
Alias string // command invoked by this alias command
Aliases []string // flag aliases
Complete string // completion directive
CompleteWhenHidden bool // still offer this flag in completions even when hidden from help
Default string // default value for non-enum flags (rendered as " (default: X)" suffix)
Enum []string // enum values
EnumDefault string // default value annotation for enum display
EnumHighlight []string // highlight hint substrings (parallel to Enum)
EnumTerse []string // short descriptions for enum values (parallel to Enum)
Extension string // file extension filter for completion (e.g. "yaml" or "yaml,yml")
Forward bool // forward this flag's value to dynamic completion handlers
Group string // help section group
HasArg bool // true if the flag takes a value (non-bool)
Help string // help text for --help output
HideDefault bool // suppress the default-value annotation in help output
Hidden bool // hidden flag
HideLong bool // hide the long flag from help output
HideShort bool // hide the short flag from help output
Order Order // completion ordering mode
InversePrefix string // prefix for negated flag (default "no-")
IsArg bool // true if this is a positional argument
IsCSV bool // true if the field type is CSVFlag or *CSVFlag
IsSlice bool // true if the field type is a slice
Name string // flag name
Negatable bool // true if the flag supports --no- prefix
NegativeOnly bool // advertise only the --no- variant in help
NegativeDesc string // explicit description for --no- variant
NoIndent bool // suppress short-flag alignment indent in help
Optional bool // true if arg is optional
Origin string // where this metadata came from (e.g. struct field name)
Persistent bool // true if the flag remains available on descendant subcommands
Placeholder string // placeholder like <value>
PlaceholderOverride bool // true if placeholder was set via clib tag
PositiveDesc string // explicit description for positive variant (negatable flags)
PositiveOnly bool // advertise only the positive variant in help
Short string // short flag letter
Terse string // very short description for completions
ValueHint string // value type hint for completion (file, dir, command, user, host, url, email)
}
FlagMeta holds metadata extracted from a single struct field's tags.
func (*FlagMeta) Desc ¶
Desc returns the Terse description for use in completions. Falls back to Help if Terse is empty. Only the first line of Help is used.
func (*FlagMeta) ParseClibTag ¶
ParseClibTag parses a clib:"..." struct tag value into meta. These are clib-specific annotations that supplement what the CLI framework provider (kong, cobra, etc.) already supplies.
Format: comma-separated entries, values optionally single-quoted.
clib:"terse='Draft filter',complete='predictor=repo',group='filters'"
Supported keys: alias, complete, complete-hidden, enum, group, inverse, negatable, negative, order, placeholder, positive, terse.
The positive and negative keys are dual-form: with a value they set that variant's completion description, bare they advertise only that variant in help output (the flag stays negatable, so both spellings still parse and complete).
type Generator ¶
type Generator struct {
AppName string
DynamicArgs []string // per-position dynamic completion; final entry repeats for additional positional args
HasMaxPositionalArgs bool
IncludeHidden bool // offer hidden flags as completions instead of omitting them
MaxPositionalArgs int
Order Order
Specs []Spec
Subs []SubSpec
}
Generator generates shell completion scripts.
func NewGenerator ¶
NewGenerator creates a Generator for the named application.
func (*Generator) FromFlags ¶
FromFlags populates completion specs from pre-inspected flag metadata.
func (*Generator) Install ¶
Install writes the completion script to the appropriate shell config directory. An empty shell defaults to fish.
type Handler ¶
Handler is called when a dynamic completion is requested. It receives the completion type, the detected shell name, and any preceding positional args passed from the shell.
type Option ¶
type Option func(*Generator)
Option configures a Generator.
func WithIncludeHidden ¶
func WithIncludeHidden() Option
WithIncludeHidden offers hidden flags as completions instead of omitting them. By default a flag hidden from --help is also withheld from completions; enabling this surfaces every hidden flag across the command tree. For a single flag, prefer the per-flag complete-hidden opt-in instead.
type PreflightOption ¶
type PreflightOption func(*preflightConfig)
PreflightOption configures CompletionFlags.Handle behavior.
func WithArgs ¶
func WithArgs(args []string) PreflightOption
WithArgs passes preceding positional args to the completion handler.
func WithQuiet ¶
func WithQuiet(quiet bool) PreflightOption
WithQuiet suppresses output during install/uninstall.
type Spec ¶
type Spec struct {
CommaList bool // comma-separated multi-value (e.g. --columns)
Dynamic string // dynamic completion type (e.g. "author" -> "<app> --@complete=author")
Extension string // file extension filter for completion (e.g. "yaml" or "yaml,yml")
Forward bool // forward this flag's value to dynamic completion handlers
HasArg bool // flag takes a value
Hidden bool // hidden from completions
LongFlag string // e.g. "author" (no dashes)
Order Order // completion ordering mode
Persistent bool // true if the flag remains available on descendant subcommands
ShortFlag string // e.g. "a" (no dash)
Terse string // very short description for tab completion
ValueDescs []ValueDesc // static values with descriptions (takes precedence over Values)
ValueHint string // value type hint: file, dir, command, user, host, url, email
Values []string // static completion values (from enum)
}
Spec describes a single flag for shell completion generation.
func SortVisibleSpecs ¶
SortVisibleSpecs returns non-hidden specs sorted by long flag name, falling back to short flag for short-only flags.
func SpecsFromFlagMeta ¶
SpecsFromFlagMeta expands a single FlagMeta into completion specs, including negated variants where applicable.
type SubSpec ¶
type SubSpec struct {
Aliases []string // command aliases (e.g. ["up"] for "update")
DynamicArgs []string // per-position dynamic completion; final entry repeats for additional positional args
HasMaxPositionalArgs bool
MaxPositionalArgs int
Name string // subcommand name (e.g. "bump")
PathArgs bool // enable file completion for positional args
Specs []Spec // subcommand-specific flag specs
Subs []SubSpec // nested subcommands
Terse string // short description for tab completion
}
SubSpec describes a subcommand for shell completion generation.
func SortSubSpecs ¶
SortSubSpecs returns a copy of subs sorted by name.