Skip to content

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

feat(completion): mirror wrapped built-in for alias arg completion (#3172)

Zexin Yuan22484860e85c
diff --git a/docs/content/extending.md b/docs/content/extending.md
index 77349b766..772fac056 100644
--- a/docs/content/extending.md
+++ b/docs/content/extending.md
@@ -88,6 +88,8 @@ For indexing (`{{ args[0] }}`), looping, and counting, see [Passing values](@/ho
Tokens after `--` forward unconditionally, bypassing any binding. Writing `wt deploy -- --branch=foo` forwards the literal `--branch=foo` to `{{ args }}` even though the template references `{{ branch }}`.
+An alias that forwards `{{ args }}` to a `wt` command — like `co = "wt switch {{ args }}"` or `cm = "wt step commit {{ args }}"` — inherits that command's argument and flag completion, so `wt co <Tab>` completes branches the same way `wt switch <Tab>` does.
+
### Inspecting and previewing
- `wt config alias show <name>` prints the template.
diff --git a/skills/worktrunk/reference/extending.md b/skills/worktrunk/reference/extending.md
index 101ac86e7..091080eed 100644
--- a/skills/worktrunk/reference/extending.md
+++ b/skills/worktrunk/reference/extending.md
@@ -88,6 +88,8 @@ For indexing (`{{ args[0] }}`), looping, and counting, see [Passing values](http
Tokens after `--` forward unconditionally, bypassing any binding. Writing `wt deploy -- --branch=foo` forwards the literal `--branch=foo` to `{{ args }}` even though the template references `{{ branch }}`.
+An alias that forwards `{{ args }}` to a `wt` command — like `co = "wt switch {{ args }}"` or `cm = "wt step commit {{ args }}"` — inherits that command's argument and flag completion, so `wt co <Tab>` completes branches the same way `wt switch <Tab>` does.
+
### Inspecting and previewing
- `wt config alias show <name>` prints the template.
diff --git a/src/completion.rs b/src/completion.rs
index 46014e412..95a4e401a 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -9,7 +9,9 @@ use clap_complete::env::CompleteEnv;
use crate::cli;
use crate::commands::{AliasMap, load_aliases};
use crate::display::format_relative_time_short;
-use worktrunk::config::{CommandConfig, ProjectConfig, UserConfig};
+use worktrunk::config::{
+ ALIAS_ARGS_KEY, CommandConfig, ProjectConfig, UserConfig, template_references_var,
+};
use worktrunk::git::{BranchCategory, HookType, Repository};
/// Handle shell-initiated completion requests via `COMPLETE=$SHELL wt`
@@ -547,7 +549,16 @@ fn inject_alias_subcommands(cmd: Command) -> Command {
if cmd.get_subcommands().any(|s| s.get_name() == name.as_str()) {
continue;
}
- cmd = cmd.subcommand(build_alias_completion_command(name, entry.representative()));
+ // Mirror the wrapped built-in leaf when the alias forwards {{ args }}
+ // to one (e.g. `co = "wt switch {{ args }}"` gets switch's completion,
+ // `cm = "wt step commit {{ args }}"` gets step-commit's); otherwise fall
+ // back to the generic alias stub.
+ let rep = entry.representative();
+ let stub = match mirror_builtin_leaf(rep, &cmd) {
+ Some(leaf) => mirror_alias_command(leaf, name, rep),
+ None => build_alias_completion_command(name, rep),
+ };
+ cmd = cmd.subcommand(stub);
}
// Step-level injection: keep historical `wt step <alias>` completions.
cmd.mut_subcommand("step", |mut step| {
@@ -567,6 +578,82 @@ fn inject_alias_subcommands(cmd: Command) -> Command {
})
}
+/// If an alias forwards `{{ args }}` from exactly one command that invokes a
+/// `wt` subcommand chain, return a clone of the deepest **leaf** subcommand it
+/// targets — so completion can mirror that subcommand's flags + positional
+/// completers under the alias name (e.g. `co = "wt switch {{ args }}"` mirrors
+/// `switch`, `cm = "wt step commit {{ args }}"` mirrors `step commit`).
+///
+/// Detection gates, each load-bearing:
+/// - **`template_references_var` per command** (minijinja, not a substring) —
+/// scoped to each command rather than the cross-command union returned by
+/// `referenced_vars_for_config`, so a non-forwarding sibling referencing
+/// `{{ args }}` can't flip mirroring on. Satisfies CLAUDE.md's "Use Existing
+/// Dependencies" rule.
+/// - **Exactly one forwarder.** Zero means the alias ignores CLI positionals;
+/// many means args fan out and mirroring any one would mislead.
+/// - **Leading `wt`.** Bare `switch {{ args }}` runs the shell builtin, not wt.
+/// - **Tree-walk to a leaf.** Descend `find_subcommand` token by token, stopping
+/// at the first non-subcommand token (a flag, positional, or `{{`); mirror
+/// only if the walk lands on a leaf. A bare dispatcher (`wt step {{ args }}`)
+/// lands on a non-leaf and bails — it never offers the dispatcher's children.
+fn mirror_builtin_leaf(rep: &CommandConfig, root: &Command) -> Option<Command> {
+ // Exactly one command forwards CLI args via {{ args }}.
+ let mut forwarders = rep
+ .commands()
+ .filter(|c| template_references_var(&c.template, ALIAS_ARGS_KEY))
+ .collect::<Vec<_>>();
+ if forwarders.len() != 1 {
+ return None;
+ }
+ let template = &forwarders.pop()?.template;
+
+ // Leading `wt` — bare `switch {{ args }}` runs the shell builtin, not wt.
+ let mut tokens = template.split_whitespace();
+ if tokens.next()? != "wt" {
+ return None;
+ }
+
+ // Descend the tree through subcommand tokens; stop at the first token that
+ // isn't a subcommand (a flag, a positional, or `{{`).
+ let mut node = root;
+ let mut descended = false;
+ for tok in tokens {
+ match node.find_subcommand(tok) {
+ Some(child) => {
+ node = child;
+ descended = true;
+ }
+ None => break,
+ }
+ }
+
+ // Mirror only leaves, and only if we actually descended (rejects a bare
+ // `wt {{ args }}` with no subcommand).
+ if !descended || node.get_subcommands().next().is_some() {
+ return None;
+ }
+ Some(node.clone())
+}
+
+/// Build the completion `Command` for a mirrored alias: clone the target leaf
+/// and rename it to the alias. The clone carries the leaf's flags, positional
+/// completers, value parsers, and help verbatim — `Command`/`Arg`/`Extensions`
+/// and `ArgValueCompleter` are all `Clone` in clap 4.6, and the completer is
+/// `Arc`-backed so the live git query survives. clap_complete's engine descends
+/// by subcommand name only, so a renamed clone is completed like the original.
+fn mirror_alias_command(leaf: Command, alias_name: &str, rep: &CommandConfig) -> Command {
+ let first_template = rep
+ .commands()
+ .next()
+ .map(|c| c.template.as_str())
+ .unwrap_or("");
+ let help = truncate_template(first_template);
+ let name: &'static str = Box::leak(alias_name.to_string().into_boxed_str());
+ let about: &'static str = Box::leak(format!("alias: {help}").into_boxed_str());
+ leaf.name(name).about(about)
+}
+
/// Build a completion stub `clap::Command` for an alias. Leaks strings since
/// completion is a short-lived subprocess that exits after printing candidates.
fn build_alias_completion_command(name: &str, cmd_config: &CommandConfig) -> Command {
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index 14b72538e..51e46bb6a 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -1866,6 +1866,241 @@ deploy = "make deploy"
assert!(stdout.contains("--var"), "Missing --var flag: {stdout}");
}
+// --- Alias argument-completion mirroring -------------------------------------
+//
+// An alias that forwards `{{ args }}` to a `wt` leaf built-in (`co = "wt switch
+// {{ args }}"`) mirrors that built-in's completion instead of the generic stub.
+// Detection: exactly one `{{ args }}`-forwarding command, leading `wt`, then a
+// tree-walk that lands on a leaf. See `mirror_builtin_leaf` in src/completion.rs.
+
+/// `wt co <Tab>` mirrors `wt switch <Tab>`: the positional completes branches,
+/// switch's flags are offered after `--`, and a bare positional tab does not
+/// spam flags (`hide_non_positional_options_for_completion` ordering).
+#[rstest]
+fn test_complete_alias_mirrors_wrapped_switch(repo: TestRepo) {
+ repo.commit("initial");
+ repo.write_project_config(
+ r#"
+[aliases]
+co = "wt switch {{ args }}"
+"#,
+ );
+ repo.commit("add config");
+ repo.run_git(&["branch", "feature/new"]);
+
+ // Bare positional → branch candidates (mirrored completer), no flag spam.
+ let output = repo.completion_cmd(&["wt", "co", ""]).output().unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("feature/new"),
+ "mirrored switch should complete branches: {stdout}"
+ );
+ assert!(
+ !stdout.contains("--create"),
+ "bare tab must not list switch's flags: {stdout}"
+ );
+
+ // Flag prefix → switch's flags.
+ let output = repo.completion_cmd(&["wt", "co", "--"]).output().unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("--create"),
+ "mirrored switch should offer --create: {stdout}"
+ );
+}
+
+/// A baked-in flag in the template (`mk = "wt switch --create {{ args }}"`)
+/// stops the tree-walk at `switch` but still mirrors it.
+#[rstest]
+fn test_complete_alias_mirrors_switch_with_baked_flag(repo: TestRepo) {
+ repo.commit("initial");
+ repo.write_project_config(
+ r#"
+[aliases]
+mk = "wt switch --create {{ args }}"
+"#,
+ );
+ repo.commit("add config");
+
+ let output = repo.completion_cmd(&["wt", "mk", "--"]).output().unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("--create"),
+ "mk should offer --create: {stdout}"
+ );
+ assert!(
+ stdout.contains("--base"),
+ "mk should offer --base: {stdout}"
+ );
+}
+
+/// A nested leaf (`cm = "wt step commit {{ args }}"`) mirrors `step commit`:
+/// its flags appear (not the generic stub's), and `--branch`'s value completes
+/// via commit's worktree-only completer.
+#[rstest]
+fn test_complete_alias_mirrors_nested_step_command(mut repo: TestRepo) {
+ repo.commit("initial");
+ repo.write_project_config(
+ r#"
+[aliases]
+cm = "wt step commit {{ args }}"
+"#,
+ );
+ repo.commit("add config");
+ // `wt step commit`'s `--branch` uses `worktree_only_completer`, so create a
+ // worktree (which also creates its branch).
+ repo.add_worktree("feature/new");
+
+ // Flag prefix → step-commit's own flags (not the generic stub's --var).
+ let output = repo.completion_cmd(&["wt", "cm", "--"]).output().unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("--stage"),
+ "mirrored step-commit should offer --stage: {stdout}"
+ );
+ assert!(
+ stdout.contains("--show-prompt"),
+ "mirrored step-commit should offer --show-prompt: {stdout}"
+ );
+ assert!(
+ !stdout.contains("--var"),
+ "mirrored step-commit must not expose the generic stub's --var: {stdout}"
+ );
+
+ // `--branch <value>` completes via commit's worktree_only_completer.
+ let output = repo
+ .completion_cmd(&["wt", "cm", "--branch", ""])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("feature/new"),
+ "mirrored step-commit --branch should complete worktree branches: {stdout}"
+ );
+}
+
+/// An alias that does not wrap a `wt` built-in falls back to the generic stub:
+/// no branch completion.
+#[rstest]
+fn test_complete_alias_falls_back_when_not_wrapping_builtin(repo: TestRepo) {
+ repo.commit("initial");
+ repo.write_project_config(
+ r#"
+[aliases]
+greet = "echo hi {{ branch }}"
+"#,
+ );
+ repo.commit("add config");
+ repo.run_git(&["branch", "feature/new"]);
+
+ let output = repo.completion_cmd(&["wt", "greet", ""]).output().unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ !stdout.contains("feature/new"),
+ "non-wrapping alias must not complete branches: {stdout}"
+ );
+}
+
+/// A bare dispatcher (`s = "wt step {{ args }}"`) lands on a non-leaf and falls
+/// back to the generic stub — it must NOT offer `step`'s subcommands.
+#[rstest]
+fn test_complete_alias_bare_dispatcher_falls_back(repo: TestRepo) {
+ repo.commit("initial");
+ repo.write_project_config(
+ r#"
+[aliases]
+s = "wt step {{ args }}"
+"#,
+ );
+ repo.commit("add config");
+
+ let output = repo.completion_cmd(&["wt", "s", ""]).output().unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ !stdout.contains("commit"),
+ "bare wt step wrapper must not mirror step's subcommands: {stdout}"
+ );
+ assert!(
+ !stdout.contains("diff"),
+ "bare wt step wrapper must not mirror step's subcommands: {stdout}"
+ );
+}
+
+/// Multiple commands forwarding `{{ args }}` is ambiguous → generic stub.
+#[rstest]
+fn test_complete_alias_multiple_forwarders_fall_back(repo: TestRepo) {
+ repo.commit("initial");
+ repo.write_project_config(
+ r#"
+[aliases]
+both = ["wt switch {{ args }}", "echo {{ args }}"]
+"#,
+ );
+ repo.commit("add config");
+ repo.run_git(&["branch", "feature/new"]);
+
+ let output = repo.completion_cmd(&["wt", "both", ""]).output().unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ !stdout.contains("feature/new"),
+ "ambiguous multi-forwarder alias must not mirror: {stdout}"
+ );
+}
+
+/// An alias whose command doesn't reference `{{ args }}` doesn't forward CLI
+/// positionals → generic stub.
+#[rstest]
+fn test_complete_alias_no_args_forwarding_falls_back(repo: TestRepo) {
+ repo.commit("initial");
+ repo.write_project_config(
+ r#"
+[aliases]
+co = "wt switch --create main"
+"#,
+ );
+ repo.commit("add config");
+ repo.run_git(&["branch", "feature/new"]);
+
+ let output = repo.completion_cmd(&["wt", "co", ""]).output().unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ !stdout.contains("feature/new"),
+ "alias that doesn't forward {{ args }} must not mirror: {stdout}"
+ );
+}
+
+/// The single forwarder need not be the first command — a pipeline that runs a
+/// prep step then `wt switch {{ args }}` still mirrors switch.
+#[rstest]
+fn test_complete_alias_mirrors_when_forwarder_not_first(repo: TestRepo) {
+ repo.commit("initial");
+ repo.write_project_config(
+ r#"
+[aliases]
+pre = ["npm install", "wt switch {{ args }}"]
+"#,
+ );
+ repo.commit("add config");
+ repo.run_git(&["branch", "feature/new"]);
+
+ let output = repo.completion_cmd(&["wt", "pre", ""]).output().unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("feature/new"),
+ "forwarder-not-first alias should still mirror switch: {stdout}"
+ );
+}
+
/// Prepend a directory to PATH on a Command.
fn prepend_path(cmd: &mut std::process::Command, dir: &std::path::Path) {
let (path_var, current) = std::env::vars_os()