Skip to content

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

56.0 KB
Raw Blame
//! Shell completion (`COMPLETE=$SHELL wt -- <tokens>`).
//!
//! Every Tab press forks a whole `wt` process, and the user is waiting on it
//! with a finger still on the key — so this is the one path where wall-clock
//! latency is the feature. It is also the path with the least room to hide
//! work: there is no progressive rendering to paint behind, no cache to amortize
//! across invocations (the process exits, and no shell caches a dynamic
//! completion), and nothing the shell can show until the process is done.
//!
//! Two structural rules follow, both easy to undo by accident:
//!
//! - **Everything the completion needs is fetched concurrently.** The work is a
//!   handful of independent git reads, each roughly one fork's latency, so
//!   sequencing them costs their sum where the user waits for their max. The
//!   process runs in two waves: [`Repository::prewarm`] fills the discovery,
//!   git-config, and user-config caches on three threads, and then
//!   `branches_for_completion` runs the ref and worktree scans on three more.
//!   The second wave depends on the first only through `Repository::at`, which
//!   needs the common dir the first wave resolved.
//! - **Nothing is scanned that cannot reach the user.** The completer decides
//!   up front whether a remote-only branch could be offered from this argument
//!   at all, and passes that down rather than filtering afterwards —
//!   `refs/remotes/` is the most expensive read here, since a long-lived clone
//!   carries far more remote-tracking refs than local branches.
//!
//! `main` returns here before it builds the rayon pool, which this path never
//! uses; see the call site. A change to any of this is measured against
//! `benches/completion.rs`, which runs one repo big enough in every dimension
//! to make the difference visible — and *not* against a `-vv` trace, which
//! skips prewarm's rev-parse batch (benches/AGENTS.md, "Analyzing a trace").

use std::cell::RefCell;
use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::io::Write;

use clap::Command;
use clap_complete::engine::{ArgValueCompleter, CompletionCandidate, ValueCompleter};
use clap_complete::env::CompleteEnv;

use crate::cli;
use crate::commands::{AliasMap, ParsedFilter, load_aliases};
use crate::display::format_relative_time_short;
use worktrunk::config::{
    ALIAS_ARGS_KEY, CommandConfig, HookSource, ProjectConfig, UserConfig, template_references_var,
};
use worktrunk::git::{BranchCategory, HookType, Repository};

