Skip to main content

Crate veks_completion

Crate veks_completion 

Source
Expand description

Dynamic shell completion engine for CLI tools.

Provides a generic, tree-based completion system that completes one level at a time (no eager subcommand chaining). The caller defines the command tree via CommandTree, and this crate handles:

  • Walking the tree to find candidates for a given input
  • Filtering out options already present on the command line
  • Handling bare key=value params alongside --flag options
  • Dynamic option discovery from command-line context (e.g., reading a workload file to discover its declared parameters)
  • Generating bash completion scripts
  • Handling the _<APP>_COMPLETE=bash env var callbacks

§Usage

use veks_completion::{CommandTree, Node, complete, print_bash_script, handle_complete_env};

let tree = CommandTree::new("myapp")
    .command("run", Node::leaf(&["--dry-run", "--threads"]))
    .command("check", Node::leaf(&["--all", "--quiet"]))
    .group("pipeline", Node::group(vec![
        ("compute", Node::group(vec![
            ("knn", Node::leaf(&["--base", "--query", "--metric"])),
        ])),
    ]));

// In main():
if handle_complete_env("myapp", &tree) {
    std::process::exit(0);
}

Re-exports§

pub use cli::render_help;
pub use cli::CommandSpec;
pub use cli::OptionSpec;
pub use cli::ParsedArgs;
pub use cli::PositionalSpec;
pub use cli::VeksCli;
pub use options::CommandOption;
pub use options::OptionConflict;
pub use options::OptionDef;
pub use options::OptionRegistry;
pub use options::ParseMismatch;

Modules§

cli
The veks-completion CLI framework: argument parsing, help, and a command definition model — the in-tree replacement for clap.
options
Shared, per-command option definitions with a project-wide consistency guarantee.
providers
Built-in SubtreeProviders that downstream embedders can attach to a Node to enable common context-sensitive completion scenarios without implementing a grammar from scratch.

Structs§

BracketState
Bracket / quote depth at the cursor, computed by PartialParse::bracket_state. Lets a grammar-aware provider answer “am I inside a {...}, (...), [...], or quoted string?” without re-implementing the scanner.
CommandTree
The top-level command tree for an application.
Directive
A richer flag descriptor that bundles the CLI form, optional YAML mirror, value semantics, and repeatability into one declaration. Adapters can expand a &[Directive] into per-flag completion + parse rules without the caller writing a parallel translation layer.
Extras
Free-form payload slot on a Node (TODO item 8). Wraps an Arc<dyn Any + Send + Sync> so embedders can attach handler types, parser state, or anything else without forcing veks-completion to grow generic parameters or hard dependencies.
Node
Carries two metadata fields used by stratified (multi-tap) completion:
ParsedCommand
Result of parse_argv — a structured view of an argv vector against a CommandTree. Embedders use this to dispatch handlers without writing a parallel walker.
PartialParse
Structured snapshot of the partial command-line state at the cursor position. Passed to subtree providers so they can offer context-aware completions without re-tokenising COMP_LINE.
StrictNode
Type-state wrapper around Node that tracks at the type level whether the node has been given a category and an explicit tap-tier level.
TapState
Persistable tap state — the bytes a driver would write between tap events. Two fields: the wall-clock ms at which the tap happened, and the count to persist (which is the layer just shown, or 0 if we just closed the cycle by hitting max_level).

Enums§

ClosedValues
A closed set of valid values for a flag. Both static (&'static [&'static str]) and runtime-owned (Vec<String>) variants are supported via the same query API.
MetadataError
Errors produced by CommandTree::validate.
ParseError
Errors returned by parse_argv.
Shell
Supported shells for completion-script generation.
Stability
A node in the command tree.

Constants§

DEFAULT_LEVEL
Default visibility tier when a node doesn’t explicitly opt into a higher tier. Tier 1 means “show on the very first tab tap” — preserves the pre-stratification behavior for existing apps that haven’t categorized their commands.
DIAGNOSTIC_FLAGS
Check for completion env vars and handle them.
SUBTREE_PROVIDER_MAX_TAPS
Cap on rapid-tap advancement when the resolved completion path includes a SubtreeProvider. The provider owns its candidate output and may layer it by tap (e.g. tap 1 = primary set, tap 2 = primary + secondary), so the engine can’t infer a meaningful max from tree shape alone. This constant defines how many tap tiers the engine will surface to a provider before the cadence rule resets back to tap 1.
TAP_ADVANCE_MS
Window inside which a same-key tap counts as a rapid follow-up and advances to the next layer. Outside this window, the next tap starts fresh at layer 1. Exposed so embedders can mention or match the same value in their own UX.

Traits§

CategoryTag
Discovery-category abstraction.
LevelTag
Discovery-tier abstraction symmetric with CategoryTag.

Functions§

