predict

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 13 Imported by: 0

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:

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/compute-completion-candidates/ 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

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

func (c Context) Arg(index int) string

Arg returns the positional argument at the given 0-based index, or an empty string if out of bounds.

func (Context) FlagValue

func (c Context) FlagValue(name string, fallback string) string

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

func (c Context) FlagValues(name string) []string

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

func (c Context) Getenv(key string) string

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

func (c Context) HasFlag(name string) bool

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.

func (Context) LastArg

func (c Context) LastArg() string

LastArg returns the last positional argument, or an empty string if no arguments are present.

func (Context) WithFlagValues

func (c Context) WithFlagValues(flagValues map[string][]string) Context

WithFlagValues returns a shallow copy of the context with FlagMultiValues populated. If Flags is nil and flagValues is non-empty, Flags is also populated from the last entry of each 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
)

func (Directive) Has

func (d Directive) Has(flag Directive) bool

Has reports whether the directive contains the specified bitmask flag.

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

	// Alias marks the candidate as an alternative spelling of another
	// candidate: a subcommand or flag alias declared on the command schema, or
	// a domain alias (such as a taskfile task alias) supplied by a predictor.
	// Aliases are offered by default and can be suppressed by the user with
	// the application-prefixed completion aliases sideband (<APP>_COMPLETION_ALIASES).
	Alias bool
}

Item represents a single completion candidate with optional description, display label, and styling.

func NewItem

func NewItem(value, description string) Item

NewItem constructs a new Item candidate with the given value and description.

func (Item) WithAlias added in v0.3.0

func (i Item) WithAlias() Item

WithAlias returns a copy of the Item marked as an alias of another candidate. Predictors completing domain aliases (for example taskfile task aliases) use this so the user can suppress them with the completion aliases sideband.

func (Item) WithDescription

func (i Item) WithDescription(description string) Item

WithDescription returns a copy of the Item with the specified description.

func (Item) WithDisplay

func (i Item) WithDisplay(display string) Item

WithDisplay returns a copy of the Item with the specified display label.

func (Item) WithStyle

func (i Item) WithStyle(style string) Item

WithStyle returns a copy of the Item with the specified style applied.

func (Item) WithTag

func (i Item) WithTag(tag string) Item

WithTag returns a copy of the Item with the specified group tag.

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 Batch

func Batch(predictors ...Predictor) Predictor

Batch combines multiple predictors into a single aggregated predictor.

func Callback

func Callback(fn func(c Context) Predictor) Predictor

Callback defers candidate computation until invocation time using the provided function.

func Dirs

func Dirs() Predictor

Dirs configures in-process directory completion.

func DirsFiltered

func DirsFiltered(filter func(path string, entry os.DirEntry) bool) Predictor

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

func DirsGlob(patterns ...string) Predictor

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

func FileContents(filePath string, parser func(content []byte) []Item) Predictor

FileContents reads a file relative to the completion context directory and extracts completion items using the provided parser.

func FileLines

func FileLines(filePath string) Predictor

FileLines configures completion of non-empty, non-comment lines from a file.

func Files

func Files(extensions ...string) Predictor

Files configures in-process file completion with optional file extension filters.

func FilesFiltered

func FilesFiltered(filter func(path string, entry os.DirEntry) bool) Predictor

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

func FilesGlob(patterns ...string) Predictor

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 Items

func Items(items ...Item) Predictor

Items creates a Predictor with the specified completion items.

func KeyValue

func KeyValue(valuesByKey map[string][]string) Predictor

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

func Map(items map[string]string) Predictor

Map creates a Predictor from a map of completion candidate values to descriptions, sorted by key.

func MultiParts

func MultiParts(delimiter string, fn func(c Context) Predictor) Predictor

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

func PathsFiltered(filter func(path string, entry os.DirEntry) bool) Predictor

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 Symlinks() Predictor

Symlinks configures completion of symbolic links.

func Values

func Values(values ...string) Predictor

Values creates a Predictor from static candidate value strings.

func (Predictor) Exclude

func (p Predictor) Exclude(values ...string) Predictor

Exclude returns a new Predictor that filters out candidates whose Value or Display matches any of the specified values.

func (Predictor) FilterText

func (p Predictor) FilterText(toComplete string) Predictor

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

func (p Predictor) Invoke(ctx Context) Result

Invoke evaluates the Predictor against the given Context and returns the resolved Result.

func (Predictor) KeepOrder

func (p Predictor) KeepOrder() Predictor

KeepOrder marks the predictor to instruct the shell to preserve candidate order.

func (Predictor) NoSpace

func (p Predictor) NoSpace() Predictor

NoSpace marks the predictor to instruct the shell not to append a space after completion.

func (Predictor) Prefix

func (p Predictor) Prefix(prefix string) Predictor

Prefix prepends a prefix string to all candidate values.

func (Predictor) Raw

func (p Predictor) Raw() []string

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

func (p Predictor) Style(style string) Predictor

Style sets a default style for candidates in this predictor that do not have their own style.

func (Predictor) Suffix

func (p Predictor) Suffix(suffix string) Predictor

Suffix appends a suffix string to all candidate values.

func (Predictor) Tag

func (p Predictor) Tag(tag string) Predictor

Tag sets a default group tag for candidates in this predictor that do not have their own tag.

func (Predictor) Timeout

func (p Predictor) Timeout(d time.Duration, alternative ...Predictor) Predictor

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.

func (Predictor) Usage

func (p Predictor) Usage(message string) Predictor

Usage attaches an ActiveHelp/tooltip hint message to the predictor. This is completion-time guidance, not the root package's syntax-help usage summary (Session.Usage and App.UsageOnError).

func (Predictor) Usagef

func (p Predictor) Usagef(format string, a ...any) Predictor

Usagef attaches a formatted ActiveHelp/tooltip hint message to the predictor using fmt.Sprintf. See Usage for the distinction from the root package's syntax-help usage summary.

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.

Jump to

Keyboard shortcuts

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