Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

feat(completions): ship dynamic registration for package installs (#3105)

Ben Druckerad43df7656c9
diff --git a/src/cli/config.rs b/src/cli/config.rs
index 39a3de6e7..5c733956e 100644
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -154,12 +154,11 @@ Detects various forms of the integration pattern regardless of:
)]
ShowTheme,
- /// Generate static shell completions for package managers
+ /// Generate shell completions for package managers
///
- /// Outputs static completion scripts for Homebrew and other package managers.
- /// Only completes commands and flags, not branch names.
- /// This is predominantly for package managers. Users should run
- /// `wt config shell install` instead.
+ /// Outputs a completion registration that calls the binary at TAB time, so branch and
+ /// worktree names complete from a plain package install. For interactive setup, run
+ /// `wt config shell install` instead. It also enables directory changing on switch.
#[command(hide = true)]
Completions {
/// Shell to generate completions for
diff --git a/src/commands/init.rs b/src/commands/init.rs
index de15f6bf3..0df1f1fbf 100644
--- a/src/commands/init.rs
+++ b/src/commands/init.rs
@@ -1,12 +1,11 @@
use anyhow::Context;
-use clap::CommandFactory;
-use clap_complete::generate;
+use clap_complete::env::{
+ Bash as EnvBash, EnvCompleter, Fish as EnvFish, Powershell as EnvPowershell, Zsh as EnvZsh,
+};
use std::io::{self, Write};
use worktrunk::shell;
use worktrunk::styling::println;
-use crate::cli::Cli;
-
pub fn handle_init(shell: shell::Shell, cmd: String) -> Result<(), String> {
let init = shell::ShellInit::with_prefix(shell, cmd);
@@ -20,46 +19,51 @@ pub fn handle_init(shell: shell::Shell, cmd: String) -> Result<(), String> {
Ok(())
}
-/// Generate static shell completions to stdout.
+/// Generate shell completions to stdout for package manager integration.
///
/// This is the handler for `wt config shell completions <shell>`. It outputs completion
/// scripts suitable for package manager integration (e.g., Homebrew's
/// `generate_completions_from_executable`).
///
+/// Bash, Zsh, Fish, and PowerShell all emit a *dynamic* registration: the same
+/// script `COMPLETE=<shell> wt` prints, which calls the binary at TAB time. This
+/// means a plain package install gets live branch and worktree name completion with
+/// no `wt config shell install`. Zsh additionally needs a thin transform so the
+/// script works when autoloaded from `fpath` (Homebrew installs it as
+/// `site-functions/_wt`). See `make_zsh_autoload_safe`. The other three need no
+/// transform: Homebrew sources bash files, autoloads fish completion files by
+/// command name, and PowerShell registrations are sourced into the profile.
+///
+/// Nushell uses template-based integration (the shell wrapper and completer in one
+/// file), which is already dynamic, so its output is the full `init` template.
+///
/// Unlike `wt config shell init`, this does not:
/// - Modify any files
/// - Include shell integration (cd-on-switch functionality)
-/// - Register dynamic completions
-///
-/// TODO(completions): We output static completions because that's the package manager
-/// convention, but dynamic completions (one-liner that calls the binary at tab-time)
-/// might be better—users would get branch name completion. See the fish example in
-/// `~/.config/fish/completions/wt.fish` which calls `COMPLETE=fish wt` at runtime.
-/// Other tools like gh/kubectl also call their binaries at runtime.
pub fn handle_completions(shell: shell::Shell) -> anyhow::Result<()> {
- let mut cmd = Cli::command();
let cmd_name = crate::binary_name();
let mut stdout = io::stdout();
match shell {
shell::Shell::Bash => {
- generate(
- clap_complete::shells::Bash,
- &mut cmd,
- &cmd_name,
- &mut stdout,
- );
- }
- shell::Shell::Fish => {
- generate(
- clap_complete::shells::Fish,
- &mut cmd,
- &cmd_name,
- &mut stdout,
- );
+ EnvBash
+ .write_registration("COMPLETE", &cmd_name, &cmd_name, &cmd_name, &mut stdout)
+ .context("failed to write bash completion registration")?;
}
shell::Shell::Zsh => {
- generate(clap_complete::shells::Zsh, &mut cmd, &cmd_name, &mut stdout);
+ let mut buf = Vec::new();
+ EnvZsh
+ .write_registration("COMPLETE", &cmd_name, &cmd_name, &cmd_name, &mut buf)
+ .context("failed to write zsh completion registration")?;
+ let script = String::from_utf8(buf)
+ .context("zsh completion registration was not valid UTF-8")?;
+ let script = make_zsh_autoload_safe(&script, &cmd_name);
+ write!(stdout, "{}", script).context("failed to write to stdout")?;
+ }
+ shell::Shell::Fish => {
+ EnvFish
+ .write_registration("COMPLETE", &cmd_name, &cmd_name, &cmd_name, &mut stdout)
+ .context("failed to write fish completion registration")?;
}
shell::Shell::Nushell => {
// Nushell uses template-based integration (shell wrapper + completions in one)
@@ -71,14 +75,47 @@ pub fn handle_completions(shell: shell::Shell) -> anyhow::Result<()> {
write!(stdout, "{}", code).context("failed to write to stdout")?;
}
shell::Shell::PowerShell => {
- generate(
- clap_complete::shells::PowerShell,
- &mut cmd,
- &cmd_name,
- &mut stdout,
- );
+ EnvPowershell
+ .write_registration("COMPLETE", &cmd_name, &cmd_name, &cmd_name, &mut stdout)
+ .context("failed to write powershell completion registration")?;
}
}
Ok(())
}
+
+/// Make clap's dynamic zsh registration safe to autoload from `fpath`.
+///
+/// clap's registration ends with `compdef <func> <cmd>`, which assumes the script is
+/// sourced or eval'd. Homebrew instead installs it as `site-functions/_<cmd>` and lets
+/// compinit autoload it on the first completion, where the file body runs as the `_<cmd>`
+/// completion function. In that mode a bare `compdef` is too late. zsh expects the file
+/// to *perform* the completion, not register a handler.
+///
+/// The replacement is a dual-mode guard: when `funcstack[1]` is `_<cmd>` (autoloaded),
+/// call clap's completer directly. Otherwise (sourced/eval'd) register it via `compdef`.
+/// The leading `#compdef <cmd>` line clap already emits stays first, which is what marks
+/// the file for compinit autoload.
+///
+/// The two display zstyles match `templates/zsh.zsh` so package-installed users get the
+/// same single-column branch listing as `install` users. They precede the guard because
+/// in autoload mode the whole file body runs as `_<cmd>` on every completion: setting the
+/// styles before the completer call means `_describe` sees them on the *first* TAB, not
+/// only on the second.
+fn make_zsh_autoload_safe(script: &str, cmd_name: &str) -> String {
+ let func = format!("_clap_dynamic_completer_{}", cmd_name.replace('-', "_"));
+ let trailing = format!("compdef {func} {cmd_name}");
+ let replacement = format!(
+ r#"# Single-column display keeps descriptions visually associated with each branch.
+zstyle ':completion:*:{cmd_name}:*' list-max 1
+# Prevent grouping branches with identical descriptions (same timestamp) on one line.
+zstyle ':completion:*:*:{cmd_name}:*' list-grouped false
+
+if [ "$funcstack[1]" = "_{cmd_name}" ]; then
+ {func} "$@"
+else
+ compdef {func} {cmd_name}
+fi"#
+ );
+ script.replace(&trailing, &replacement)
+}
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap b/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap
index dd7888814..be3f1a9b7 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap
@@ -74,14 +74,7 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
# Use `command` to bypass the shell function and call the binary directly.
# Without this, `wt` would call the shell function which evals
# the completion script internally but doesn't re-emit it.
- #
- # The -V flag creates an unsorted group, preserving our recency-based
- # ordering instead of zsh's default alphabetical sort.
- # Note: _describe's -V does NOT take an argument - it just sets a flag.
- # The _describe function internally passes -o nosort to compadd.
- # TODO(clap): Ideally clap_complete would preserve ordering natively.
- # See: https://github.com/clap-rs/clap/issues/5752
- eval "$(COMPLETE=zsh command "${WORKTRUNK_BIN:-wt}" 2>/dev/null | sed "s/_describe 'values'/_describe -V 'values'/")" || return
+ eval "$(COMPLETE=zsh command "${WORKTRUNK_BIN:-wt}" 2>/dev/null)" || return
fi
_clap_dynamic_completer_wt "$@"
}
diff --git a/templates/zsh.zsh b/templates/zsh.zsh
index d013d8ba9..7de32d1f6 100644
--- a/templates/zsh.zsh
+++ b/templates/zsh.zsh
@@ -70,14 +70,7 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
# Use `command` to bypass the shell function and call the binary directly.
# Without this, `{{ cmd }}` would call the shell function which evals
# the completion script internally but doesn't re-emit it.
- #
- # The -V flag creates an unsorted group, preserving our recency-based
- # ordering instead of zsh's default alphabetical sort.
- # Note: _describe's -V does NOT take an argument - it just sets a flag.
- # The _describe function internally passes -o nosort to compadd.
- # TODO(clap): Ideally clap_complete would preserve ordering natively.
- # See: https://github.com/clap-rs/clap/issues/5752
- eval "$(COMPLETE=zsh command "${WORKTRUNK_BIN:-{{ cmd }}}" 2>/dev/null | sed "s/_describe 'values'/_describe -V 'values'/")" || return
+ eval "$(COMPLETE=zsh command "${WORKTRUNK_BIN:-{{ cmd }}}" 2>/dev/null)" || return
fi
_clap_dynamic_completer_{{ cmd }} "$@"
}
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index 9b123a986..c4c0315c9 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -1441,13 +1441,15 @@ test = "cargo test"
}
}
-/// Test static shell completions command for package managers.
+/// Test shell completions command for package managers.
///
-/// The `wt config shell completions <shell>` command outputs static completion
-/// scripts suitable for package manager integration (e.g., Homebrew's
-/// `generate_completions_from_executable`).
+/// The `wt config shell completions <shell>` command outputs completion scripts
+/// suitable for package manager integration (e.g., Homebrew's
+/// `generate_completions_from_executable`). For bash and zsh the output is a
+/// *dynamic* registration that calls the binary at TAB time, so branch and
+/// worktree names complete on a plain package install.
#[rstest]
-fn test_static_completions_for_all_shells() {
+fn test_completions_for_all_shells() {
// Test each supported shell produces valid output
for shell in ["bash", "fish", "nu", "zsh", "powershell"] {
let output = wt_command()
@@ -1474,18 +1476,91 @@ fn test_static_completions_for_all_shells() {
stdout.contains("complete") || stdout.contains("_wt"),
"{shell}: should contain bash completion markers"
);
+ // Dynamic registration: clap's runtime completer function plus a
+ // `complete -F` binding that calls the binary at TAB time.
+ assert!(
+ stdout.contains("_clap_complete_wt"),
+ "{shell}: should contain clap's dynamic completer function, got:\n{stdout}"
+ );
+ assert!(
+ stdout.contains("complete -") && stdout.contains("-F _clap_complete_wt wt"),
+ "{shell}: should register the dynamic completer via complete -F, got:\n{stdout}"
+ );
+ // The old static output built `COMPREPLY` from a hardcoded word list via
+ // `compgen`. Dynamic output asks the binary for candidates instead.
+ assert!(
+ !stdout.contains("compgen"),
+ "{shell}: should not contain static compgen boilerplate, got:\n{stdout}"
+ );
}
"fish" => {
assert!(
stdout.contains("complete") && stdout.contains("wt"),
"{shell}: should contain fish completion markers"
);
+ // Dynamic registration: a single `complete --command wt` whose argument
+ // source calls the binary at TAB time. The static output instead listed
+ // subcommands via `-n`/`__fish_*` predicates.
+ assert!(
+ stdout.contains("--command wt") && stdout.contains("COMPLETE=fish"),
+ "{shell}: should call the binary at TAB time, got:\n{stdout}"
+ );
+ assert!(
+ !stdout.contains("__fish_"),
+ "{shell}: should not contain static __fish_ predicate boilerplate, got:\n{stdout}"
+ );
}
"zsh" => {
assert!(
stdout.contains("#compdef") || stdout.contains("_wt"),
"{shell}: should contain zsh completion markers"
);
+ // Dynamic registration: the `#compdef` autoload marker, clap's runtime
+ // completer that calls the binary at TAB time, and the autoload guard.
+ assert!(
+ stdout.contains("#compdef wt"),
+ "{shell}: should contain the #compdef autoload marker, got:\n{stdout}"
+ );
+ assert!(
+ stdout.contains(r#"COMPLETE="zsh""#)
+ && stdout.contains(r#"wt -- "${words[@]}""#),
+ "{shell}: should call the binary at TAB time, got:\n{stdout}"
+ );
+ // Dual-mode guard: autoloaded from fpath -> complete directly; sourced -> compdef.
+ // `funcstack[1]` is the discriminating token (absent from clap's raw output);
+ // the `compdef` must sit *inside* the guard (after the funcstack check), not as
+ // clap's bare trailing line. That ordering is what proves the transform applied.
+ let funcstack_pos = stdout
+ .find("funcstack[1]")
+ .expect("dynamic zsh registration should contain the autoload guard");
+ let compdef_pos = stdout
+ .find("compdef _clap_dynamic_completer_wt wt")
+ .expect("guard should register via compdef when sourced");
+ assert!(
+ funcstack_pos < compdef_pos,
+ "{shell}: compdef must sit inside the guard, after the funcstack check, got:\n{stdout}"
+ );
+ // Single-column display zstyles, matched to `templates/zsh.zsh`.
+ assert!(
+ stdout.contains("list-max 1") && stdout.contains("list-grouped false"),
+ "{shell}: should append the single-column display zstyles, got:\n{stdout}"
+ );
+ // The zstyles must precede the guard. In autoload mode the whole file body
+ // runs as `_wt` on every completion, so setting the styles before the
+ // completer call is what makes single-column listing apply on the FIRST TAB.
+ // Regression guard for the bug where the zstyles followed the guard.
+ let zstyle_pos = stdout.find("list-max 1").unwrap();
+ let guard_pos = stdout.find("funcstack[1]").unwrap();
+ assert!(
+ zstyle_pos < guard_pos,
+ "{shell}: display zstyles must come before the autoload guard, got:\n{stdout}"
+ );
+ // The old static output drove completion from `_arguments`. Dynamic output
+ // builds the candidate list from the binary instead.
+ assert!(
+ !stdout.contains("_arguments"),
+ "{shell}: should not contain static _arguments boilerplate, got:\n{stdout}"
+ );
}
"nu" => {
// Nushell uses template-based integration, not clap_complete
@@ -1504,6 +1579,12 @@ fn test_static_completions_for_all_shells() {
|| stdout.contains("$scriptBlock"),
"{shell}: should contain PowerShell completion markers"
);
+ // Dynamic registration: the completer invokes the binary at TAB time
+ // (sets COMPLETE and calls `wt`), rather than embedding a static word list.
+ assert!(
+ stdout.contains(r#"COMPLETE = "powershell""#) && stdout.contains("wt"),
+ "{shell}: should call the binary at TAB time, got:\n{stdout}"
+ );
}
_ => {}
}
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index ecb095447..d522a81a5 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -118,14 +118,7 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
# Use `command` to bypass the shell function and call the binary directly.
# Without this, `wt` would call the shell function which evals
# the completion script internally but doesn't re-emit it.
- #
- # The -V flag creates an unsorted group, preserving our recency-based
- # ordering instead of zsh's default alphabetical sort.
- # Note: _describe's -V does NOT take an argument - it just sets a flag.
- # The _describe function internally passes -o nosort to compadd.
- # TODO(clap): Ideally clap_complete would preserve ordering natively.
- # See: https://github.com/clap-rs/clap/issues/5752
- eval "$(COMPLETE=zsh command "${WORKTRUNK_BIN:-wt}" 2>/dev/null | sed "s/_describe 'values'/_describe -V 'values'/")" || return
+ eval "$(COMPLETE=zsh command "${WORKTRUNK_BIN:-wt}" 2>/dev/null)" || return
fi
_clap_dynamic_completer_wt "$@"
}