apply_directives
Apply a slice of Directives to a Node in one call. Each directive becomes:
closed_set
Build a ValueProvider over a fixed set of candidate values, filtered by the typed prefix. This is the completion side of a closed-set option — e.g. the derive emits it for #[arg(value_parser = ["text", "csv", "json"])] so the same single declaration that drives parsing also feeds tab-completion.
complete
Compute completion candidates for the given input words.
complete_at_level_only
Rotating-tier completion. Returns root-level candidates whose Node::level() == only_level (NOT the cumulative <= set), so successive tab taps cycle through tiers one at a time and wrap around after the highest. Once the user starts typing a specific name, behaves identically to complete — the level filter applies only at the root with an empty partial.
complete_at_tap
Stratified completion: returns root-level candidates with Node::level() <= tap_count, so the Nth tab tap reveals progressively more commands. Inside a subcommand or with a non-empty partial, behaves identically to complete — the level filter applies only when the user is at the root prompt with no prefix typed.
complete_at_tap_with_raw
Same as complete_at_tap but additionally accepts the raw COMP_LINE and the cursor’s byte offset. Subtree providers receive these in PartialParse::raw_line / PartialParse::cursor_offset, enabling grammar-aware completion (e.g. for embedded query DSLs like MetricsQL or PromQL where bracket / quote / operator state at the cursor matters).
complete_expanded
Expanded completion: show all group command pairs.
complete_rotating
Convenience wrapper over complete_at_level_only that maps the raw tap counter to the rotating level. Cycle length is computed relative to whichever group node the user has descended into — a subgroup with only level-1 children has a cycle length of 1 (every tap shows the same set), while a subgroup with Primary+Secondary+Advanced children has a cycle length of 3. A tap beyond the cycle wraps back to level 1.
complete_rotating_with_raw
Same as complete_rotating but additionally threads the raw COMP_LINE and cursor offset through to subtree providers via PartialParse::raw_line / PartialParse::cursor_offset. Used by handle_complete_env so grammar-aware providers can inspect raw text + cursor position.
completions_registered_marker
The environment variable the completion-registration script exports to mark that completions are wired up in the current shell — e.g. _VECTORDATA_COMPLETIONS_REGISTERED. The binary checks it (see hint_completions_unregistered) to decide whether to nudge the user.
detect_shell
Detect the user’s interactive shell.
fn_provider
Helper to wrap a fn-pointer provider into the closure-typed ValueProvider. Most existing global providers use plain fn pointers and call this when registering.
handle_complete_env
handle_diagnostic_args
Triple-dash diagnostic dispatcher. Inspect std::env::args for a recognised ---* flag (see DIAGNOSTIC_FLAGS) and, if found, run the corresponding diagnostic and return true. The caller should process::exit(0) (or just return) when this returns true, exactly like handle_complete_env.
hint_completions_unregistered
Print a one-line nudge to stderr when tab-completion for app_name is not yet enabled in this shell, telling the user how to turn it on permanently. Call once per normal (non-completion) invocation.
next_tap_state
Pure cadence rule. Given the previous persisted state (and the input key it was recorded against), the current time, the current input key, and the max layer count for the current group, returns:
parse_argv
Parse argv (excluding the program name) against the supplied CommandTree. Walks subcommands, collects flags, separates positionals.
parse_argv_lenient
Lenient variant of parse_argv — unknown flags are treated as positionals rather than rejected. Useful for “pass-through” CLIs that wrap external commands.
print_bash_script
Generate a bash completion script that calls back into the app.
print_completions
Print a direct completion script for <app> completions --shell <shell>. This is what the indirect wrapper sources at shell startup; callers can invoke it directly when they want the raw script in stdout.
print_indirect_wrapper
Print a completions snippet for <app> completions (no --shell) — the convenience entry point users typically call once at shell startup. Auto-detects the user’s shell and emits a comment header plus an indirect-source <(...) line that pulls the actual script from <app> completions --shell <shell>.
print_partial_parse_for_diagnostics
Pretty-print the engine’s view of a PartialParse for the ---trace-partial-parse and downstream provider diagnostic flags. Public so provider-specific diagnostic dispatchers (e.g. crate::providers::metricsql_diagnostic_args) can reuse the same output format.
render_usage
Render a --help-style usage block for a node at the given path (TODO item 6). The same model that drives tab completion drives help, so the two surfaces can’t drift.
shell_ready_candidates
Convert semantic candidates into the exact bytes handed to bash.
trace_completion_candidates
Pure core of the ---trace-completion diagnostic: run the completion engine for user_line (the command line as typed AFTER the binary name, e.g. "datasets li") with the cursor at byte offset user_point within it (default: end of line), and return exactly the lines the diagnostic prints.

Type Aliases§

DynamicOptionsProvider
A function that provides additional option candidates based on context.
SubtreeProvider
Type alias for group-level context-aware completion providers (TODO item 7). Receives a structured PartialParse of the command line state and returns candidates to merge into the completer’s output.
ValueProvider
A function that provides dynamic completion values for a specific option.