/// Handle shell-initiated completion requests via `COMPLETE=$SHELL wt`
pub(crate) fn maybe_handle_env_completion() -> bool {
    let Some(shell_name) = std::env::var_os("COMPLETE") else {
        return false;
    };

    if shell_name.is_empty() || shell_name == "0" {
        return false;
    }

    // Tab-completion output lands above the user's prompt — any stray stderr
    // warnings would display there. Silence config deprecation/unknown-field
    // warnings for the duration of this process.
    worktrunk::config::suppress_warnings();

    let mut args: Vec<OsString> = std::env::args_os().collect();

    // Remove the binary name and find the `--` separator
    args.remove(0);
    let escape_index = args
        .iter()
        .position(|a| *a == "--")
        .map(|i| i + 1)
        .unwrap_or(args.len());
    args.drain(0..escape_index);

    let current_dir = std::env::current_dir().ok();

    // If no args after `--`, output the shell registration script
    if args.is_empty() {
        // Use CompleteEnv for registration script generation, under the name the
        // shell integration binds — not clap's own (see `registration_name`).
        //
        // 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. 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))
            .bin(name)
            .try_complete(all_args, current_dir.as_deref());
        CONTEXT.with(|ctx| ctx.borrow_mut().take());
        return true;
    }

    // Determine the index of the word being completed.
    // - Bash/Zsh: Pass `_CLAP_COMPLETE_INDEX` env var with the cursor position
    // - Fish/Nushell: Append the current token as the last argument, so index = len - 1
    let index: usize = std::env::var("_CLAP_COMPLETE_INDEX")
        .ok()
        .and_then(|i| i.parse().ok())
        .unwrap_or_else(|| args.len() - 1);

    // Only completed words can set globals: the cursor may still be editing
    // a config filename or directory. Reuse runtime parsing so attached flag
    // values and globals after built-in subcommands follow the same rules.
    let globals = crate::parse_early_globals(args.iter().take(index).cloned());
    CONTEXT.with(|ctx| {
        *ctx.borrow_mut() = Some(CompletionContext {
            args: args.clone(),
            hook_type: globals.hook_type,
        });
    });
    let current_dir = globals.directory.clone().or(current_dir);
    crate::apply_global_options(globals.directory, globals.config, globals.config_overrides);

    // Completion exits before `main`'s `logging::init`, so the normal
    // `-v`/`-vv` pipeline never runs here. `WORKTRUNK_VERBOSE` opts this
    // short-lived subprocess into the same logging as a flagged command — the
    // env-var equivalent of `-vv` — so humanized timing (`✓ git …`) and
    // `$ git …` start records for a slow completion land in `.git/wt/logs/`
    // just as `-vv` writes them. Left unset, completion stays silent so stray
    // stderr never lands above the user's prompt.
    let completion_verbose = crate::logging::env_verbose_level();
    if completion_verbose > 0 {
        crate::logging::init(completion_verbose);
    }

    // Fill the git-discovery, git-config, and user-config caches on three
    // concurrent threads, exactly as `main` does before dispatching a command.
    // 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: 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
    // `prewarm_user_config` loads `UserConfig` eagerly and its deprecation
    // 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>`).
    // The early parse includes only words before the cursor, so editing the
    // subcommand itself never invokes a binary from PATH.
    if let Some(start) = globals.external_subcommand_index {
        let subcommand = args[start].to_string_lossy();
        // The early parse excludes built-ins; configured aliases also take
        // precedence over PATH binaries. Reuse the alias-injected tree.
        let binary = format!("wt-{subcommand}");
        if cmd.find_subcommand(&*subcommand).is_none()
            && let Some(forwarded) = forward_completion_to_custom(
                &binary,
                &args[start..],
                &shell_name,
                start,
                current_dir.as_deref(),
            )
        {
            let _ = std::io::stdout().write_all(forwarded.as_bytes());
            CONTEXT.with(|ctx| ctx.borrow_mut().take());
            return true;
        }
    }

    // Generate completions with filtering
    let cmd = inject_hook_subcommands(cmd);
    let cmd = inject_custom_subcommands(cmd);
    let mut cmd = hide_non_positional_options_for_completion(cmd);
    cmd.build();

    // Check if the current word is exactly "-" (single dash)
    // If so, we want to show both short flags (-h) AND long flags (--help)
    // clap only returns matches for the prefix, so we call complete twice
    let current_word = args.get(index).map(|s| s.to_string_lossy().into_owned());
    let include_long_flags = current_word.as_deref() == Some("-");

    let completions = match clap_complete::engine::complete(
        &mut cmd,
        args.clone(),
        index,
        current_dir.as_deref(),
    ) {
        Ok(c) => c,
        Err(_) => {
            CONTEXT.with(|ctx| ctx.borrow_mut().take());
            return true;
        }
    };

    // If single dash, also get completions for "--" and merge
    let completions = if include_long_flags {
        let mut merged = completions;
        let mut args_with_double_dash = args;
        if let Some(word) = args_with_double_dash.get_mut(index) {
            *word = OsString::from("--");
        }
        let mut cmd2 = cmd.clone();
        if let Ok(long_completions) = clap_complete::engine::complete(
            &mut cmd2,
            args_with_double_dash,
            index,
            current_dir.as_deref(),
        ) {
            // Add long flags that aren't already present (avoid duplicates)
            for candidate in long_completions {
                let value = candidate.get_value();
                if !merged.iter().any(|c| c.get_value() == value) {
                    merged.push(candidate);
                }
            }
        }
        merged
    } else {
        completions
    };

    // Bash does not filter COMPREPLY by prefix — its programmable completion
    // (-F) passes the array as-is. Fish/zsh apply their own matching (substring,
    // fuzzy), so they receive all candidates. For bash, we must filter here.
    let shell_name = shell_name.to_string_lossy();
    let completions = if shell_name.as_ref() == "bash" {
        let prefix = current_word.as_deref().unwrap_or("").to_owned();
        if prefix.is_empty() {
            completions
        } else {
            completions
                .into_iter()
                .filter(|c| c.get_value().to_string_lossy().starts_with(&*prefix))
                .collect()
        }
    } else {
        completions
    };

    // Write completions in the appropriate format for the shell
    let ifs = std::env::var("_CLAP_IFS").ok();
    let separator = ifs.as_deref().unwrap_or("\n");

    // Shell-specific separator between value and description
    // zsh uses ":", fish/nushell use "\t", bash doesn't support descriptions
    let help_sep = match shell_name.as_ref() {
        "zsh" => Some(":"),
        "fish" | "nu" => Some("\t"),
        _ => None,
    };

    let mut stdout = std::io::stdout();
    for (i, candidate) in completions.iter().enumerate() {
        if i != 0 {
            let _ = write!(stdout, "{}", separator);
        }
        let value = candidate.get_value().to_string_lossy();
        match (help_sep, candidate.get_help()) {
            (Some(sep), Some(help)) => {
                let _ = write!(stdout, "{}{}{}", value, sep, help);
            }
            _ => {
                let _ = write!(stdout, "{}", value);
            }
        }
    }

    CONTEXT.with(|ctx| ctx.borrow_mut().take());
    true
}

/// Branch completion without additional context filtering (e.g., --base, merge target).
pub(crate) fn branch_value_completer() -> ArgValueCompleter {
    ArgValueCompleter::new(BranchCompleter {
        suppress_with_create: false,
        exclude_remote_only: false,
        worktree_only: false,
        qualify_remote_prefix: false,
    })
}

/// Branch completion for positional arguments (switch).
/// Suppresses completions when --create flag is present.
pub(crate) fn worktree_branch_completer() -> ArgValueCompleter {
    ArgValueCompleter::new(BranchCompleter {
        suppress_with_create: true,
        exclude_remote_only: false,
        worktree_only: false,
        qualify_remote_prefix: true,
    })
}

