complete

package
v0.7.17 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 15 Imported by: 2

Documentation

Index

Constants

View Source
const (
	HintCommand = "command"
	HintDir     = "dir"
	HintEmail   = "email"
	HintFile    = "file"
	HintHost    = "host"
	HintURL     = "url"
	HintUser    = "user"
)

Value hint constants for completion.

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

func ApplyActionArgs(action *Action, args []string)

ApplyActionArgs supplements action with completion flags parsed from args. Existing action fields are only updated when the corresponding flag is present.

func ApplyMeta

func ApplyMeta(spec *Spec, meta *FlagMeta)

ApplyMeta populates spec fields from a FlagMeta's completion-related annotations (Complete, Extension, ValueHint, Terse, Enum).

func GenerateBash

func GenerateBash(g *Generator) (string, error)

GenerateBash generates a bash shell completion script.

func GenerateElvish

func GenerateElvish(g *Generator) (string, error)

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

func GenerateFish(g *Generator) (string, error)

GenerateFish generates a fish shell completion script.

func GenerateNu

func GenerateNu(g *Generator) (string, error)

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

func GeneratePwsh(g *Generator) (string, error)

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

func GenerateZsh(g *Generator) (string, error)

GenerateZsh generates a zsh shell completion script.

func HandleAction

func HandleAction(a Action, gen *Generator, handler Handler, quiet bool) (bool, error)

HandleAction dispatches the given completion action against gen. Returns true if an action was handled (caller should exit).

func NegatableSpecs

func NegatableSpecs(spec Spec, positiveDesc, negativeDesc, inversePrefix string) (Spec, Spec)

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

func ParseCompleteTag(tag string) (string, bool, []string)

ParseCompleteTag parses the complete struct tag value. Format: comma-separated parts of "predictor=<name>", "comma", and/or "values=<space-separated values>".

func RegisterShell

func RegisterShell(name string, fn ShellFunc)

RegisterShell registers a shell completion generator. Shell subpackages call this from init().

func ValidateGenerator

func ValidateGenerator(g *Generator) error

ValidateGenerator validates shell-sensitive fields in g.

func ValidateShellSafe

func ValidateShellSafe(s, label string) error

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

func ValidateSpecs(specs []Spec) error

ValidateSpecs validates shell-sensitive fields in specs.

func ValidateSubs

func ValidateSubs(subs []SubSpec) error

ValidateSubs recursively validates shell-sensitive subcommand fields.

func WriteIndented

func WriteIndented(sb *strings.Builder, indent, block string)

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

func (f *FlagMeta) Desc() string

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

func (f *FlagMeta) ParseClibTag(t string) error

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).

func (*FlagMeta) Validate

func (f *FlagMeta) Validate() error

Validate checks constraints that depend on the fully populated FlagMeta, including fields set by the CLI framework (e.g. negatable from kong's tag). Callers should invoke this after all metadata is populated.

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

func NewGenerator(command string, opts ...Option) *Generator

NewGenerator creates a Generator for the named application.

func (*Generator) FromFlags

func (g *Generator) FromFlags(flags []FlagMeta) *Generator

FromFlags populates completion specs from pre-inspected flag metadata.

func (*Generator) Install

func (g *Generator) Install(sh string, quiet bool) error

Install writes the completion script to the appropriate shell config directory. An empty shell defaults to fish.

func (*Generator) Print

func (g *Generator) Print(w io.Writer, sh string) error

Print writes the completion script for the given shell to w. An empty shell defaults to fish.

func (*Generator) Uninstall

func (g *Generator) Uninstall(sh string, quiet bool) error

Uninstall removes the completion script for the given shell. An empty shell defaults to fish.

type Handler

type Handler func(shell, kind string, args []string)

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.

func WithOrder

func WithOrder(order Order) Option

WithOrder sets the default completion ordering for flags that do not specify an explicit order.

type Order

type Order string

Order controls how shell completion candidates are ordered.

const (
	// OrderKeep preserves the candidate order for shells that support it.
	OrderKeep Order = "keep"
	// OrderShell uses the shell's normal ordering behavior.
	OrderShell Order = "shell"
)

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 ShellFunc

type ShellFunc func(g *Generator) (string, error)

ShellFunc generates a completion script for a given shell.

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

func SortVisibleSpecs(specs []Spec) []Spec

SortVisibleSpecs returns non-hidden specs sorted by long flag name, falling back to short flag for short-only flags.

func SpecsFromFlagMeta

func SpecsFromFlagMeta(f FlagMeta) []Spec

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

func SortSubSpecs(subs []SubSpec) []SubSpec

SortSubSpecs returns a copy of subs sorted by name.

type ValueDesc

type ValueDesc struct {
	Value string
	Desc  string
}

ValueDesc pairs a completion value with an optional description.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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