Skip to content

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

Forward shell completions to external subcommands (wt-*) (#2074)

Pablo Specialede9bc631d653
diff --git a/src/completion.rs b/src/completion.rs
index 685c574b7..73c3fd6c0 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -46,6 +46,28 @@ pub(crate) fn maybe_handle_env_completion() -> bool {
return true;
}
+ // If the subcommand word matches an external 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 external binary if no built-in subcommand has this name.
+ // Built-ins always take precedence 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()
+ {
+ // Forward args[1..] to the external binary
+ if let Some(forwarded) =
+ forward_completion_to_external(&binary, &args[1..], &shell_name)
+ {
+ let _ = std::io::stdout().write_all(forwarded.as_bytes());
+ CONTEXT.with(|ctx| ctx.borrow_mut().take());
+ return true;
+ }
+ }
+ }
+
// Generate completions with filtering
let mut cmd = completion_command();
cmd.build();
@@ -374,6 +396,7 @@ thread_local! {
fn completion_command() -> Command {
let cmd = cli::build_command();
let cmd = inject_alias_subcommands(cmd);
+ let cmd = inject_external_subcommands(cmd);
hide_non_positional_options_for_completion(cmd)
}
@@ -463,6 +486,140 @@ fn truncate_template(template: &str) -> &str {
}
}
+/// Forward a completion request to an external `wt-*` binary.
+///
+/// Rebuilds the args as if the user invoked `wt-sync <rest>` directly, passing
+/// the `COMPLETE` env var so the external binary generates completions.
+fn forward_completion_to_external(
+ binary: &str,
+ args: &[OsString],
+ shell: &OsStr,
+) -> Option<String> {
+ // Build args for the external binary: [binary_name, rest_args...]
+ let mut ext_args: Vec<OsString> = vec![OsString::from(binary)];
+ ext_args.extend_from_slice(&args[1..]);
+
+ // Adjust the completion index: subtract 1 since we removed the subcommand name
+ let index = std::env::var("_CLAP_COMPLETE_INDEX")
+ .ok()
+ .and_then(|i| i.parse::<usize>().ok())
+ .map(|i| i.saturating_sub(1));
+
+ let mut cmd = std::process::Command::new(binary);
+ cmd.arg("--");
+ cmd.args(&ext_args);
+ cmd.env("COMPLETE", shell);
+ cmd.env(
+ "_CLAP_IFS",
+ std::env::var("_CLAP_IFS").unwrap_or_else(|_| "\n".to_string()),
+ );
+ if let Some(idx) = index {
+ cmd.env("_CLAP_COMPLETE_INDEX", idx.to_string());
+ }
+
+ // Capture stdout from the external binary. Using std::process::Command
+ // directly (not shell_exec::Cmd) because this runs during completion —
+ // a short-lived subprocess where logging/tracing is unwanted.
+ let result = cmd
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .ok()?
+ .wait_with_output()
+ .ok()?;
+ if result.status.success() {
+ String::from_utf8(result.stdout).ok()
+ } else {
+ None
+ }
+}
+
+/// Discover `wt-*` executables on PATH and inject them as subcommands for completion.
+///
+/// This mirrors git's approach: `wt sync` dispatches to `wt-sync`, and completions
+/// should show `sync` as a subcommand. External subcommands that shadow built-in
+/// commands are skipped (built-ins always take precedence at runtime).
+fn inject_external_subcommands(cmd: Command) -> Command {
+ inject_external_subcommand_list(cmd, discover_external_subcommands())
+}
+
+/// Add discovered external subcommands to the completion command tree.
+///
+/// Each external gets a stub `Command` with `allow_external_subcommands(true)` so
+/// any trailing args are accepted without error. Built-in subcommands are never shadowed.
+fn inject_external_subcommand_list(mut cmd: Command, externals: Vec<String>) -> Command {
+ for name in externals {
+ if cmd.find_subcommand(&name).is_some() {
+ continue;
+ }
+ // Leak is fine: completion is a short-lived subprocess that exits after
+ // printing candidates (same pattern as inject_alias_subcommands).
+ let name: &'static str = Box::leak(name.into_boxed_str());
+ let about: &'static str = Box::leak(format!("external: wt-{name}").into_boxed_str());
+ let sub = Command::new(name)
+ .about(about)
+ .allow_external_subcommands(true);
+ cmd = cmd.subcommand(sub);
+ }
+ cmd
+}
+
+/// Find `wt-*` executables on PATH, returning their subcommand names (without the `wt-` prefix).
+fn discover_external_subcommands() -> Vec<String> {
+ let Some(path_var) = std::env::var_os("PATH") else {
+ return Vec::new();
+ };
+ discover_external_subcommands_in(&path_var)
+}
+
+/// Find `wt-*` executables in the given PATH value, returning subcommand names
+/// (without the `wt-` prefix). On Windows, executable extensions (.exe, .cmd, etc.)
+/// are stripped so that `wt-sync.exe` produces the subcommand name `sync`.
+fn discover_external_subcommands_in(path_var: &OsStr) -> Vec<String> {
+ let mut seen = std::collections::HashSet::new();
+ let mut result = Vec::new();
+
+ for dir in std::env::split_paths(path_var) {
+ let Ok(entries) = std::fs::read_dir(&dir) else {
+ continue;
+ };
+ for entry in entries.flatten() {
+ let file_name = entry.file_name();
+ let Some(name) = file_name.to_str() else {
+ continue;
+ };
+ let Some(subcommand) = name.strip_prefix("wt-") else {
+ continue;
+ };
+ // Strip executable extensions on Windows (.exe, .cmd, etc.)
+ #[cfg(windows)]
+ let subcommand = std::path::Path::new(subcommand)
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or(subcommand);
+
+ if subcommand.is_empty() || !seen.insert(subcommand.to_string()) {
+ continue;
+ }
+
+ // Verify it's executable (on Unix)
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ if let Ok(meta) = entry.metadata()
+ && meta.permissions().mode() & 0o111 == 0
+ {
+ continue;
+ }
+ }
+ result.push(subcommand.to_string());
+ }
+ }
+
+ result.sort();
+ result
+}
+
/// Hide non-positional options so they're filtered out when positional/subcommand
/// completions exist, but still shown when completing `--<TAB>`.
///
@@ -540,4 +697,197 @@ mod tests {
assert_eq!(result.len(), 56);
assert_eq!(result, "a".repeat(56));
}
+
+ #[test]
+ fn test_discover_empty_path() {
+ let result = discover_external_subcommands_in(OsStr::new(""));
+ assert!(result.is_empty());
+ }
+
+ #[test]
+ fn test_discover_nonexistent_dir() {
+ let result =
+ discover_external_subcommands_in(OsStr::new("/nonexistent/path/xxxxxxxx_wt_test"));
+ assert!(result.is_empty());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn test_discover_finds_wt_executables() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir().unwrap();
+
+ for name in ["wt-alpha", "wt-beta"] {
+ let path = dir.path().join(name);
+ std::fs::write(&path, "#!/bin/sh\n").unwrap();
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+
+ let result = discover_external_subcommands_in(dir.path().as_os_str());
+ assert_eq!(result, vec!["alpha", "beta"]);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn test_discover_skips_non_executable() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir().unwrap();
+
+ let exec = dir.path().join("wt-exec");
+ std::fs::write(&exec, "#!/bin/sh\n").unwrap();
+ std::fs::set_permissions(&exec, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ let noexec = dir.path().join("wt-noexec");
+ std::fs::write(&noexec, "data").unwrap();
+ std::fs::set_permissions(&noexec, std::fs::Permissions::from_mode(0o644)).unwrap();
+
+ let result = discover_external_subcommands_in(dir.path().as_os_str());
+ assert_eq!(result, vec!["exec"]);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn test_discover_deduplicates_across_dirs() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir1 = tempfile::tempdir().unwrap();
+ let dir2 = tempfile::tempdir().unwrap();
+
+ for dir in [dir1.path(), dir2.path()] {
+ let path = dir.join("wt-dup");
+ std::fs::write(&path, "#!/bin/sh\n").unwrap();
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+
+ let path = std::env::join_paths([dir1.path(), dir2.path()]).unwrap();
+ let result = discover_external_subcommands_in(&path);
+ assert_eq!(result, vec!["dup"]);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn test_discover_skips_bare_prefix_and_non_matching() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir().unwrap();
+
+ // "wt-" with no suffix should be skipped
+ let empty = dir.path().join("wt-");
+ std::fs::write(&empty, "#!/bin/sh\n").unwrap();
+ std::fs::set_permissions(&empty, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ // Non-matching name should be skipped
+ let other = dir.path().join("other-tool");
+ std::fs::write(&other, "#!/bin/sh\n").unwrap();
+ std::fs::set_permissions(&other, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ let result = discover_external_subcommands_in(dir.path().as_os_str());
+ assert!(result.is_empty());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn test_discover_results_are_sorted() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir().unwrap();
+
+ // Create in reverse alphabetical order
+ for name in ["wt-zebra", "wt-apple", "wt-mango"] {
+ let path = dir.path().join(name);
+ std::fs::write(&path, "#!/bin/sh\n").unwrap();
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+
+ let result = discover_external_subcommands_in(dir.path().as_os_str());
+ assert_eq!(result, vec!["apple", "mango", "zebra"]);
+ }
+
+ #[test]
+ fn test_inject_external_adds_subcommands() {
+ let cmd = Command::new("wt")
+ .subcommand(Command::new("switch"))
+ .subcommand(Command::new("list"));
+
+ let cmd = inject_external_subcommand_list(cmd, vec!["sync".into(), "deploy".into()]);
+
+ assert!(cmd.find_subcommand("sync").is_some());
+ assert!(cmd.find_subcommand("deploy").is_some());
+ assert!(cmd.find_subcommand("switch").is_some());
+ assert!(cmd.find_subcommand("list").is_some());
+ }
+
+ #[test]
+ fn test_inject_external_skips_builtins() {
+ let cmd = Command::new("wt").subcommand(Command::new("switch").about("built-in switch"));
+
+ let cmd = inject_external_subcommand_list(cmd, vec!["switch".into(), "sync".into()]);
+
+ // "switch" should still be the built-in, not the external
+ let switch = cmd.find_subcommand("switch").unwrap();
+ assert_eq!(switch.get_about().unwrap().to_string(), "built-in switch");
+ // "sync" should be added as external
+ let sync = cmd.find_subcommand("sync").unwrap();
+ assert!(sync.get_about().unwrap().to_string().contains("external"));
+ }
+
+ #[test]
+ fn test_inject_external_empty_list() {
+ let cmd = Command::new("wt").subcommand(Command::new("switch"));
+ let cmd = inject_external_subcommand_list(cmd, vec![]);
+ assert_eq!(cmd.get_subcommands().count(), 1);
+ }
+
+ #[test]
+ fn test_inject_external_allows_trailing_args() {
+ let cmd = Command::new("wt");
+ let cmd = inject_external_subcommand_list(cmd, vec!["sync".into()]);
+
+ let sync = cmd.find_subcommand("sync").unwrap();
+ assert!(sync.is_allow_external_subcommands_set());
+ }
+
+ #[test]
+ fn test_forward_to_nonexistent_binary() {
+ let result = forward_completion_to_external(
+ "/nonexistent/binary/xxxxxxxx_wt_test",
+ &[OsString::from("test")],
+ OsStr::new("bash"),
+ );
+ assert!(result.is_none());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn test_forward_to_external_binary() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir().unwrap();
+ let script = dir.path().join("wt-fake");
+ std::fs::write(&script, "#!/bin/sh\nprintf '%s\\n%s' '--all' '--verbose'\n").unwrap();
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ let result = forward_completion_to_external(
+ script.to_str().unwrap(),
+ &[OsString::from("fake"), OsString::from("--")],
+ OsStr::new("bash"),
+ );
+ assert!(result.is_some());
+ let output = result.unwrap();
+ assert!(output.contains("--all"));
+ assert!(output.contains("--verbose"));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn test_forward_to_failing_binary() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir().unwrap();
+ let script = dir.path().join("wt-fail");
+ std::fs::write(&script, "#!/bin/sh\nexit 1\n").unwrap();
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ let result = forward_completion_to_external(
+ script.to_str().unwrap(),
+ &[OsString::from("fail")],
+ OsStr::new("bash"),
+ );
+ assert!(result.is_none());
+ }
}
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index 528f23dc1..238f6f9ce 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -1,4 +1,8 @@
-use crate::common::{TestRepo, repo, wt_command, wt_completion_command};
+use crate::common::{
+ TestRepo,
+ mock_commands::{MockConfig, MockResponse},
+ repo, wt_command, wt_completion_command,
+};
use insta::Settings;
use rstest::rstest;
@@ -1686,3 +1690,80 @@ deploy = "make deploy"
assert!(stdout.contains("--yes"), "Missing --yes flag: {stdout}");
assert!(stdout.contains("--var"), "Missing --var flag: {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()
+ .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
+ .map(|(k, v)| (k.to_string_lossy().into_owned(), Some(v)))
+ .unwrap_or(("PATH".to_string(), None));
+
+ let mut paths: Vec<std::path::PathBuf> = current
+ .as_deref()
+ .map(|p| std::env::split_paths(p).collect())
+ .unwrap_or_default();
+ paths.insert(0, dir.to_path_buf());
+ let new_path = std::env::join_paths(&paths).unwrap();
+ cmd.env(path_var, new_path);
+}
+
+/// External `wt-*` binaries on PATH appear as subcommand completion candidates.
+#[rstest]
+fn test_complete_external_subcommand_listed(repo: TestRepo) {
+ repo.commit("initial");
+
+ // Create a mock wt-testext binary on PATH
+ let ext_dir = tempfile::tempdir().unwrap();
+ MockConfig::new("wt-testext")
+ .command("_default", MockResponse::output("external ran\n"))
+ .write(ext_dir.path());
+
+ // Complete "wt " — should include "testext" from the external binary
+ let mut cmd = repo.completion_cmd(&["wt", ""]);
+ prepend_path(&mut cmd, ext_dir.path());
+ cmd.env("MOCK_CONFIG_DIR", ext_dir.path());
+ let output = cmd.output().unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ assert!(
+ stdout.contains("testext"),
+ "External subcommand 'testext' missing from completion output: {stdout}"
+ );
+ // Built-in subcommands should still be present
+ assert!(
+ stdout.contains("switch"),
+ "Built-in 'switch' missing from completion output: {stdout}"
+ );
+}
+
+/// Completion for an external subcommand's flags forwards to the external binary.
+#[cfg(unix)]
+#[rstest]
+fn test_complete_external_subcommand_forwards(repo: TestRepo) {
+ use std::os::unix::fs::PermissionsExt;
+ repo.commit("initial");
+
+ // Create a real shell script that outputs completions (not mock-stub,
+ // which needs MOCK_CONFIG_DIR and doesn't know about COMPLETE env var).
+ let ext_dir = tempfile::tempdir().unwrap();
+ let script = ext_dir.path().join("wt-testext");
+ std::fs::write(
+ &script,
+ "#!/bin/sh\nprintf '%s\\n%s' '--custom-flag' '--another'\n",
+ )
+ .unwrap();
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ // Complete "wt testext --" — should forward to wt-testext and show its output
+ let mut cmd = repo.completion_cmd(&["wt", "testext", "--"]);
+ prepend_path(&mut cmd, ext_dir.path());
+ let output = cmd.output().unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ assert!(
+ stdout.contains("--custom-flag"),
+ "Forwarded completion output missing '--custom-flag': {stdout}"
+ );
+}
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index a932338ca..9b5de4472 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -2960,6 +2960,22 @@ fi
);
}
+ /// Build a hermetic PATH for completion tests.
+ ///
+ /// Creates a temp dir with a symlink to the `wt` binary, then builds PATH
+ /// from that dir + system dirs (excluding cargo target directories). This
+ /// prevents co-built binaries like `wt-perf` from leaking into completion
+ /// output as external subcommands.
+ fn completion_test_path(wt_bin: &std::path::Path) -> (tempfile::TempDir, String) {
+ let dir = tempfile::tempdir().unwrap();
+ std::os::unix::fs::symlink(wt_bin, dir.path().join("wt")).unwrap();
+ // Only include the symlink dir + essential system dirs. This prevents
+ // any user-installed `wt-*` binaries (e.g. ~/.cargo/bin/wt-sync) or
+ // co-compiled helpers (target/debug/wt-perf) from appearing.
+ let path = format!("{}:/usr/bin:/bin:/usr/sbin:/sbin", dir.path().display());
+ (dir, path)
+ }
+
/// Black-box test: zsh completion produces correct subcommands.
///
/// Sources actual `wt config shell init zsh`, triggers completion, snapshots result.
@@ -2986,17 +3002,14 @@ _wt_lazy_complete
"#
);
+ // Filter PATH to exclude cargo target directories so `wt-perf` (test
+ // helper) doesn't leak into completion output as an external subcommand.
+ let (_dir, clean_path) = completion_test_path(&wt_bin);
+
let output = std::process::Command::new("zsh")
.arg("-c")
.arg(&script)
- .env(
- "PATH",
- format!(
- "{}:{}",
- wt_bin.parent().unwrap().display(),
- std::env::var("PATH").unwrap_or_default()
- ),
- )
+ .env("PATH", &clean_path)
.output()
.unwrap();
@@ -3024,17 +3037,12 @@ for c in "${{COMPREPLY[@]}}"; do echo "${{c%% *}}"; done
"#
);
+ let (_dir, clean_path) = completion_test_path(&wt_bin);
+
let output = std::process::Command::new("bash")
.arg("-c")
.arg(&script)
- .env(
- "PATH",
- format!(
- "{}:{}",
- wt_bin.parent().unwrap().display(),
- std::env::var("PATH").unwrap_or_default()
- ),
- )
+ .env("PATH", &clean_path)
.output()
.unwrap();
@@ -3047,11 +3055,13 @@ for c in "${{COMPREPLY[@]}}"; do echo "${{c%% *}}"; done
#[test]
fn test_fish_completion_subcommands() {
let wt_bin = wt_bin();
+ let (_dir, clean_path) = completion_test_path(&wt_bin);
let output = std::process::Command::new(&wt_bin)
.args(["--", "wt", ""])
.env("COMPLETE", "fish")
.env("_CLAP_COMPLETE_INDEX", "1")
+ .env("PATH", &clean_path)
.output()
.unwrap();
@@ -3071,10 +3081,12 @@ for c in "${{COMPREPLY[@]}}"; do echo "${{c%% *}}"; done
#[test]
fn test_nushell_completion_subcommands() {
let wt_bin = wt_bin();
+ let (_dir, clean_path) = completion_test_path(&wt_bin);
let output = std::process::Command::new(&wt_bin)
.args(["--", "wt", ""])
.env("COMPLETE", "nu")
+ .env("PATH", &clean_path)
.output()
.unwrap();
@@ -3088,6 +3100,106 @@ for c in "${{COMPREPLY[@]}}"; do echo "${{c%% *}}"; done
assert_snapshot!(completions);
}
+ /// Shell integration test: completing an external subcommand's flags
+ /// forwards the request to the `wt-*` binary on PATH.
+ ///
+ /// Places a `wt-fake` script in the hermetic PATH, then triggers
+ /// `wt fake --<tab>` via the fish completion protocol. Verifies that:
+ /// 1. The external script's output appears (forwarding works)
+ /// 2. `_CLAP_COMPLETE_INDEX` is decremented by 1 (index adjustment)
+ #[test]
+ fn test_fish_completion_forwards_to_external() {
+ use std::os::unix::fs::PermissionsExt;
+ let wt_bin = wt_bin();
+ let (dir, clean_path) = completion_test_path(&wt_bin);
+
+ // Place a wt-fake script that outputs distinctive completions and
+ // echoes the received _CLAP_COMPLETE_INDEX so we can verify adjustment.
+ let script = dir.path().join("wt-fake");
+ std::fs::write(
+ &script,
+ "#!/bin/sh\nprintf '%s\\n%s\\n' '--fake-flag' \"idx:${_CLAP_COMPLETE_INDEX}\"\n",
+ )
+ .unwrap();
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ // Fish protocol: `wt -- wt fake --` with COMPLETE=fish.
+ // _CLAP_COMPLETE_INDEX=2 (completing the 3rd word "—" in "wt fake --").
+ // The forwarding code should detect "fake" is external, forward to
+ // wt-fake, and decrement the index to 1.
+ let output = std::process::Command::new(&wt_bin)
+ .args(["--", "wt", "fake", "--"])
+ .env("COMPLETE", "fish")
+ .env("_CLAP_COMPLETE_INDEX", "2")
+ .env("PATH", &clean_path)
+ .output()
+ .unwrap();
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("--fake-flag"),
+ "Forwarded completions should include external script output: {stdout}"
+ );
+ assert!(
+ stdout.contains("idx:1"),
+ "_CLAP_COMPLETE_INDEX should be adjusted from 2 to 1: {stdout}"
+ );
+ }
+
+ /// Shell integration test: bash completion forwards to external subcommands.
+ ///
+ /// Sources the real `wt config shell init bash` output, places a `wt-fake`
+ /// script on the hermetic PATH, and triggers `wt fake --<tab>` through
+ /// bash's completion machinery.
+ #[test]
+ fn test_bash_completion_forwards_to_external() {
+ use std::os::unix::fs::PermissionsExt;
+ let wt_bin = wt_bin();
+ let (dir, clean_path) = completion_test_path(&wt_bin);
+
+ // Place a wt-fake script that outputs completions
+ let ext_script = dir.path().join("wt-fake");
+ std::fs::write(
+ &ext_script,
+ "#!/bin/sh\nprintf '%s\\n%s\\n' '--fake-opt' '--fake-verbose'\n",
+ )
+ .unwrap();
+ std::fs::set_permissions(&ext_script, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ let init = std::process::Command::new(&wt_bin)
+ .args(["config", "shell", "init", "bash"])
+ .output()
+ .unwrap();
+ let shell_integration = String::from_utf8_lossy(&init.stdout);
+
+ // Trigger completion for "wt fake --" through bash's completion system.
+ let script = format!(
+ r#"
+{shell_integration}
+COMP_WORDS=(wt fake --) COMP_CWORD=2
+_wt_lazy_complete
+for c in "${{COMPREPLY[@]}}"; do echo "${{c%% *}}"; done
+"#
+ );
+
+ let output = std::process::Command::new("bash")
+ .arg("-c")
+ .arg(&script)
+ .env("PATH", &clean_path)
+ .output()
+ .unwrap();
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("--fake-opt"),
+ "Bash completion should forward to wt-fake and show its output: {stdout}"
+ );
+ assert!(
+ stdout.contains("--fake-verbose"),
+ "Bash completion should include all external completions: {stdout}"
+ );
+ }
+
// ========================================================================
// Stderr/Stdout Redirection Tests
// ========================================================================