/// Branch completion for remove command - excludes remote-only branches.
pub(crate) fn local_branches_completer() -> ArgValueCompleter {
    ArgValueCompleter::new(BranchCompleter {
        suppress_with_create: false,
        exclude_remote_only: true,
        worktree_only: false,
        qualify_remote_prefix: false,
    })
}

/// Branch completion for commands that only operate on worktrees (e.g., copy-ignored).
pub(crate) fn worktree_only_completer() -> ArgValueCompleter {
    ArgValueCompleter::new(BranchCompleter {
        suppress_with_create: false,
        exclude_remote_only: false,
        worktree_only: true,
        qualify_remote_prefix: false,
    })
}

/// Hook command name completion for `wt hook <hook-type> <name>`.
/// Completes with effective user and project command names for the hook type being invoked.
pub(crate) fn hook_command_name_completer() -> ArgValueCompleter {
    ArgValueCompleter::new(HookCommandCompleter)
}

/// Alias name completion for `wt config alias <show|dry-run> <name>`.
///
/// Completes with the merged user + project alias name set. Returns all
/// candidates unfiltered — the outer `maybe_handle_env_completion` does
/// bash-specific prefix filtering; fish/zsh apply their own matching.
pub(crate) fn alias_name_completer() -> ArgValueCompleter {
    ArgValueCompleter::new(AliasNameCompleter)
}

#[derive(Clone, Copy)]
struct AliasNameCompleter;

impl ValueCompleter for AliasNameCompleter {
    fn complete(&self, current: &OsStr) -> Vec<CompletionCandidate> {
        if current.to_str().is_some_and(|s| s.starts_with('-')) {
            return Vec::new();
        }
        load_aliases_for_completion()
            .into_keys()
            .map(CompletionCandidate::new)
            .collect()
    }
}

#[derive(Clone, Copy)]
struct HookCommandCompleter;

impl ValueCompleter for HookCommandCompleter {
    fn complete(&self, current: &OsStr) -> Vec<CompletionCandidate> {
        // If user is typing an option (starts with -), don't suggest command names
        if current.to_str().is_some_and(|s| s.starts_with('-')) {
            return Vec::new();
        }

        // Return all candidates without prefix filtering — let the shell apply its
        // own matching (substring in fish, fuzzy in zsh, prefix in bash). The
        // bash-specific prefix filter in maybe_handle_env_completion() handles bash.

        // Get the hook type from the command line context
        let hook_type = CONTEXT.with(|ctx| ctx.borrow().as_ref().and_then(|ctx| ctx.hook_type));
        let Some(hook_type) = hook_type else {
            return Vec::new();
        };

        let mut candidates = Vec::new();

        let filter = ParsedFilter::parse(current.to_str().unwrap_or_default());
        let add_named_commands =
            |candidates: &mut Vec<_>, config: &CommandConfig, source: HookSource| {
                if !filter.matches_source(source) {
                    return;
                }
                candidates.extend(config.commands().filter_map(|cmd| {
                    let name = cmd.name.as_ref()?;
                    let name = if filter.source.is_some() {
                        source.command_label(Some(name))
                    } else {
                        name.clone()
                    };
                    Some(CompletionCandidate::new(name))
                }));
            };

        let repo = Repository::current().ok();
        let project_id = repo
            .as_ref()
            .and_then(|repo| repo.project_identifier().ok());

        // Use the same global + per-project merge as hook execution.
        if let Ok(user_config) = UserConfig::load()
            && let Some(config) = user_config.hooks(project_id.as_ref()).get(hook_type)
        {
            add_named_commands(&mut candidates, config, HookSource::User);
        }

        // Load project config and add project hook names
        // Pass write_hints=false to avoid side effects during completion
        if let Some(repo) = repo
            && let Ok(Some(project_config)) = ProjectConfig::load(&repo, false)
            && let Some(config) = project_config.hooks.get(hook_type)
        {
            add_named_commands(&mut candidates, config, HookSource::Project);
        }

        candidates
    }
}

#[derive(Clone, Copy)]
struct BranchCompleter {
    suppress_with_create: bool,
    exclude_remote_only: bool,
    worktree_only: bool,
    qualify_remote_prefix: bool,
}

