Skip to content

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

Honor alias precedence over PATH executables during completion (#4548)

Maximilian Roos7b6108774310
diff --git a/src/completion.rs b/src/completion.rs
index 3d167abdf..8dab93ab6 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -94,10 +94,9 @@ pub(crate) fn maybe_handle_env_completion() -> bool {
// A bare `Command` is all the registration needs: clap_complete 4.6.9's
// `write_registration` reads `cmd.get_name()` and `self.bin` (set below,
// so its `cmd.get_bin_name()` fallback never fires), and nothing else off
- // the command. Handing it `completion_command()` instead would build the
- // whole completion tree — `Repository::current()`, both config loads, and
- // a scan of every `PATH` directory for `wt-*` — to produce one string, on
- // the first TAB of every new shell.
+ // the command. Building the completion tree instead would load the
+ // repository and both configs and scan every PATH directory for
+ // `wt-*` to produce one string, on the first TAB of every new shell.
let name = registration_name();
let all_args: Vec<OsString> = std::env::args_os().collect();
let _ = CompleteEnv::with_factory(move || Command::new(name))
@@ -112,7 +111,7 @@ pub(crate) fn maybe_handle_env_completion() -> bool {
// Completion answers and returns long before `main` reaches its own
// `Repository::prewarm` call, so without this every one of those reads is
// a separate fork taken serially, on the one path where the user is
- // waiting with a finger on Tab: `completion_command`'s alias injection
+ // waiting with a finger on Tab: the completion tree's alias injection
// needs the configs, and the branch completers below need the discovery
// caches. Placed after the registration-script return, which resolves no
// repository at all, and after `suppress_warnings` above, since
@@ -120,18 +119,19 @@ pub(crate) fn maybe_handle_env_completion() -> bool {
// warnings must not land above the user's prompt.
Repository::prewarm();
+ // Resolve built-ins and aliases once, before considering PATH binaries.
+ // This tree owns the same precedence as runtime dispatch.
+ let cmd = inject_alias_subcommands(cli::build_command());
+
// If the subcommand word matches a custom-subcommand binary, forward the
// completion request to it (e.g., `wt sync --<tab>` → `wt-sync --<tab>`).
// args[0] is the binary name ("wt"), args[1] is the subcommand ("sync").
if args.len() >= 3 {
let subcommand = args[1].to_string_lossy();
- // Only forward to the custom binary if no built-in subcommand has this
- // name. Built-ins always take precedence at runtime, so completions
- // must agree.
+ // Built-ins and configured aliases both take precedence over PATH
+ // binaries at runtime, so completions must agree.
let binary = format!("wt-{subcommand}");
- if cli::build_command().find_subcommand(&*subcommand).is_none()
- && which::which(&binary).is_ok()
- {
+ if cmd.find_subcommand(&*subcommand).is_none() && which::which(&binary).is_ok() {
// Forward args[1..] to the custom binary
if let Some(forwarded) = forward_completion_to_custom(&binary, &args[1..], &shell_name)
{
@@ -143,7 +143,9 @@ pub(crate) fn maybe_handle_env_completion() -> bool {
}
// Generate completions with filtering
- let mut cmd = completion_command();
+ let cmd = inject_hook_subcommands(cmd);
+ let cmd = inject_custom_subcommands(cmd);
+ let mut cmd = hide_non_positional_options_for_completion(cmd);
cmd.build();
// Determine the index of the word being completed.
@@ -180,8 +182,7 @@ pub(crate) fn maybe_handle_env_completion() -> bool {
if let Some(word) = args_with_double_dash.get_mut(index) {
*word = OsString::from("--");
}
- let mut cmd2 = completion_command();
- cmd2.build();
+ let mut cmd2 = cmd.clone();
if let Ok(long_completions) = clap_complete::engine::complete(
&mut cmd2,
args_with_double_dash,
@@ -542,14 +543,6 @@ fn registration_name() -> &'static str {
Box::leak(name.into_boxed_str())
}
-fn completion_command() -> Command {
- let cmd = cli::build_command();
- let cmd = inject_alias_subcommands(cmd);
- let cmd = inject_hook_subcommands(cmd);
- let cmd = inject_custom_subcommands(cmd);
- hide_non_positional_options_for_completion(cmd)
-}
-
/// Inject hook type names as subcommands of `hook` so both completion and
/// `wt hook --help` list them. Clap doesn't dispatch these at runtime — the
/// real parser uses the `external_subcommand` `Run(Vec<OsString>)` variant —
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index 20670ed5e..d63795727 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -2220,6 +2220,50 @@ printf '%s\n%s\n%s' '--custom-flag' '--another' "retired:${WORKTRUNK_DIRECTIVE_F
);
}
+/// Alias completions must win over an executable with the same name, just
+/// like dispatch. The losing executable must not run even on a Tab press.
+#[cfg(unix)]
+#[rstest]
+#[case(false)]
+#[case(true)]
+fn test_complete_alias_shadows_custom_binary(repo: TestRepo, #[case] project: bool) {
+ use std::os::unix::fs::PermissionsExt;
+
+ let config = r#"
+[aliases]
+co = "wt switch {{ args }}"
+"#;
+ if project {
+ repo.write_project_config(config);
+ } else {
+ repo.write_test_config(config);
+ }
+ let ext_dir = crate::common::test_tempdir();
+ let script = ext_dir.path().join("wt-co");
+ let marker = ext_dir.path().join("called");
+ std::fs::write(
+ &script,
+ r#"#!/bin/sh
+printf called > "$WORKTRUNK_TEST_COMPLETION_MARKER"
+printf -- '--external-flag\n'
+"#,
+ )
+ .unwrap();
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ let mut cmd = repo.completion_cmd(&["wt", "co", "--"]);
+ prepend_path(&mut cmd, ext_dir.path());
+ cmd.env("WORKTRUNK_TEST_COMPLETION_MARKER", &marker);
+ let output = cmd.output().unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("--create"),
+ "alias must mirror switch: {stdout}"
+ );
+ assert!(!marker.exists(), "shadowed executable must not run");
+}
+
/// Regression for #3816: `config shell init --cmd <name>` must generate a
/// completion loader whose clap-derived identifiers match the ones the binary
/// emits at TAB time.