Documentation
¶
Overview ¶
Package predict generates shell autocompletion candidates for command-line tools.
A Predictor generates completion candidates. Build predictors using constructors like Values, Files, Dirs, or Map, then compose them with combinators like Batch and Callback:
// Static candidates
formats := predict.Values("json", "yaml", "toml")
// Candidates with descriptions
methods := predict.Map(map[string]string{
"GET": "Retrieve resource",
"POST": "Create resource",
})
// Dynamic prediction based on previous command-line flags
target := predict.Callback(func(c predict.Context) predict.Predictor {
env := c.FlagValue("env", "staging")
return predict.Values(env+"-app-1", env+"-app-2")
})
Predictors evaluate against a Context and return a Result containing completion items, shell directives, and usage text.
Common constructors include static values (Values, Map, Items, KeyValue, KeyValueDescribed), the filesystem (Files, Dirs, Executables, Symlinks), multi-part paths (MultiParts), dynamic callbacks (Callback), and the empty predictor (None).
Modifiers refine prediction behavior:
- Predictor.FilterText: matches against a typed prefix.
- Predictor.Exclude: filters out already selected candidates.
- Predictor.KeepOrder: disables alphabetical sorting.
- Predictor.Timeout: limits how long completion waits for dynamic callbacks.
Candidates keep declaration order; Map sorts its keys alphabetically. Shells may re-sort candidates unless Predictor.KeepOrder is set.
Completion waits up to DefaultTimeout (250ms) for dynamic callbacks. A timed-out callback is not canceled and may continue running. Predictor.Timeout adjusts the wait limit; a negative duration disables it.
This package is a standalone SDK with no dependency on the root conga package, so it can be reused independently of the framework.
Predictors reach the command line through the root package's App.Predictor builder method and the conga.Predictable interface; see https://docs.conga.sh/how-to/wire-custom-completion/ for the wiring guide.
Domain-specific types and their predictors live in the topical network, system, and timezone packages; see https://docs.conga.sh/reference/domain-types/.
Index ¶
- Constants
- type Context
- func (c Context) Arg(index int) string
- func (c Context) FlagValue(name string, fallback string) string
- func (c Context) FlagValues(name string) []string
- func (c Context) Getenv(key string) string
- func (c Context) HasFlag(name string) bool
- func (c Context) LastArg() string
- func (c Context) WithFlagValues(flagValues map[string][]string) Context
- type DirFilterable
- type Directive
- type FileFilterable
- type Item
- type PathFilterable
- type Predictor
- func Batch(predictors ...Predictor) Predictor
- func Callback(fn func(c Context) Predictor) Predictor
- func Dirs() Predictor
- func DirsFiltered(filter func(path string, entry os.DirEntry) bool) Predictor
- func DirsGlob(patterns ...string) Predictor
- func Executables() Predictor
- func FileContents(filePath string, parser func(content []byte) []Item) Predictor
- func FileLines(filePath string) Predictor
- func Files(extensions ...string) Predictor
- func FilesFiltered(filter func(path string, entry os.DirEntry) bool) Predictor
- func FilesGlob(patterns ...string) Predictor
- func Items(items ...Item) Predictor
- func KeyValue(valuesByKey map[string][]string) Predictor
- func KeyValueDescribed(valuesByKey map[string][]string, descriptionByKey map[string]string) Predictor
- func Map(items map[string]string) Predictor
- func MultiParts(delimiter string, fn func(c Context) Predictor) Predictor
- func None() Predictor
- func PathsFiltered(filter func(path string, entry os.DirEntry) bool) Predictor
- func Symlinks() Predictor
- func Values(values ...string) Predictor
- func (p Predictor) Exclude(values ...string) Predictor
- func (p Predictor) FilterText(toComplete string) Predictor
- func (p Predictor) Invoke(ctx Context) Result
- func (p Predictor) KeepOrder() Predictor
- func (p Predictor) NoSpace() Predictor
- func (p Predictor) Prefix(prefix string) Predictor
- func (p Predictor) Raw() []string
- func (p Predictor) Style(style string) Predictor
- func (p Predictor) Suffix(suffix string) Predictor
- func (p Predictor) Tag(tag string) Predictor
- func (p Predictor) Timeout(d time.Duration, alternative ...Predictor) Predictor
- func (p Predictor) Usage(message string) Predictor
- func (p Predictor) Usagef(format string, a ...any) Predictor
- type Result
Constants ¶
const DefaultTimeout = 250 * time.Millisecond
DefaultTimeout is the default execution timeout applied to dynamic predictor callbacks.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Context ¶
type Context struct {
// ToComplete is the word fragment under the cursor being completed. The
// implicit filtering term of a Predictor is derived from it unless
// FilterText has been called with a non-empty query.
ToComplete string
// Args holds the positional arguments parsed before ToComplete for the
// target command, in order.
Args []string
// Parts holds the already-completed segments of a MultiParts value (e.g.
// the key segment while completing key=val). The engine leaves it empty: it
// is populated by MultiParts for the nested predictor only.
Parts []string
// ParentParts holds the Parts segments of the enclosing MultiParts
// invocation. Like Parts, it is populated by MultiParts for the nested
// predictor, not by the engine.
ParentParts []string
// Flags maps each supplied flag name (including aliases and short forms)
// to the last supplied value. The engine populates it together with
// FlagMultiValues; the accessors treat FlagMultiValues as authoritative
// when both are set. Use FlagValue to read it with a fallback.
Flags map[string]string
// FlagMultiValues maps each supplied flag name (including aliases and
// short forms) to all supplied values in order. An empty entry counts as
// absent. Use FlagValues to read it.
FlagMultiValues map[string][]string
// Dir is the working directory used by filesystem predictors to resolve
// relative paths (empty means the process working directory). The App
// engine currently leaves it empty; SDK callers may set it explicitly.
Dir string
// Env holds the environment variables visible to the completion run,
// consulted by Getenv with a fallback to os.Getenv for absent keys. The
// App engine currently leaves it nil.
Env map[string]string
// EnvLookup queries the environment variables visible to the completion run.
// When non-nil, Getenv consults this callback before checking Env and falling
// back to os.Getenv.
EnvLookup func(key string) (string, bool)
}
Context provides contextual data and metadata about the current command line invocation being completed.
func (Context) Arg ¶
Arg returns the positional argument at the given 0-based index, or an empty string if out of bounds.
func (Context) FlagValue ¶
FlagValue returns the value of the named flag, or fallback if the flag is absent. It shares one precedence with FlagValues and HasFlag: the multi-value map is authoritative when both maps carry the flag.
func (Context) FlagValues ¶
FlagValues returns all values supplied for the named flag, or nil if absent. It shares one precedence with FlagValue and HasFlag: the multi-value map is authoritative when both maps carry the flag. The returned slice is a clone, so mutating it does not affect the context.
func (Context) Getenv ¶
Getenv returns the value of the environment variable named by key from the context's environment, checking EnvLookup first (if non-nil), then the Env map, falling back to os.Getenv when the key is absent.
func (Context) HasFlag ¶
HasFlag reports whether a flag with the given name was supplied. It shares one precedence with FlagValue and FlagValues: the multi-value map is authoritative when both maps carry the flag.
type DirFilterable ¶
type DirFilterable interface {
// MatchDir reports whether the directory entry at path satisfies the filter predicate.
MatchDir(path string, entry os.DirEntry) bool
}
DirFilterable is implemented by custom domain directory types that filter directories with a custom predicate. The engine only evaluates MatchDir for directory entries, including symlinks that resolve to directories.
type Directive ¶
type Directive int
Directive is a bitmask representing actions the shell completion script should perform.
const ( // DirectiveError indicates an error occurred and completions should be ignored. DirectiveError Directive = 1 << 0 // DirectiveNoSpace indicates the shell should not append a space after the candidate. DirectiveNoSpace Directive = 1 << 1 // DirectiveNoFileCompletion indicates the shell should not fall back to file completion. DirectiveNoFileCompletion Directive = 1 << 2 // DirectiveKeepOrder indicates the shell should preserve candidate ordering. DirectiveKeepOrder Directive = 1 << 3 )
type FileFilterable ¶
type FileFilterable interface {
// MatchFile reports whether the file entry at path satisfies the filter predicate.
MatchFile(path string, entry os.DirEntry) bool
}
FileFilterable is implemented by custom domain file types that filter files with a custom predicate.
type Item ¶
type Item struct {
// Value is the string inserted into the command line.
Value string
// Display is the menu label. Leaving it empty is supported: Items
// normalizes it to Value at construction, and the wire layer resolves an
// empty Display to Value when serializing candidates.
Display string
// Description is the optional help text shown next to the candidate.
Description string
// Style is the optional style token string from the internal style
// vocabulary (e.g. blue). Empty leaves styling to the shell theme.
Style string
// Tag is the optional grouping tag (e.g. commands, flags) used by
// tag-aware shells to group candidates in the menu.
Tag string
}
Item represents a single completion candidate with optional description, display label, and styling.
func (Item) WithDescription ¶
WithDescription returns a copy of the Item with the specified description.
func (Item) WithDisplay ¶
WithDisplay returns a copy of the Item with the specified display label.
type PathFilterable ¶
type PathFilterable interface {
// MatchPath reports whether the filesystem path and entry satisfy the filter predicate.
MatchPath(path string, entry os.DirEntry) bool
}
PathFilterable is implemented by custom domain path types that evaluate both files and directories.
type Predictor ¶
type Predictor struct {
// contains filtered or unexported fields
}
Predictor represents a completion candidate generator or combinator.
func Callback ¶
Callback defers candidate computation until invocation time using the provided function.
func DirsFiltered ¶
DirsFiltered configures in-process directory completion with a custom filter predicate. Only directories matching the predicate are offered; symlinks that resolve to directories are treated as directories. This filter is a predicate over directory entries, not the query match of Predictor.FilterText.
func DirsGlob ¶
DirsGlob configures in-process directory completion filtered by glob patterns. A directory is offered when its base name matches at least one pattern (filepath.Match syntax; a wildcard-free pattern such as build matches that literal name).
func Executables ¶
func Executables() Predictor
Executables configures completion of executable binaries found in the system $PATH or local relative paths when starting with '.' or '/'.
func FileContents ¶
FileContents reads a file relative to the completion context directory and extracts completion items using the provided parser.
func FilesFiltered ¶
FilesFiltered configures file completion with a custom filter predicate. Directories are retained for traversal, while files are filtered using the provided predicate. This filter is a predicate over directory entries, not the query match of Predictor.FilterText.
func FilesGlob ¶
FilesGlob configures in-process file completion filtered by glob patterns. Directories are retained for traversal, while files must match at least one pattern against their base name (filepath.Match syntax; a wildcard-free pattern such as Makefile matches that literal name).
func KeyValue ¶
KeyValue creates a segmented KEY=VALUE Predictor from a map of keys to allowed value slices.
func KeyValueDescribed ¶
func KeyValueDescribed(valuesByKey map[string][]string, descriptionByKey map[string]string) Predictor
KeyValueDescribed creates a segmented KEY=VALUE Predictor from a map of keys to allowed value slices, carrying a per-key description shown next to the key candidate. A nil or empty description map behaves exactly like KeyValue; an absent or empty description renders the key without one.
func Map ¶
Map creates a Predictor from a map of completion candidate values to descriptions, sorted by key.
func MultiParts ¶
MultiParts completes segmented tokens by splitting on a delimiter.
func None ¶
func None() Predictor
None creates a Predictor that suppresses completion and file fallbacks.
func PathsFiltered ¶
PathsFiltered configures completion where both files and directories are evaluated against the filter predicate. This filter is a predicate over directory entries, not the query match of Predictor.FilterText.
func (Predictor) Exclude ¶
Exclude returns a new Predictor that filters out candidates whose Value or Display matches any of the specified values.
func (Predictor) FilterText ¶
FilterText filters candidates by matching against the given query prefix. The argument replaces the implicit ctx.ToComplete term used during filtering; FilterText("") restores the implicit term. There is no "disable filtering" spelling. This method filters by query match: unlike the predicate-based FilesFiltered, DirsFiltered, and PathsFiltered constructors, whose filter argument is a predicate over directory entries.
func (Predictor) Invoke ¶
Invoke evaluates the Predictor against the given Context and returns the resolved Result.
func (Predictor) KeepOrder ¶
KeepOrder marks the predictor to instruct the shell to preserve candidate order.
func (Predictor) NoSpace ¶
NoSpace marks the predictor to instruct the shell not to append a space after completion.
func (Predictor) Raw ¶
Raw returns the statically stored completion candidate values: the raw strings recorded by constructors such as Values, Items, and Map, or the Value fields of the stored Items when no raw slice was recorded. It is a snapshot, not an evaluation: callbacks, batches, and MultiParts are not invoked (a callback-only predictor returns an empty slice), and while Exclude narrows the stored set, Prefix, Suffix, Style, and Tag are ignored because they apply to Result.Items only. The returned slice is always a fresh copy.
func (Predictor) Style ¶
Style sets a default style for candidates in this predictor that do not have their own style.
func (Predictor) Tag ¶
Tag sets a default group tag for candidates in this predictor that do not have their own tag.
func (Predictor) Timeout ¶
Timeout sets an execution deadline for the predictor with an optional fallback predictor. Passing d < 0 disables timeout enforcement for this predictor. Passing d == 0 (the default) applies DefaultTimeout. If more than one alternative predictor is passed, Timeout panics.
type Result ¶
type Result struct {
// Items holds the completion candidates. Their order is significant when
// Directive includes DirectiveKeepOrder: the wire layer forwards the
// keeporder instruction and the shell preserves the engine order.
Items []Item
// Directive is the bitmask of shell instructions produced by the
// predictor and its modifiers.
Directive Directive
// Usage is an ActiveHelp/tooltip hint accompanying the candidates, not
// syntax help. When Directive includes DirectiveError, the wire layer
// also uses it as the error message for shells with a message channel
// (an empty Usage renders the literal ERROR).
Usage string
}
Result represents the evaluated result of a Predictor against a Context.