impl ValueCompleter for BranchCompleter {
    fn complete(&self, current: &OsStr) -> Vec<CompletionCandidate> {
        // If user is typing an option (starts with -), don't suggest branches
        if current.to_str().is_some_and(|s| s.starts_with('-')) {
            return Vec::new();
        }

        // Return all candidates without prefix filtering — let the shell apply its
        // own matching (substring in fish, fuzzy in zsh, prefix in bash). Pre-filtering
        // here prevents shells from using their native matching strategies.

        if self.suppress_with_create && suppress_switch_branch_completion() {
            return Vec::new();
        }

        // A typed remote prefix is an explicit request for remote-tracking
        // names. Keep the qualified name so the shell can complete `origin/…`,
        // including in repositories where the general list omits remotes.
        if self.qualify_remote_prefix
            && let Some(current) = current.to_str()
            && current.contains('/')
            && let Ok(repo) = Repository::current()
            && repo.all_remote_urls().iter().any(|(name, _)| {
                current
                    .strip_prefix(name)
                    .is_some_and(|suffix| suffix.starts_with('/'))
            })
        {
            std::thread::scope(|scope| {
                scope.spawn(|| {
                    let _ = repo.local_branches();
                });
                scope.spawn(|| {
                    let _ = repo.remote_branches();
                });
            });
            let remotes = repo.remote_branches().unwrap_or_default();
            let locals = repo.local_branches().unwrap_or_default();
            let local_name_set: HashSet<_> =
                locals.iter().map(|branch| branch.name.as_str()).collect();
            let local_names: Vec<_> = locals
                .iter()
                .filter(|branch| branch.name.starts_with(current))
                .collect();
            let mut candidates: Vec<_> = local_names
                .iter()
                .map(|branch| {
                    let help = format!("/ {}", format_relative_time_short(branch.committer_ts));
                    CompletionCandidate::new(branch.name.clone()).help(Some(help.into()))
                })
                .collect();
            candidates.extend(
                remotes
                    .iter()
                    .filter(|remote| {
                        remote.short_name.starts_with(current)
                            && !local_name_set.contains(remote.short_name.as_str())
                            && !local_name_set.contains(remote.local_name.as_str())
                    })
                    .map(|remote| {
                        let help = format!("⇣ {}", format_relative_time_short(remote.committer_ts));
                        CompletionCandidate::new(remote.short_name.clone()).help(Some(help.into()))
                    }),
            );
            return candidates;
        }

        // Whether a remote-only branch could reach the user from this argument
        // at all. It decides the scan as well as the filter: a completer that
        // answers "no" never runs `for-each-ref refs/remotes/`, which on a
        // fetched-into clone is the most expensive call on this path.
        let may_offer_remote_only = !self.exclude_remote_only && !self.worktree_only;

        let branches = match Repository::current()
            .and_then(|repo| repo.branches_for_completion(may_offer_remote_only))
        {
            Ok(b) => b,
            Err(_) => return Vec::new(),
        };

        if branches.is_empty() {
            return Vec::new();
        }

        // Even where they're on offer, drop remote-only branches once the total
        // count is large. Shells like bash/zsh prompt "do you wish to see all N
        // possibilities?" which makes completion unusable in repos with many remotes.
        // Threshold of 100 aligns with bash's default `completion-query-items`.
        let exclude_remote_only = !may_offer_remote_only || branches.len() > 100;

        branches
            .into_iter()
            .filter(|branch| {
                if self.worktree_only {
                    matches!(branch.category, BranchCategory::Worktree)
                } else if exclude_remote_only {
                    !matches!(branch.category, BranchCategory::Remote(_))
                } else {
                    true
                }
            })
            .map(|branch| {
                let time_str = format_relative_time_short(branch.timestamp);
                let help = match branch.category {
                    BranchCategory::Worktree => format!("+ {}", time_str),
                    BranchCategory::Local => format!("/ {}", time_str),
                    BranchCategory::Remote(remotes) => {
                        format!("⇣ {} {}", time_str, remotes.join(", "))
                    }
                };
                CompletionCandidate::new(branch.name).help(Some(help.into()))
            })
            .collect()
    }
}

fn suppress_switch_branch_completion() -> bool {
    CONTEXT.with(|ctx| {
        ctx.borrow()
            .as_ref()
            .is_some_and(|ctx| ctx.contains("--create") || ctx.contains("-c"))
    })
}

struct CompletionContext {
    args: Vec<OsString>,
    hook_type: Option<HookType>,
}

impl CompletionContext {
    fn contains(&self, needle: &str) -> bool {
        self.args
            .iter()
            .any(|arg| arg.to_string_lossy().as_ref() == needle)
    }
}

// Thread-local context tracking is required because clap's ValueCompleter::complete()
// receives only the current argument being completed, not the full command line.
// We need access to all arguments to detect `--create` / `-c` flags and suppress
// branch completion when creating a new worktree (since the branch doesn't exist yet).
thread_local! {
    static CONTEXT: RefCell<Option<CompletionContext>> = const { RefCell::new(None) };
}

/// The command name the registration script binds completions to.
///
/// clap derives every identifier in that script — the completer function name,
/// zsh's trailing `compdef`, bash's `complete -F`, PowerShell's
/// `Register-ArgumentCompleter -CommandName` — from its own `Command` name,
/// which is the compile-time `wt`. The shell integration can be generated for a
/// different name (`wt config shell init --cmd git-wt`, or a binary installed
/// under another name), and then the generated loader guards on and calls a
/// function the registration never defines: nothing completes, and since the
/// guard never becomes true the script is regenerated on every TAB (#3816).
/// zsh's trailing `compdef` is worse than inert — it hands worktrunk's
/// completer to whatever name it carries, i.e. to the *other* `wt` that
/// `--cmd` exists to step around.
///
/// So the generated loader passes the name it bound in `WORKTRUNK_COMPLETE_NAME`
/// and the registration is emitted under that name. The fallback is
/// [`crate::binary_name`], which covers a binary installed as `git-wt` and
/// invoked directly.
///
/// Both arms are validated, because both end up embedded verbatim in generated
/// shell code and neither has necessarily been through the `--cmd` gate:
/// `binary_name` is `argv[0]`'s file stem, so a binary installed under a name
/// outside the allowlist would otherwise emit `complete -F _clap_complete_<name>`
/// with an identifier the shell can't parse — completions would silently do
/// nothing rather than fall back. `handle_completions` in `src/commands/init.rs`
/// validates `binary_name` for the same reason before writing a registration.
/// A rejected env var still defers to the binary name, which is the more useful
/// answer than the constant; only a binary name that also fails lands on `wt`.
///
/// Leaked because `Command::name` takes a `clap::builder::Str`, which borrows
/// unless clap's `string` feature is on — the same trade `build_hook_completion_command`
/// makes. One small allocation in a process that writes the script and exits.
fn registration_name() -> &'static str {
    let is_valid = |name: &String| worktrunk::shell::validate_shell_command_name(name).is_ok();
    let name = std::env::var("WORKTRUNK_COMPLETE_NAME")
        .ok()
        .filter(is_valid)
        .or_else(|| Some(crate::binary_name()).filter(is_valid))
        .unwrap_or_else(|| "wt".to_string());
    Box::leak(name.into_boxed_str())
}

/// 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 —
/// but the help renderer and completion engine both walk the `Command` tree
/// to produce their output, so injecting stubs into an augmented clone shows
/// the types without affecting argument dispatch.
///
/// Mirrors `inject_alias_subcommands` which does the equivalent for
/// top-level alias names.
pub(crate) fn inject_hook_subcommands(cmd: Command) -> Command {
    cmd.mut_subcommand("hook", |mut hook| {
        for &name in cli::HOOK_TYPE_NAMES {
            // Skip if a real subcommand already uses this name (won't happen
            // today, but keeps the injection idempotent).
            if hook.get_subcommands().any(|s| s.get_name() == name) {
                continue;
            }
            hook = hook.subcommand(build_hook_completion_command(name));
        }
        hook
    })
}

/// Build a completion stub `clap::Command` for a hook type. Declares the known
/// flags (so they show up in `wt hook pre-merge --<Tab>` completions) and wires
/// the name completer for the first positional (hook command name filter).
fn build_hook_completion_command(name: &'static str) -> Command {
    let about: &'static str = Box::leak(format!("Run {name} hooks").into_boxed_str());
    Command::new(name)
        .about(about)
        .arg(
            clap::Arg::new("dry-run")
                .long("dry-run")
                .action(clap::ArgAction::SetTrue)
                .help("Show what would run without executing"),
        )
        .arg(
            clap::Arg::new("foreground")
                .long("foreground")
                .action(clap::ArgAction::SetTrue)
                .help("Run in foreground (block until complete)"),
        )
        .arg(
            clap::Arg::new("yes")
                .short('y')
                .long("yes")
                .action(clap::ArgAction::SetTrue)
                .help("Skip approval prompts for project hooks"),
        )
        .arg(
            clap::Arg::new("var")
                .long("var")
                .value_name("KEY=VALUE")
                .num_args(1)
                .action(clap::ArgAction::Append)
                .help("Set template variable (deprecated — prefer --KEY=VALUE)"),
        )
        .arg(
            clap::Arg::new("name")
                .num_args(0..)
                .add(hook_command_name_completer())
                .help("Filter by command name(s)"),
        )
}

/// Inject configured aliases as subcommands at both the top level and under
/// `step` so they appear in completions for `wt <Tab>` and `wt step <Tab>`.
///
/// Aliases are loaded from user config and project config (same merge order as
/// `step_alias`). Aliases that shadow a built-in at a given level are skipped
/// for that level only — `commit` is shadowed under `step` but offered at the
/// top level, since `wt commit` runs the alias.
///
/// Unlike `inject_hook_subcommands`, this is intentionally *not* called from
/// `help.rs`. Hooks have a fixed clap-expressible argument schema; aliases
/// don't — `AliasOptions::parse` routes `--KEY=VALUE` based on which template
/// vars the alias references, `--dry-run` is rejected, post-alias `--yes`
/// forwards to `{{ args }}`. A clap stub is a useful approximation for
/// completion but would misrepresent alias semantics on a `--help` page. The
/// help-path counterparts are `augment_help` (text-splices the `Aliases:`
/// section into `wt --help` / `wt step --help`, preserving source markers and
/// shadowed-by-builtin annotations) and `try_intercept_alias_help` (redirects
/// `wt <alias> --help` to `wt config alias show` / `dry-run`).
fn inject_alias_subcommands(cmd: Command) -> Command {
    let aliases = load_aliases_for_completion();
    if aliases.is_empty() {
        return cmd;
    }

    let mut cmd = cmd;
    // Top-level injection: skip aliases that match a top-level built-in. The
    // help text on the stub uses the representative source's first command
    // template (user wins over project), matching how the announcement
    // banner orders the two when both are configured.
    for (name, entry) in &aliases {
        if cmd.get_subcommands().any(|s| s.get_name() == name.as_str()) {
            continue;
        }
        // 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| {
        for (name, entry) in aliases {
            if step
                .get_subcommands()
                .any(|s| s.get_name() == name.as_str())
            {
                continue;
            }
            step = step.subcommand(build_alias_completion_command(
                &name,
                entry.representative(),
            ));
        }
        step
    })
}

/// 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 AGENTS.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.
///
/// The stub declares no flags of its own. An alias's flags are its template
/// variables (`--KEY=VALUE`), which vary per alias: `AliasOptions::parse`
/// rejects `--dry-run` unless the template references `dry_run`, and forwards
/// `--var` to the alias as a plain argument.
fn build_alias_completion_command(name: &str, cmd_config: &CommandConfig) -> Command {
    // Use the first command's template for the help text
    let first_template = cmd_config
        .commands()
        .next()
        .map(|c| c.template.as_str())
        .unwrap_or("");
    let help = truncate_template(first_template);
    let name: &'static str = Box::leak(name.to_string().into_boxed_str());
    let about: &'static str = Box::leak(format!("alias: {help}").into_boxed_str());
    Command::new(name).about(about)
}

/// Load aliases from user and project config for completion. Outside a git
/// repo, only user config is read (per-project user-config overrides aren't
/// resolved without a project_id).
fn load_aliases_for_completion() -> AliasMap {
    let Ok(user_config) = UserConfig::load() else {
        return AliasMap::new();
    };
    let repo = Repository::current().ok();
    let project_config = repo
        .as_ref()
        .and_then(|r| ProjectConfig::load(r, false).ok().flatten());
    load_aliases(repo.as_ref(), &user_config, project_config.as_ref())
}

/// Truncate a template string for use as completion help text.
fn truncate_template(template: &str) -> &str {
    let s = template.trim();
    let first_line = s.lines().next().unwrap_or(s);
    if first_line.len() > 60 {
        &first_line[..first_line.floor_char_boundary(57)]
    } else {
        first_line
    }
}

/// Forward a completion request to a custom `wt-*` binary.
///
/// Rebuilds the args as if the user invoked `wt-sync <rest>` directly, passing
/// the `COMPLETE` env var so the custom binary generates completions.
fn forward_completion_to_custom(
    binary: &str,
    args: &[OsString],
    shell: &OsStr,
    removed_words: usize,
    current_dir: Option<&std::path::Path>,
) -> Option<String> {
    try_forward_completion_to_custom(binary, args, shell, removed_words, current_dir)
        .ok()
        .flatten()
}

/// Like [`forward_completion_to_custom`], but surfaces spawn/wait errors
/// instead of flattening them to `None`. Keeps production callers on the
/// `Option`-returning wrapper while letting tests distinguish spawn failures
/// (e.g., transient `ETXTBSY`) from a child that ran but produced no output.
fn try_forward_completion_to_custom(
    binary: &str,
    args: &[OsString],
    shell: &OsStr,
    removed_words: usize,
    current_dir: Option<&std::path::Path>,
) -> std::io::Result<Option<String>> {
    // Build args for the custom binary: [binary_name, rest_args...]
    let mut child_args: Vec<OsString> = vec![OsString::from(binary)];
    child_args.extend_from_slice(&args[1..]);

    // Drop wt and its global options from the child's cursor position.
    let index = std::env::var("_CLAP_COMPLETE_INDEX")
        .ok()
        .and_then(|i| i.parse::<usize>().ok())
        .map(|i| i.saturating_sub(removed_words));

    // Resolve before applying the child's cwd, as runtime custom dispatch
    // does. Relative PATH entries must not select another executable in -C.
    let path = which::which(binary).map_err(std::io::Error::other)?;
    let mut cmd = std::process::Command::new(path);
    if let Some(dir) = current_dir {
        cmd.current_dir(dir);
    }
    cmd.arg("--");
    cmd.args(&child_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());
    }
    // Don't propagate `WORKTRUNK_VERBOSE` to the forwarded binary: at level 2 a
    // worktrunk-family child would re-run `logging::init` and truncate the
    // repo-wide `.git/wt/logs/` trace files this completion just wrote — wasted
    // work at best, the parent's trace lost at worst (the child's stderr is
    // discarded below, so it can't surface anything useful anyway).
    cmd.env_remove(crate::logging::VERBOSE_ENV);
    // The retired single-file protocol is never delegated to child processes.
    cmd.env_remove(worktrunk::shell_exec::RETIRED_DIRECTIVE_FILE_ENV_VAR);

    // Capture the custom binary's stdout — it carries the forwarded completion
    // candidates. Uses `std::process::Command` rather than `shell_exec::Cmd`
    // because we only need that captured stdout, not `Cmd`'s tracing/streaming;
    // stderr is discarded so the child can't write above the user's prompt.
    cmd.stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null());
    let result = worktrunk::shell_exec::spawn(&mut cmd)?.wait_with_output()?;
    if result.status.success() {
        Ok(String::from_utf8(result.stdout).ok())
    } else {
        Ok(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. Custom subcommands that shadow built-in
/// commands are skipped (built-ins always take precedence at runtime).
fn inject_custom_subcommands(cmd: Command) -> Command {
    inject_custom_subcommand_list(cmd, discover_custom_subcommands())
}

/// Add discovered custom subcommands to the completion command tree.
///
/// Each one 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_custom_subcommand_list(mut cmd: Command, customs: Vec<String>) -> Command {
    for name in customs {
        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!("custom: 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_custom_subcommands() -> Vec<String> {
    let Some(path_var) = std::env::var_os("PATH") else {
        return Vec::new();
    };
    discover_custom_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_custom_subcommands_in(path_var: &OsStr) -> Vec<String> {
    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);

            // Use the dispatch resolver's executable rules, including symlink
            // targets and Windows extensions. A non-executable entry must not
            // hide a valid command in a later PATH directory.
            if subcommand.is_empty() || which::which(dir.join(format!("wt-{subcommand}"))).is_err()
            {
                continue;
            }
            result.push(subcommand.to_string());
        }
    }

    result.sort();
    result.dedup();
    result
}

/// Hide non-positional options so they're filtered out when positional/subcommand
/// completions exist, but still shown when completing `--<TAB>`.
///
/// This exploits clap_complete's behavior: if any non-hidden candidates exist,
/// hidden ones are dropped. When all candidates are hidden, they're kept.
fn hide_non_positional_options_for_completion(cmd: Command) -> Command {
    fn process_command(cmd: Command, is_root: bool) -> Command {
        // Disable built-in help flag (not visible to mut_args) and add custom replacement
        let cmd = cmd.disable_help_flag(true).arg(
            clap::Arg::new("help")
                .short('h')
                .long("help")
                .action(clap::ArgAction::Help)
                .help("Print help (see more with '--help')"),
        );

        // Only root command has --version
        let cmd = if is_root {
            cmd.disable_version_flag(true).arg(
                clap::Arg::new("version")
                    .short('V')
                    .long("version")
                    .action(clap::ArgAction::Version)
                    .help("Print version"),
            )
        } else {
            cmd
        };

        // Hide non-positional args that aren't already hidden.
        // Args originally marked hide=true stay hidden always.
        // Args we hide here will appear when completing `--` (all-hidden = all shown).
        let cmd = cmd.mut_args(|arg| {
            if arg.is_positional() || arg.is_hide_set() {
                arg
            } else {
                arg.hide(true)
            }
        });

        cmd.mut_subcommands(|sub| process_command(sub, false))
    }

    process_command(cmd, true)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Clap supplies canonical hook names, including silent aliases, without
    /// confusing option values or named filters with the selected hook type.
    #[test]
    fn test_parsed_hook_type() {
        for &name in cli::HOOK_TYPE_NAMES {
            let args = ["wt", "--config", "pre-switch", "hook", name, "post-start"];
            let globals = crate::parse_early_globals(args.into_iter().map(Into::into));
            assert_eq!(globals.hook_type, Some(name.parse().unwrap()), "{name}");
        }
        for (alias, canonical) in [("pre-create", "pre-start"), ("post-create", "post-start")] {
            let args = ["wt", "hook", alias];
            let globals = crate::parse_early_globals(args.into_iter().map(Into::into));
            assert_eq!(globals.hook_type, Some(canonical.parse().unwrap()));
        }
        let globals = crate::parse_early_globals(["wt", "switch", "pre-switch"].map(Into::into));
        assert_eq!(globals.hook_type, None);
    }

    #[test]
    fn test_truncate_template() {
        // Short template — returned as-is
        assert_eq!(truncate_template("echo hello"), "echo hello");

        // Multiline — only first line
        assert_eq!(truncate_template("line one\nline two"), "line one");

        // Leading/trailing whitespace trimmed
        assert_eq!(truncate_template("  spaced  \n"), "spaced");

        // Exactly 60 chars — no truncation
        let s60 = "a".repeat(60);
        assert_eq!(truncate_template(&s60), s60.as_str());

        // 61 chars — truncated to 57
        let s61 = "b".repeat(61);
        assert_eq!(truncate_template(&s61), &"b".repeat(57));

        // Multi-byte chars where byte 57 falls mid-character.
        // 'a' (1 byte) × 56 + '€' (3 bytes) × 2 = 62 bytes, > 60.
        // Byte 57 is the second byte of the first '€', so the loop backs up to 56.
        let multi = "a".repeat(56) + "€€";
        let result = truncate_template(&multi);
        assert_eq!(result.len(), 56);
        assert_eq!(result, "a".repeat(56));
    }

    #[test]
    fn test_discover_empty_path() {
        let result = discover_custom_subcommands_in(OsStr::new(""));
        assert!(result.is_empty());
    }

    #[test]
    fn test_discover_nonexistent_dir() {
        let result =
            discover_custom_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 = worktrunk::testing::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_custom_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 = worktrunk::testing::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_custom_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 = worktrunk::testing::tempdir().unwrap();
        let dir2 = worktrunk::testing::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_custom_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 = worktrunk::testing::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_custom_subcommands_in(dir.path().as_os_str());
        assert!(result.is_empty());
    }

    #[test]
    fn test_discover_skips_directories() {
        let dir = worktrunk::testing::test_tempdir();
        std::fs::create_dir(dir.path().join("wt-directory")).unwrap();
        assert!(discover_custom_subcommands_in(dir.path().as_os_str()).is_empty());
    }

    #[cfg(unix)]
    #[test]
    fn test_discover_checks_symlink_targets() {
        use std::os::unix::fs::{PermissionsExt, symlink};
        let dir = worktrunk::testing::test_tempdir();
        let executable = dir.path().join("executable");
        let non_executable = dir.path().join("data");
        std::fs::write(&executable, "#!/bin/sh\n").unwrap();
        std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
        std::fs::write(&non_executable, "data").unwrap();
        std::fs::set_permissions(&non_executable, std::fs::Permissions::from_mode(0o644)).unwrap();
        symlink(&executable, dir.path().join("wt-valid")).unwrap();
        symlink(&non_executable, dir.path().join("wt-invalid")).unwrap();
        symlink(dir.path().join("missing"), dir.path().join("wt-broken")).unwrap();
        assert_eq!(
            discover_custom_subcommands_in(dir.path().as_os_str()),
            vec!["valid"]
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_discover_finds_later_executable() {
        use std::os::unix::fs::PermissionsExt;
        let first = worktrunk::testing::test_tempdir();
        let second = worktrunk::testing::test_tempdir();
        for (dir, mode) in [(first.path(), 0o644), (second.path(), 0o755)] {
            let path = dir.join("wt-visible");
            std::fs::write(&path, "#!/bin/sh\n").unwrap();
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
        }
        let path = std::env::join_paths([first.path(), second.path()]).unwrap();
        assert_eq!(discover_custom_subcommands_in(&path), vec!["visible"]);
    }

    #[cfg(unix)]
    #[test]
    fn test_discover_results_are_sorted() {
        use std::os::unix::fs::PermissionsExt;
        let dir = worktrunk::testing::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_custom_subcommands_in(dir.path().as_os_str());
        assert_eq!(result, vec!["apple", "mango", "zebra"]);
    }

    #[test]
    fn test_inject_custom_adds_subcommands() {
        let cmd = Command::new("wt")
            .subcommand(Command::new("switch"))
            .subcommand(Command::new("list"));

        let cmd = inject_custom_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_custom_skips_builtins() {
        let cmd = Command::new("wt").subcommand(Command::new("switch").about("built-in switch"));

        let cmd = inject_custom_subcommand_list(cmd, vec!["switch".into(), "sync".into()]);

        // "switch" should still be the built-in, not the custom subcommand
        let switch = cmd.find_subcommand("switch").unwrap();
        assert_eq!(switch.get_about().unwrap().to_string(), "built-in switch");
        // "sync" should be added as a custom subcommand
        let sync = cmd.find_subcommand("sync").unwrap();
        assert!(sync.get_about().unwrap().to_string().contains("custom"));
    }

    #[test]
    fn test_inject_custom_empty_list() {
        let cmd = Command::new("wt").subcommand(Command::new("switch"));
        let cmd = inject_custom_subcommand_list(cmd, vec![]);
        assert_eq!(cmd.get_subcommands().count(), 1);
    }

    #[test]
    fn test_inject_custom_allows_trailing_args() {
        let cmd = Command::new("wt");
        let cmd = inject_custom_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_custom(
            "/nonexistent/binary/xxxxxxxx_wt_test",
            &[OsString::from("test")],
            OsStr::new("bash"),
            1,
            None,
        );
        assert!(result.is_none());
    }

    /// Invoke `try_forward_completion_to_custom`, polling past transient
    /// `ETXTBSY` spawn failures.
    ///
    /// Under parallel test execution, another thread can fork() while we hold
    /// the freshly-written script open for write. The child briefly inherits
    /// the writable fd, and Linux refuses to exec a file with outstanding
    /// writers (ETXTBSY). The condition clears within microseconds, so poll
    /// until the kernel lets us through. Surfaced elsewhere — e.g. under
    /// `cargo llvm-cov`, where coverage instrumentation widens every
    /// fork-to-exec window enough to hit this reliably.
    #[cfg(unix)]
    fn forward_with_etxtbsy_retry(
        binary: &str,
        args: &[OsString],
        shell: &OsStr,
    ) -> std::io::Result<Option<String>> {
        use std::io::ErrorKind;
        let mut result: Option<std::io::Result<Option<String>>> = None;
        worktrunk::testing::wait_for("ETXTBSY to clear and script to exec", || {
            match try_forward_completion_to_custom(binary, args, shell, 1, None) {
                Err(e) if e.kind() == ErrorKind::ExecutableFileBusy => false,
                other => {
                    result = Some(other);
                    true
                }
            }
        });
        result.expect("wait_for returned without recording a result")
    }

    #[cfg(unix)]
    #[test]
    fn test_forward_to_custom_binary() {
        use std::os::unix::fs::PermissionsExt;
        let dir = worktrunk::testing::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 output = forward_with_etxtbsy_retry(
            script.to_str().unwrap(),
            &[OsString::from("fake"), OsString::from("--")],
            OsStr::new("bash"),
        )
        .expect("spawn failed")
        .expect("script exited non-zero or produced invalid UTF-8");
        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 = worktrunk::testing::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();

        // The script spawned successfully but exited 1 — Ok(None), not Err.
        let result = forward_with_etxtbsy_retry(
            script.to_str().unwrap(),
            &[OsString::from("fail")],
            OsStr::new("bash"),
        )
        .expect("spawn failed");
        assert!(result.is_none());
    }
}