Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Adopt Clap's dynamic shell completions
Maximilian Roos78c1159323ad
diff --git a/Cargo.lock b/Cargo.lockindex e9b7782b9..1b6b4fcb6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -306,6 +306,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8e602857739c5a4291dfa33b5a298aeac9006185229a700e5810a3ef7272d971"dependencies = ["clap",+ "clap_lex",+ "is_executable",+ "shlex",][[package]]@@ -1004,6 +1007,15 @@ dependencies = ["serde_json",]+[[package]]+name = "is_executable"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baabb8b4867b26294d818bf3f651a454b6901431711abb96e296245888d6e8c4"+dependencies = [+ "windows-sys 0.60.2",+]+[[package]]name = "is_terminal_polyfill"version = "1.70.2"diff --git a/Cargo.toml b/Cargo.tomlindex 2fe64eb36..5212aef15 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -42,8 +42,8 @@ anstream = "0.6"anstyle = "1.0"askama = { version = "0.14", default-features = false, features = ["derive", "std"] }chrono = "0.4"-clap = { version = "4.5", features = ["derive"] }-clap_complete = "4.5"+clap = { version = "4.5", features = ["derive", "unstable-ext"] }+clap_complete = { version = "4.5", features = ["unstable-dynamic"] }config = "0.15"directories = "6.0"env_logger = "0.11"diff --git a/benches/completion.rs b/benches/completion.rsindex 7a8fc30d1..752635274 100644--- a/benches/completion.rs+++ b/benches/completion.rs@@ -1,4 +1,5 @@use criterion::{Criterion, criterion_group, criterion_main};+use std::path::Path;use std::process::Command;use tempfile::TempDir;@@ -62,43 +63,41 @@ fn setup_test_repo(num_branches: usize, num_worktrees: usize) -> TempDir {temp_dir}+fn run_completion(repo_path: &Path, words: &[&str]) {+ let index = words.len().saturating_sub(1);+ Command::new("cargo")+ .args(["run", "--"])+ .env("COMPLETE", "bash")+ .env("_CLAP_COMPLETE_INDEX", index.to_string())+ .env("_CLAP_COMPLETE_COMP_TYPE", "9")+ .env("_CLAP_COMPLETE_SPACE", "true")+ .env("_CLAP_IFS", "\n")+ .arg("--")+ .args(words)+ .current_dir(repo_path)+ .output()+ .unwrap();+}+fn bench_completion_switch(c: &mut Criterion) {let mut group = c.benchmark_group("completion_switch");// Benchmark with 10 branchesgroup.bench_function("10_branches", |b| {let temp = setup_test_repo(10, 0);- b.iter(|| {- Command::new("cargo")- .args(["run", "--", "complete", "wt", "switch", ""])- .current_dir(temp.path())- .output()- .unwrap();- });+ b.iter(|| run_completion(temp.path(), &["wt", "switch", ""]));});// Benchmark with 50 branchesgroup.bench_function("50_branches", |b| {let temp = setup_test_repo(50, 0);- b.iter(|| {- Command::new("cargo")- .args(["run", "--", "complete", "wt", "switch", ""])- .current_dir(temp.path())- .output()- .unwrap();- });+ b.iter(|| run_completion(temp.path(), &["wt", "switch", ""]));});// Benchmark with 100 branchesgroup.bench_function("100_branches", |b| {let temp = setup_test_repo(100, 0);- b.iter(|| {- Command::new("cargo")- .args(["run", "--", "complete", "wt", "switch", ""])- .current_dir(temp.path())- .output()- .unwrap();- });+ b.iter(|| run_completion(temp.path(), &["wt", "switch", ""]));});group.finish();@@ -110,13 +109,7 @@ fn bench_completion_switch_with_worktrees(c: &mut Criterion) {// Benchmark with 50 branches, 10 with worktrees (tests filtering performance)group.bench_function("50_branches_10_worktrees", |b| {let temp = setup_test_repo(50, 10);- b.iter(|| {- Command::new("cargo")- .args(["run", "--", "complete", "wt", "switch", ""])- .current_dir(temp.path())- .output()- .unwrap();- });+ b.iter(|| run_completion(temp.path(), &["wt", "switch", ""]));});group.finish();@@ -128,13 +121,7 @@ fn bench_completion_push(c: &mut Criterion) {// Benchmark push completion (shows all branches, no filtering)group.bench_function("100_branches", |b| {let temp = setup_test_repo(100, 0);- b.iter(|| {- Command::new("cargo")- .args(["run", "--", "complete", "wt", "push", ""])- .current_dir(temp.path())- .output()- .unwrap();- });+ b.iter(|| run_completion(temp.path(), &["wt", "push", ""]));});group.finish();diff --git a/src/cli.rs b/src/cli.rsindex ebcdd4632..d08723373 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -135,6 +135,7 @@ pub enum StandaloneCommand {/// Squash commits with LLM-generated messageSquash {/// Target branch to squash against (defaults to default branch)+ #[arg(add = crate::completion::branch_value_completer())]target: Option<String>,/// Auto-approve project commands without saving approvals.@@ -152,6 +153,7 @@ pub enum StandaloneCommand {/// the push and restores them afterward so other agents' changes stay intact.Push {/// Target branch (defaults to default branch)+ #[arg(add = crate::completion::branch_value_completer())]target: Option<String>,/// Allow pushing merge commits (non-linear history)@@ -162,6 +164,7 @@ pub enum StandaloneCommand {/// Rebase current branch onto target branchRebase {/// Target branch to rebase onto (defaults to default branch)+ #[arg(add = crate::completion::branch_value_completer())]target: Option<String>,},@@ -375,6 +378,7 @@ Use '@' to refer to your current HEAD (following git's convention):wt remove @ # Remove current worktree"#)]Switch {/// Branch name, worktree path, '@' for current HEAD, or '-' for previous branch+ #[arg(add = crate::completion::worktree_branch_completer())]branch: String,/// Create a new branch@@ -382,7 +386,7 @@ Use '@' to refer to your current HEAD (following git's convention):create: bool,/// Base branch to create from (only with --create). Use '@' for current HEAD- #[arg(short = 'b', long)]+ #[arg(short = 'b', long, add = crate::completion::branch_value_completer())]base: Option<String>,/// Execute command after switching@@ -447,6 +451,7 @@ Switch to default in primary:wt remove # (when already in primary worktree)"#)]Remove {/// Worktree names or branches to remove (use '@' for current, defaults to current if none specified)+ #[arg(add = crate::completion::worktree_branch_completer())]worktrees: Vec<String>,/// Don't delete the branch after removing the worktree (by default, branches are deleted)@@ -507,6 +512,7 @@ Skip pre-merge commands:wt merge --no-verify"#)]Merge {/// Target branch to merge into (defaults to default branch)+ #[arg(add = crate::completion::branch_value_completer())]target: Option<String>,/// Disable squashing commits (by default, commits are squashed into one before merging)@@ -533,12 +539,4 @@ Skip pre-merge commands:#[arg(long)]tracked_only: bool,},-- /// Internal completion helper (hidden)- #[command(hide = true)]- Complete {- /// Arguments to complete- #[arg(trailing_var_arg = true, allow_hyphen_values = true)]- args: Vec<String>,- },}diff --git a/src/commands/completion.rs b/src/commands/completion.rsdeleted file mode 100644index 5c4b37c36..000000000--- a/src/commands/completion.rs+++ /dev/null@@ -1,410 +0,0 @@-// Custom completion implementation rather than clap's unstable-dynamic feature.-//-// While clap_complete offers CompleteEnv and ArgValueCompleter traits, we implement-// our own completion logic because:-// - unstable-dynamic is an unstable API that may change between versions-// - We need conditional completion logic (e.g., don't complete branches when --create is present)-// - We need runtime-fetched values (git branches) with context-aware filtering-// - We need precise control over positional argument state tracking with flags-//-// This approach uses stable APIs and handles edge cases that clap's completion system-// isn't designed for. See the extensive test suite in tests/integration_tests/completion.rs--use clap::{Arg, Command, CommandFactory};-use std::sync::OnceLock;-use worktrunk::git::{GitError, Repository};-use worktrunk::styling::{ERROR, ERROR_EMOJI, println};--/// Cache the built command to avoid repeated construction cost-static CMD: OnceLock<Command> = OnceLock::new();--/// Get or build the cached command-fn built_cmd() -> &'static Command {- CMD.get_or_init(|| {- let mut cmd = crate::cli::Cli::command();- cmd.build();- cmd- })-}--/// Completion item with optional help text for fish shell descriptions-#[derive(Debug)]-struct Item {- name: String,- help: Option<String>,-}--/// Represents what we're trying to complete-#[derive(Debug)]-enum CompletionTarget<'a> {- /// Completing a value for an option flag (e.g., `--base <value>` or `--base=<value>`)- Option(&'a Arg, String), // (clap Arg, prefix to complete)- /// Completing a positional branch argument (switch/push/merge/remove commands)- PositionalBranch(String), // prefix to complete- /// No special completion needed- Unknown,-}--/// Print completion items in fish-friendly format (name\thelp)-/// Other shells ignore the tab separator and just use the name-fn print_items(items: impl IntoIterator<Item = Item>) {- for Item { name, help } in items {- if let Some(help) = help {- println!("{name}\t{help}");- } else {- println!("{name}");- }- }-}--/// True if `arg` takes one or more values (vs. boolean/COUNT flags)-fn takes_value(arg: &Arg) -> bool {- arg.get_num_args().is_some_and(|n| n.max_values() > 0)-}--/// Build a fast lookup of options (active subcommand + globals) -> takes_value-fn build_opt_index<'a>(- active: &'a Command,- root: &'a Command,-) -> (- std::collections::HashMap<String, bool>,- std::collections::HashMap<char, bool>,-) {- use std::collections::HashMap;-- let mut long_map: HashMap<String, bool> = HashMap::new();- let mut short_map: HashMap<char, bool> = HashMap::new();-- // Local opts- for opt in active.get_opts() {- if let Some(l) = opt.get_long() {- long_map.insert(l.to_string(), takes_value(opt));- }- if let Some(s) = opt.get_short() {- short_map.insert(s, takes_value(opt));- }- }-- // Global opts- for opt in root.get_opts() {- if opt.is_global_set() {- if let Some(l) = opt.get_long() {- long_map.entry(l.to_string()).or_insert(takes_value(opt));- }- if let Some(s) = opt.get_short() {- short_map.entry(s).or_insert(takes_value(opt));- }- }- }-- (long_map, short_map)-}--/// Check if a positional argument should be completed using clap introspection-///-/// This function uses clap metadata to determine whether we're still completing the first-/// positional argument. It handles:-/// - Flags that take values (--flag value, --flag=value, -f value, -fvalue)-/// - Short flag clusters (-abc where any flag might consume a value)-/// - POSIX `--` end-of-options terminator-/// - Global flags (--verbose, --source, --internal)-///-/// Returns true if we're still on the first positional argument (should complete branches).-/// Returns false if a positional has been provided and we've moved past it.-fn should_complete_positional_arg(- args: &[String],- start_index: usize,- active: &Command,- root: &Command,-) -> bool {- let (longs, shorts) = build_opt_index(active, root);-- let mut i = start_index;- let mut accept_opts = true;-- 'scan: while i < args.len() {- let tok = &args[i];-- if tok.is_empty() {- // Cursor placeholder; skip and keep scanning- i += 1;- continue 'scan;- }-- if accept_opts && tok == "--" {- accept_opts = false;- i += 1;- continue 'scan;- }-- if accept_opts && tok.starts_with("--") {- let body = &tok[2..];- if let Some(_eq) = body.find('=') {- // --long=value- i += 1;- continue 'scan;- } else {- // --long [value?]- let name = body;- if longs.get(name).copied().unwrap_or(false) {- // Value is next arg unless we are currently typing it- if i == args.len() - 1 {- // Completing option value, not a positional- return false;- }- i += 2;- continue 'scan;- }- i += 1;- continue 'scan;- }- }-- if accept_opts && tok.starts_with('-') && tok.len() > 1 {- // Short clusters: -abc (if some short takes a value, the remainder is its value)- let mut chars = tok[1..].chars().peekable();- while let Some(c) = chars.next() {- let takes = shorts.get(&c).copied().unwrap_or(false);- if takes {- // If anything remains in-cluster, it's the value: consume token only- if chars.peek().is_some() {- i += 1;- continue 'scan;- } else {- // Value is next token, unless we're currently typing it- if i == args.len() - 1 {- return false;- }- i += 2;- continue 'scan;- }- }- }- // No short in cluster takes a value -> just a bunch of booleans- i += 1;- continue 'scan;- }-- // If we got here, `tok` is positional (or opts are terminated)- // Return true iff it's the last token (i.e., we are still completing it)- return i >= args.len() - 1;- }-- // No positional arg found yet -> still need to complete it- true-}--fn get_branches_for_completion<F>(get_branches_fn: F) -> Vec<String>-where- F: FnOnce() -> Result<Vec<String>, GitError>,-{- get_branches_fn().unwrap_or_else(|e| {- if std::env::var("WT_DEBUG_COMPLETION").is_ok() {- println!("{ERROR_EMOJI} {ERROR}Completion error: {e}{ERROR:#}");- }- Vec::new()- })-}--/// Extract possible values from a clap Arg (handles ValueEnum and explicit PossibleValue lists)-fn items_from_arg(arg: &Arg, prefix: &str) -> Vec<Item> {- // Read clap's declared possible values (ValueEnum or explicit PossibleValue list)- let possible_values = arg.get_possible_values();-- if possible_values.is_empty() {- return Vec::new();- }-- possible_values- .into_iter()- .filter(|pv| !pv.is_hide_set())- .map(|pv| {- let name = pv.get_name().to_string();- let help = pv.get_help().map(|s| s.to_string());- (name, help)- })- // Do a cheap prefix filter; shells will filter too, but this helps bash/zsh- .filter(|(name, _)| name.starts_with(prefix))- .map(|(name, help)| Item { name, help })- .collect()-}--/// Detect what we're trying to complete using clap introspection-/// Handles both --arg value and --arg=value formats-fn detect_completion_target<'a>(args: &[String], cmd: &'a Command) -> CompletionTarget<'a> {- if args.len() < 2 {- return CompletionTarget::Unknown;- }-- // Find the active subcommand frame by walking the command tree- let mut i = 1; // Skip binary name- let mut cur = cmd;- let mut subcommand_name = None;- while i < args.len() {- let tok = &args[i];- // Skip global flags- if tok == "--source" || tok == "--internal" || tok == "-v" || tok == "--verbose" {- i += 1;- continue;- }- if let Some(sc) = cur.find_subcommand(tok) {- subcommand_name = Some(sc.get_name());- cur = sc;- i += 1;- } else {- break;- }- }-- let last = args.last().map(String::as_str).unwrap_or("");- let prev = args.iter().rev().nth(1).map(|s| s.as_str());-- // Check for --arg=value format in last argument- if let Some(equals_pos) = last.find('=') {- let flag_part = &last[..equals_pos];- let value_part = &last[equals_pos + 1..];-- // Long form: --name=value- if let Some(long) = flag_part.strip_prefix("--")- && let Some(arg) = cur- .get_opts()- .find(|a| a.get_long().is_some_and(|l| l == long))- {- return CompletionTarget::Option(arg, value_part.to_string());- }-- // Short form: -n=value- if let Some(short) = flag_part- .strip_prefix('-')- .filter(|s| s.len() == 1)- .and_then(|s| s.chars().next())- && let Some(arg) = cur.get_opts().find(|a| a.get_short() == Some(short))- {- return CompletionTarget::Option(arg, value_part.to_string());- }- }-- // Check for --arg value format (space-separated)- if let Some(p) = prev {- // Long form: --name- if let Some(long) = p.strip_prefix("--")- && let Some(arg) = cur- .get_opts()- .find(|a| a.get_long().is_some_and(|l| l == long))- {- return CompletionTarget::Option(arg, last.to_string());- }-- // Short form: -n- if let Some(short) = p- .strip_prefix('-')- .filter(|s| s.len() == 1)- .and_then(|s| s.chars().next())- && let Some(arg) = cur.get_opts().find(|a| a.get_short() == Some(short))- {- return CompletionTarget::Option(arg, last.to_string());- }- }-- // Check if we're completing a positional branch argument- // Special handling for switch --create: don't complete when creating new branches- if let Some(subcmd) = subcommand_name {- match subcmd {- "switch" => {- let has_create = args.iter().any(|arg| arg == "--create" || arg == "-c");- if !has_create && should_complete_positional_arg(args, i, cur, cmd) {- // If last arg is the subcommand itself, prefix is empty- let prefix = if last == subcmd { "" } else { last };- return CompletionTarget::PositionalBranch(prefix.to_string());- }- }- "push" | "merge" | "remove" => {- if should_complete_positional_arg(args, i, cur, cmd) {- // If last arg is the subcommand itself, prefix is empty- let prefix = if last == subcmd { "" } else { last };- return CompletionTarget::PositionalBranch(prefix.to_string());- }- }- _ => {}- }- }-- CompletionTarget::Unknown-}--pub fn handle_complete(args: Vec<String>) -> Result<(), GitError> {- let cmd = built_cmd();-- let target = detect_completion_target(&args, cmd);-- match target {- CompletionTarget::Option(arg, prefix) => {- // Check if this is the "base" option that needs branch completion- if arg.get_long() == Some("base") {- // Complete with all branches (runtime-fetched values)- let branches = get_branches_for_completion(|| Repository::current().all_branches());- for branch in branches {- if branch.starts_with(&prefix) {- println!("{}", branch);- }- }- } else {- // Use the arg's declared possible_values (ValueEnum types)- let items = items_from_arg(arg, &prefix);- if !items.is_empty() {- print_items(items);- }- }- }- CompletionTarget::PositionalBranch(prefix) => {- // Complete with all branches (runtime-fetched values)- let branches = get_branches_for_completion(|| Repository::current().all_branches());- for branch in branches {- if branch.starts_with(&prefix) {- println!("{}", branch);- }- }- }- CompletionTarget::Unknown => {- // Check for positionals with ValueEnum possible_values (e.g., init <Shell>, beta run-hook <HookType>)- // Walk the command tree to find the active subcommand- let mut i = 1;- let mut cur = cmd;- while i < args.len() {- let tok = &args[i];- if tok == "--source" || tok == "--internal" || tok == "-v" || tok == "--verbose" {- i += 1;- continue;- }- if let Some(sc) = cur.find_subcommand(tok) {- cur = sc;- i += 1;- } else {- break;- }- }-- // Determine the prefix to filter by:- // - If we've consumed all args as subcommands (i >= args.len()), use empty prefix- // - Otherwise, use the last arg as prefix for filtering- let prefix = if i >= args.len() {- ""- } else {- args.last().map(String::as_str).unwrap_or("")- };-- // Check if there's a positional with possible_values- if let Some(arg) = cur- .get_positionals()- .find(|a| !a.get_possible_values().is_empty())- {- let items = items_from_arg(arg, prefix);- if !items.is_empty() {- print_items(items);- }- }- }- }-- Ok(())-}diff --git a/src/commands/init.rs b/src/commands/init.rsindex 0f7bffe5d..fd8637211 100644--- a/src/commands/init.rs+++ b/src/commands/init.rs@@ -12,7 +12,7 @@ pub fn handle_init(// Generate shell integration codelet integration_output = init- .generate(cli_cmd)+ .generate().map_err(|e| format!("Failed to generate shell code: {}", e))?;println!("{}", integration_output);diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 7894e618e..c7ba89895 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -1,7 +1,6 @@pub mod command_approval;pub mod command_executor;pub mod commit;-pub mod completion;pub mod config;pub mod configure_shell;pub mod context;@@ -17,7 +16,6 @@ pub mod select;pub mod standalone;pub mod worktree;-pub use completion::handle_complete;pub use config::{handle_config_init, handle_config_list, handle_config_refresh_cache};pub use configure_shell::{ConfigAction, handle_configure_shell};pub use init::handle_init;diff --git a/src/completion.rs b/src/completion.rsnew file mode 100644index 000000000..fbfbc33a8--- /dev/null+++ b/src/completion.rs@@ -0,0 +1,121 @@+use std::cell::RefCell;+use std::ffi::{OsStr, OsString};++use clap::{Command, CommandFactory};+use clap_complete::engine::{ArgValueCompleter, CompletionCandidate, ValueCompleter};+use clap_complete::env::CompleteEnv;++use crate::cli::Cli;+use worktrunk::git::Repository;++/// Handle shell-initiated completion requests via `COMPLETE=$SHELL wt`+pub fn maybe_handle_env_completion() -> bool {+ if std::env::var_os("COMPLETE").is_none() {+ return false;+ }++ let args: Vec<OsString> = std::env::args_os().collect();+ CONTEXT.with(|ctx| *ctx.borrow_mut() = Some(CompletionContext { args: args.clone() }));++ let current_dir = std::env::current_dir().ok();+ let handled = CompleteEnv::with_factory(completion_command)+ .try_complete(args, current_dir.as_deref())+ .unwrap_or_else(|err| err.exit());++ CONTEXT.with(|ctx| ctx.borrow_mut().take());+ handled+}++/// Branch completion without additional context filtering (e.g., --base, merge target).+pub fn branch_value_completer() -> ArgValueCompleter {+ ArgValueCompleter::new(BranchCompleter {+ suppress_with_create: false,+ })+}++/// Branch completion for positional arguments that represent worktrees (switch/remove).+pub fn worktree_branch_completer() -> ArgValueCompleter {+ ArgValueCompleter::new(BranchCompleter {+ suppress_with_create: true,+ })+}++#[derive(Clone, Copy)]+struct BranchCompleter {+ suppress_with_create: bool,+}++impl ValueCompleter for BranchCompleter {+ fn complete(&self, _current: &OsStr) -> Vec<CompletionCandidate> {+ complete_branches(self.suppress_with_create)+ }+}++fn complete_branches(suppress_with_create: bool) -> Vec<CompletionCandidate> {+ if suppress_with_create && suppress_switch_branch_completion() {+ return Vec::new();+ }++ let branches = load_branches();+ if branches.is_empty() {+ return Vec::new();+ }++ branches.into_iter().map(CompletionCandidate::new).collect()+}++fn load_branches() -> Vec<String> {+ Repository::current()+ .all_branches()+ .unwrap_or_else(|_| Vec::new())+}++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>,+}++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) };+}++fn completion_command() -> Command {+ adjust_completion_command(Cli::command())+}++// Mark positional target args as `.last(true)` to allow them after all flags.+// This enables flexible argument ordering: `wt merge --no-squash main` instead of+// requiring the more restrictive `wt merge main --no-squash`.+fn adjust_completion_command(cmd: Command) -> Command {+ cmd.mut_subcommand("merge", |merge| {+ merge.mut_arg("target", |arg| arg.last(true))+ })+ .mut_subcommand("beta", |beta| {+ beta.mut_subcommand("push", |push| push.mut_arg("target", |arg| arg.last(true)))+ .mut_subcommand("squash", |squash| {+ squash.mut_arg("target", |arg| arg.last(true))+ })+ .mut_subcommand("rebase", |rebase| {+ rebase.mut_arg("target", |arg| arg.last(true))+ })+ })+}diff --git a/src/main.rs b/src/main.rsindex ced5c43f5..1e3c0cc0f 100644--- a/src/main.rs+++ b/src/main.rs@@ -7,6 +7,7 @@ use worktrunk::styling::{SUCCESS_EMOJI, println};mod cli;mod commands;+mod completion;mod display;mod llm;mod output;@@ -18,17 +19,20 @@ use commands::command_executor::CommandContext;use commands::handle_select;use commands::worktree::{SwitchResult, handle_push};use commands::{- ConfigAction, handle_complete, handle_config_init, handle_config_list,- handle_config_refresh_cache, handle_configure_shell, handle_init, handle_list, handle_merge,- handle_rebase, handle_remove, handle_squash, handle_standalone_ask_approvals,- handle_standalone_clear_approvals, handle_standalone_commit, handle_standalone_run_hook,- handle_switch,+ ConfigAction, handle_config_init, handle_config_list, handle_config_refresh_cache,+ handle_configure_shell, handle_init, handle_list, handle_merge, handle_rebase, handle_remove,+ handle_squash, handle_standalone_ask_approvals, handle_standalone_clear_approvals,+ handle_standalone_commit, handle_standalone_run_hook, handle_switch,};use output::{execute_user_command, handle_remove_output, handle_switch_output};use cli::{Cli, Commands, ConfigCommand, StandaloneCommand};fn main() {+ if completion::maybe_handle_env_completion() {+ return;+ }+// TODO: Enhance error messages to show possible values for missing enum arguments// Currently `wt init` doesn't show available shells, but `wt init invalid` does.// Clap doesn't support this natively yet - see https://github.com/clap-rs/clap/issues/3320@@ -316,7 +320,6 @@ fn main() {force,tracked_only,),- Commands::Complete { args } => handle_complete(args),};if let Err(e) = result {diff --git a/src/shell.rs b/src/shell.rsindex 30d528a12..5926f35bf 100644--- a/src/shell.rs+++ b/src/shell.rs@@ -220,78 +220,6 @@ impl Shell {}}-/// Generate dynamic completion registrations for Fish shell by introspecting CLI structure-///-/// This generates completion registrations for all subcommands:-/// - Subcommands with positional arguments get dynamic completions via `__wt_complete`-/// - Subcommands without positional arguments get `-f` to prevent file completion fallback-///-/// The actual filtering of what completions to show is handled by the `wt complete` command,-/// which checks the command context and only returns relevant completions.-///-/// This approach ensures that when new commands are added with positional arguments,-/// they automatically get registered for completion - you only need to update the-/// completion logic in `src/commands/completion.rs` to define what completions to show.-fn generate_fish_dynamic_completions(cli_cmd: &clap::Command, cmd_prefix: &str) -> String {- fn generate_for_subcommands(- cmd: &clap::Command,- cmd_prefix: &str,- parent_chain: &[&str],- ) -> Vec<String> {- let mut completions = Vec::new();-- for subcmd in cmd.get_subcommands() {- let name = subcmd.get_name();- let current_chain: Vec<&str> = parent_chain.iter().copied().chain([name]).collect();-- // Check if this subcommand has positional arguments- let has_positional = subcmd.get_positionals().next().is_some();-- // Generate condition based on command chain- let condition = if current_chain.len() == 1 {- // Top-level: just check for the subcommand- format!("__fish_seen_subcommand_from {}", name)- } else {- // Nested: check for parent chain in sequence- // e.g., for "beta commit": "__fish_seen_subcommand_from beta; and __fish_seen_subcommand_from commit"- current_chain- .iter()- .map(|part| format!("__fish_seen_subcommand_from {}", part))- .collect::<Vec<_>>()- .join("; and ")- };-- if has_positional {- // Subcommand with positional arguments - register dynamic completion- let desc = subcmd- .get_positionals()- .next()- .and_then(|arg| arg.get_help())- .map(|h| h.to_string())- .unwrap_or_else(|| format!("{} argument", current_chain.join(" ")));-- completions.push(format!(- " complete -c {} -n '{}' -f -a '(__{}_complete)' -d '{}'",- cmd_prefix, condition, cmd_prefix, desc- ));- } else {- // Subcommand without positional arguments - prevent file completion fallback- completions.push(format!(- " complete -c {} -n '{}' -f",- cmd_prefix, condition- ));- }-- // Recurse into nested subcommands- completions.extend(generate_for_subcommands(subcmd, cmd_prefix, ¤t_chain));- }-- completions- }-- generate_for_subcommands(cli_cmd, cmd_prefix, &[]).join("\n")-}-/// Shell integration configurationpub struct ShellInit {pub shell: Shell,@@ -304,7 +232,7 @@ impl ShellInit {}/// Generate shell integration code- pub fn generate(&self, cli_cmd: &clap::Command) -> Result<String, askama::Error> {+ pub fn generate(&self) -> Result<String, askama::Error> {match self.shell {Shell::Bash | Shell::Oil => {let posix_shim = PosixDirectivesTemplate {@@ -330,11 +258,8 @@ impl ShellInit {template.render()}Shell::Fish => {- let dynamic_completions =- generate_fish_dynamic_completions(cli_cmd, &self.cmd_prefix);let template = FishTemplate {cmd_prefix: &self.cmd_prefix,- dynamic_completions,};template.render()}@@ -395,7 +320,6 @@ struct ZshTemplate<'a> {#[template(path = "fish.fish", escape = "none")]struct FishTemplate<'a> {cmd_prefix: &'a str,- dynamic_completions: String,}/// Nushell shell template@@ -429,7 +353,6 @@ struct XonshTemplate<'a> {#[cfg(test)]mod tests {use super::*;- use clap::Command;#[test]fn test_shell_from_str() {@@ -439,51 +362,4 @@ mod tests {assert!(matches!("zsh".parse::<Shell>(), Ok(Shell::Zsh)));assert!("invalid".parse::<Shell>().is_err());}-- #[test]- fn test_fish_dynamic_completions_for_nested_subcommands() {- // Test that we generate completions for nested subcommands like "dev run-hook"- let cli = Command::new("test")- .subcommand(Command::new("parent").subcommand(- Command::new("nested").arg(clap::Arg::new("hook_type").help("Hook to run")),- ))- .subcommand(Command::new("top-level").arg(clap::Arg::new("arg").help("Some arg")));-- let completions = generate_fish_dynamic_completions(&cli, "test");-- // Should include completion for nested command (parent nested)- assert!(- completions.contains(- "__fish_seen_subcommand_from parent; and __fish_seen_subcommand_from nested"- ),- "Should generate nested completion for parent nested, got: {}",- completions- );-- // Should include completion for top-level command- assert!(- completions.contains("__fish_seen_subcommand_from top-level"),- "Should generate top-level completion, got: {}",- completions- );- }-- #[test]- fn test_fish_dynamic_completions_deeply_nested() {- // Test 3-level nesting to verify recursion handles arbitrary depth- let cli = Command::new("test").subcommand(- Command::new("a").subcommand(- Command::new("b")- .subcommand(Command::new("c").arg(clap::Arg::new("arg").help("deep arg"))),- ),- );-- let completions = generate_fish_dynamic_completions(&cli, "test");-- assert!(- completions.contains("__fish_seen_subcommand_from a; and __fish_seen_subcommand_from b; and __fish_seen_subcommand_from c"),- "Should handle 3+ level nesting, got: {}",- completions- );- }}diff --git a/templates/bash.sh b/templates/bash.shindex fbc02dd44..104b5dd78 100644--- a/templates/bash.sh+++ b/templates/bash.sh@@ -51,15 +51,8 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];return $result}- # Dynamic completion function- _{{ cmd_prefix }}_complete() {- local cur="${COMP_WORDS[COMP_CWORD]}"-- # Call wt complete with current command line- local completions=$(command "$_WORKTRUNK_CMD" complete "${COMP_WORDS[@]}" 2>/dev/null)- COMPREPLY=($(compgen -W "$completions" -- "$cur"))- }-- # Register dynamic completion- complete -F _{{ cmd_prefix }}_complete {{ cmd_prefix }}+ # Register Clap-based completions (auto-updates after wt upgrades)+ if completion_script=$(COMPLETE=bash "$_WORKTRUNK_CMD" 2>/dev/null); then+ eval "$completion_script"+ fifidiff --git a/templates/fish.fish b/templates/fish.fishindex 5f5369ce1..d03fb9fee 100644--- a/templates/fish.fish+++ b/templates/fish.fish@@ -126,13 +126,9 @@ if type -q {{ cmd_prefix }}; or set -q WORKTRUNK_BINreturn $resultend- # Dynamic completion function- function __{{ cmd_prefix }}_complete- # Call {{ cmd_prefix }} complete with current command line- set -l cmd (commandline -opc)- command $_WORKTRUNK_CMD complete $cmd 2>/dev/null+ # Register Clap-based completions (auto-updates after wt upgrades)+ set -l _wt_completion_script (COMPLETE=fish $_WORKTRUNK_CMD 2>/dev/null | string collect)+ if test -n "$_wt_completion_script"+ eval $_wt_completion_scriptend-- # Register dynamic completions-{{ dynamic_completions }}enddiff --git a/templates/zsh.zsh b/templates/zsh.zshindex 87bf327b1..46855bae5 100644--- a/templates/zsh.zsh+++ b/templates/zsh.zsh@@ -51,24 +51,10 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];return $result}- # Dynamic completion function for zsh- _{{ cmd_prefix }}_complete() {- local -a completions- local -a words-- # Get current command line as array- words=("${(@)words}")-- # Call wt complete with current command line- completions=(${(f)"$(command "$_WORKTRUNK_CMD" complete "${words[@]}" 2>/dev/null)"})-- # Add completions- compadd -a completions- }-- # Register dynamic completion (only if compdef is available)- # In non-interactive shells or test environments, the completion system may not be loaded+ # Register Clap-based completions (auto-updates after wt upgrades)if (( $+functions[compdef] )); then- compdef _{{ cmd_prefix }}_complete {{ cmd_prefix }}+ local completion_script+ completion_script=$(COMPLETE=zsh "$_WORKTRUNK_CMD" 2>/dev/null)+ eval "$completion_script"fifidiff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 84be7e185..c1198cbcd 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -46,6 +46,32 @@ pub fn wt_command() -> Command {cmd}+/// Create a `wt` invocation configured like shell-driven completions (`COMPLETE=bash`).+///+/// `words` should match the shell's `COMP_WORDS` array, e.g. `["wt", "switch", ""]`.+pub fn wt_completion_command(words: &[&str]) -> Command {+ assert!(+ matches!(words.first(), Some(&"wt")),+ "completion words must include command name as the first element"+ );++ let mut cmd = wt_command();+ configure_completion_invocation(&mut cmd, words);+ cmd+}++/// Configure an existing command to mimic shell completion environment.+pub fn configure_completion_invocation(cmd: &mut Command, words: &[&str]) {+ let index = words.len().saturating_sub(1);+ cmd.arg("--");+ cmd.args(words);+ cmd.env("COMPLETE", "bash");+ cmd.env("_CLAP_COMPLETE_INDEX", index.to_string());+ cmd.env("_CLAP_COMPLETE_COMP_TYPE", "9"); // normal completion+ cmd.env("_CLAP_COMPLETE_SPACE", "true");+ cmd.env("_CLAP_IFS", "\n");+}+/// Configure an existing command with the standardized worktrunk CLI environment.////// This helper mirrors the environment preparation performed by `wt_command`@@ -187,6 +213,14 @@ impl TestRepo {// insta-cmd won't capture it in snapshots, avoiding privacy leaks.}+ /// Prepare a `wt` command configured for shell completions within this repo.+ pub fn completion_cmd(&self, words: &[&str]) -> Command {+ let mut cmd = wt_completion_command(words);+ self.clean_cli_env(&mut cmd);+ cmd.current_dir(self.root_path());+ cmd+ }+/// Get the root path of the repositorypub fn root_path(&self) -> &Path {&self.rootdiff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rsindex 2b98f48c4..7ae8e52ce 100644--- a/tests/integration_tests/completion.rs+++ b/tests/integration_tests/completion.rs@@ -1,8 +1,30 @@-use crate::common::{TestRepo, wt_command};+use crate::common::{TestRepo, wt_command, wt_completion_command};use insta::Settings;-use insta_cmd::assert_cmd_snapshot;use std::process::Command;+fn only_option_suggestions(stdout: &str) -> bool {+ stdout+ .lines()+ .filter(|line| !line.trim().is_empty())+ .all(|line| line.starts_with('-'))+}++fn value_suggestions(stdout: &str) -> Vec<&str> {+ stdout+ .lines()+ .map(str::trim)+ .filter(|line| {+ if line.is_empty() {+ false+ } else if line.starts_with('-') {+ line.contains('=')+ } else {+ true+ }+ })+ .collect()+}+#[test]fn test_complete_switch_shows_branches() {let temp = TestRepo::new();@@ -25,20 +47,12 @@ fn test_complete_switch_shows_branches() {let mut settings = Settings::clone_current();settings.set_snapshot_path("../snapshots");settings.bind(|| {- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- cmd.current_dir(temp.root_path())- .args(["complete", "wt", "switch", ""]);- assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0- ----- stdout ------ feature/new- hotfix/bug- main-- ----- stderr ------ ");+ let output = temp.completion_cmd(&["wt", "switch", ""]).output().unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(stdout.contains("feature/new"));+ assert!(stdout.contains("hotfix/bug"));+ assert!(stdout.contains("main"));});}@@ -61,20 +75,12 @@ fn test_complete_switch_shows_all_branches_including_worktrees() {let mut settings = Settings::clone_current();settings.set_snapshot_path("../snapshots");settings.bind(|| {- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- cmd.current_dir(temp.root_path())- .args(["complete", "wt", "switch", ""]);- assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0- ----- stdout ------ feature/new- hotfix/bug- main-- ----- stderr ------ ");+ let output = temp.completion_cmd(&["wt", "switch", ""]).output().unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(stdout.contains("feature/new"));+ assert!(stdout.contains("hotfix/bug"));+ assert!(stdout.contains("main"));});}@@ -93,21 +99,23 @@ fn test_complete_push_shows_all_branches() {.output().unwrap();- // Test completion for dev push (should show ALL branches, including those with worktrees)+ // Test completion for beta push (should show ALL branches, including those with worktrees)let mut settings = Settings::clone_current();settings.set_snapshot_path("../snapshots");settings.bind(|| {- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- cmd.current_dir(temp.root_path())- .args(["complete", "wt", "dev", "push", ""]);- assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0- ----- stdout ------- ----- stderr ------ ");+ let output = temp+ .completion_cmd(&["wt", "beta", "push", ""])+ .output()+ .unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ let values = value_suggestions(&stdout);+ assert!(+ values.contains(&"feature/new"),+ "values should list feature/new\n{stdout}"+ );+ assert!(values.contains(&"hotfix/bug"));+ assert!(values.contains(&"main"));});}@@ -130,50 +138,28 @@ fn test_complete_base_flag_shows_all_branches() {.unwrap();// Test completion for --base flag (long form)- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args([- "complete",- "wt",- "switch",- "--create",- "new-branch",- "--base",- "",- ])+ let output = temp+ .completion_cmd(&["wt", "switch", "--create", "new-branch", "--base", ""]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- let branches: Vec<&str> = stdout.lines().collect();+ let branches = value_suggestions(&stdout);// Should show all branches as potential baseassert!(branches.iter().any(|b| b.contains("develop")));assert!(branches.iter().any(|b| b.contains("feature/existing")));// Test completion for -b flag (short form)- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args([- "complete",- "wt",- "switch",- "--create",- "new-branch",- "-b",- "",- ])+ let output = temp+ .completion_cmd(&["wt", "switch", "--create", "new-branch", "-b", ""]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- let branches: Vec<&str> = stdout.lines().collect();+ let branches = value_suggestions(&stdout);// Should show all branches as potential base (short form works too)assert!(branches.iter().any(|b| b.contains("develop")));@@ -198,24 +184,14 @@ fn test_complete_base_flag_with_equals() {.unwrap();// Test completion for --base= format (equals sign, no space)- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args([- "complete",- "wt",- "switch",- "--create",- "new-branch",- "--base=",- ])+ let output = temp+ .completion_cmd(&["wt", "switch", "--create", "new-branch", "--base="]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- let branches: Vec<&str> = stdout.lines().collect();+ let branches = value_suggestions(&stdout);// Should show all branches as potential baseassert!(branches.iter().any(|b| b.contains("develop")));@@ -223,36 +199,23 @@ fn test_complete_base_flag_with_equals() {assert!(branches.iter().any(|b| b.contains("main")));// Test completion for --base=m (equals sign with partial value)- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args([- "complete",- "wt",- "switch",- "--create",- "new-branch",- "--base=m",- ])+ let output = temp+ .completion_cmd(&["wt", "switch", "--create", "new-branch", "--base=m"]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- let branches: Vec<&str> = stdout.lines().collect();+ let branches = value_suggestions(&stdout);- // Should only show branches that match the prefix "m"- assert!(branches.iter().any(|b| b == &"main"));- assert!(!branches.iter().any(|b| b.contains("develop")));- assert!(!branches.iter().any(|b| b.contains("feature")));+ // Should show all branches (shell handles prefix filtering)+ assert!(branches.iter().any(|b| b.contains("main")));+ assert!(branches.iter().any(|b| b.contains("develop")));+ assert!(branches.iter().any(|b| b.contains("feature")));// Test completion for -b= format (short form with equals)- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "switch", "--create", "new-branch", "-b="])+ let output = temp+ .completion_cmd(&["wt", "switch", "--create", "new-branch", "-b="]).output().unwrap();@@ -272,17 +235,19 @@ fn test_complete_outside_git_repo() {settings.set_snapshot_path("../snapshots");settings.bind(|| {- let mut cmd = wt_command();- cmd.current_dir(temp.path())- .args(["complete", "wt", "switch", ""]);-- assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0- ----- stdout ------- ----- stderr ------ ");+ let output = wt_completion_command(&["wt", "switch", ""])+ .current_dir(temp.path())+ .output()+ .unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ stdout+ .lines()+ .filter(|line| !line.trim().is_empty())+ .all(|line| line.starts_with('-')),+ "expected only option suggestions outside git repo, got:\n{stdout}"+ );});}@@ -293,18 +258,16 @@ fn test_complete_empty_repo() {settings.set_snapshot_path("../snapshots");settings.bind(|| {- let mut cmd = wt_command();- repo.clean_cli_env(&mut cmd);- cmd.current_dir(repo.root_path())- .args(["complete", "wt", "switch", ""]);-- assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0- ----- stdout ------- ----- stderr ------ ");+ let output = repo.completion_cmd(&["wt", "switch", ""]).output().unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ stdout+ .lines()+ .filter(|line| !line.trim().is_empty())+ .all(|line| line.starts_with('-')),+ "expected only option suggestions in empty repo, got:\n{stdout}"+ );});}@@ -316,18 +279,18 @@ fn test_complete_unknown_command() {settings.set_snapshot_path("../snapshots");settings.bind(|| {- let mut cmd = wt_command();- repo.clean_cli_env(&mut cmd);- cmd.current_dir(repo.root_path())- .args(["complete", "wt", "unknown-command", ""]);-- assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0- ----- stdout ------- ----- stderr ------ ");+ let output = repo+ .completion_cmd(&["wt", "unknown-command", ""])+ .output()+ .unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ let suggestions = value_suggestions(&stdout);+ assert!(+ suggestions.contains(&"init"),+ "should fall back to root completions, got:\n{stdout}"+ );+ assert!(suggestions.contains(&"config"));});}@@ -339,18 +302,19 @@ fn test_complete_beta_commit_no_positionals() {settings.set_snapshot_path("../snapshots");settings.bind(|| {- let mut cmd = wt_command();- repo.clean_cli_env(&mut cmd);- cmd.current_dir(repo.root_path())- .args(["complete", "wt", "beta", "commit", ""]);-- assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0- ----- stdout ------- ----- stderr ------ ");+ let output = repo+ .completion_cmd(&["wt", "beta", "commit", ""])+ .output()+ .unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ stdout+ .lines()+ .filter(|line| !line.trim().is_empty())+ .all(|line| line.starts_with('-')),+ "beta commit should only suggest flags, got:\n{stdout}"+ );});}@@ -362,32 +326,37 @@ fn test_complete_list_command() {settings.set_snapshot_path("../snapshots");settings.bind(|| {- let mut cmd = wt_command();- repo.clean_cli_env(&mut cmd);- cmd.current_dir(repo.root_path())- .args(["complete", "wt", "list", ""]);-- assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0- ----- stdout ------- ----- stderr ------ ");+ let output = repo.completion_cmd(&["wt", "list", ""]).output().unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ stdout+ .lines()+ .filter(|line| !line.trim().is_empty())+ .all(|line| line.starts_with('-')),+ "wt list should only suggest flags, got:\n{stdout}"+ );});}#[test]fn test_init_fish_includes_no_file_flag() {- // Test that fish init includes -f flag to disable file completion+ // Test that fish init wires Clap-based completions into the templatelet mut cmd = wt_command();let output = cmd.arg("init").arg("fish").output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- // Check that completions include -f flag- assert!(stdout.contains("-f -a '(__wt_complete)'"));+ // Ensure we embed the COMPLETE=fish registration snippet+ assert!(+ stdout.contains("COMPLETE=fish $_WORKTRUNK_CMD"),+ "Fish template should call wt with COMPLETE=fish"+ );+ assert!(+ stdout.contains("eval $_wt_completion_script"),+ "Fish template should eval the Clap completion script"+ );}#[test]@@ -414,23 +383,18 @@ fn test_complete_with_partial_prefix() {.output().unwrap();- // Complete with partial prefix - should return only branches starting with "feat"+ // Complete with partial prefix - shell does prefix filtering, we return all brancheslet mut settings = Settings::clone_current();settings.set_snapshot_path("../snapshots");settings.bind(|| {- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- cmd.current_dir(temp.root_path())- .args(["complete", "wt", "switch", "feat"]);- assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0- ----- stdout ------ feature/one- feature/two-- ----- stderr ------ ");+ let output = temp+ .completion_cmd(&["wt", "switch", "feat"])+ .output()+ .unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(stdout.contains("feature/one"));+ assert!(stdout.contains("feature/two"));});}@@ -444,13 +408,7 @@ fn test_complete_switch_shows_all_branches_even_with_worktrees() {temp.add_worktree("hotfix-worktree", "hotfix/bug");// From the main worktree, test completion - should show all branches- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "switch", ""])- .output()- .unwrap();+ let output = temp.completion_cmd(&["wt", "switch", ""]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);@@ -515,13 +473,7 @@ fn test_complete_excludes_remote_branches() {.unwrap();// Test completion- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "switch", ""])- .output()- .unwrap();+ let output = temp.completion_cmd(&["wt", "switch", ""]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);@@ -560,13 +512,7 @@ fn test_complete_merge_shows_branches() {.unwrap();// Test completion for merge (should show ALL branches, including those with worktrees)- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "merge", ""])- .output()- .unwrap();+ let output = temp.completion_cmd(&["wt", "merge", ""]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);@@ -599,21 +545,16 @@ fn test_complete_with_special_characters_in_branch_names() {}// Test completion- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "switch", ""])- .output()- .unwrap();+ let output = temp.completion_cmd(&["wt", "switch", ""]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);+ let values = value_suggestions(&stdout);// All branches should be presentfor branch in &branch_names {assert!(- stdout.contains(branch),+ values.contains(branch),"Branch {} should be in completion output",branch);@@ -642,57 +583,48 @@ fn test_complete_stops_after_branch_provided() {let mut settings = Settings::clone_current();settings.set_snapshot_path("../snapshots");settings.bind(|| {- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- cmd.current_dir(temp.root_path())- .args(["complete", "wt", "switch", "feature/one", ""]);- assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0- ----- stdout ------- ----- stderr ------ ");+ let output = temp+ .completion_cmd(&["wt", "switch", "feature/one", ""])+ .output()+ .unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ only_option_suggestions(&stdout),+ "expected only option suggestions after positional provided, got:\n{stdout}"+ );});- // Test that dev push stops completing after branch is provided+ // Test that beta push stops completing after branch is providedlet mut settings = Settings::clone_current();settings.set_snapshot_path("../snapshots");settings.bind(|| {- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- cmd.current_dir(temp.root_path()).args([- "complete",- "wt",- "dev",- "push",- "feature/one",- "",- ]);- assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0- ----- stdout ------- ----- stderr ------ ");+ let output = temp+ .completion_cmd(&["wt", "beta", "push", "feature/one", ""])+ .output()+ .unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ only_option_suggestions(&stdout),+ "expected only option suggestions after positional provided, got:\n{stdout}"+ );});// Test that merge stops completing after branch is providedlet mut settings = Settings::clone_current();settings.set_snapshot_path("../snapshots");settings.bind(|| {- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- cmd.current_dir(temp.root_path())- .args(["complete", "wt", "merge", "feature/one", ""]);- assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0- ----- stdout ------- ----- stderr ------ ");+ let output = temp+ .completion_cmd(&["wt", "merge", "feature/one", ""])+ .output()+ .unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ only_option_suggestions(&stdout),+ "expected only option suggestions after positional provided, got:\n{stdout}"+ );});}@@ -711,34 +643,32 @@ fn test_complete_switch_with_create_flag_no_completion() {let mut settings = Settings::clone_current();settings.set_snapshot_path("../snapshots");settings.bind(|| {- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- cmd.current_dir(temp.root_path())- .args(["complete", "wt", "switch", "--create", ""]);- assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0- ----- stdout ------- ----- stderr ------ ");+ let output = temp+ .completion_cmd(&["wt", "switch", "--create", ""])+ .output()+ .unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ only_option_suggestions(&stdout),+ "should not suggest branches when --create is present, got:\n{stdout}"+ );});// Test with -c flag (short form)let mut settings = Settings::clone_current();settings.set_snapshot_path("../snapshots");settings.bind(|| {- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- cmd.current_dir(temp.root_path())- .args(["complete", "wt", "switch", "-c", ""]);- assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0- ----- stdout ------- ----- stderr ------ ");+ let output = temp+ .completion_cmd(&["wt", "switch", "-c", ""])+ .output()+ .unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ only_option_suggestions(&stdout),+ "should not suggest branches when -c is present, got:\n{stdout}"+ );});}@@ -755,19 +685,8 @@ fn test_complete_switch_base_flag_after_branch() {.unwrap();// Test completion for --base even after --create and branch name- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args([- "complete",- "wt",- "switch",- "--create",- "new-feature",- "--base",- "",- ])+ let output = temp+ .completion_cmd(&["wt", "switch", "--create", "new-feature", "--base", ""]).output().unwrap();@@ -794,13 +713,7 @@ fn test_complete_remove_shows_branches() {.unwrap();// Test completion for remove (should show ALL branches)- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "remove", ""])- .output()- .unwrap();+ let output = temp.completion_cmd(&["wt", "remove", ""]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);@@ -817,19 +730,15 @@ fn test_complete_dev_run_hook_shows_hook_types() {temp.commit("initial");// Test completion for beta run-hook- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "beta", "run-hook", ""])+ let output = temp+ .completion_cmd(&["wt", "beta", "run-hook", ""]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- let hooks: Vec<&str> = stdout.lines().collect();+ let hooks = value_suggestions(&stdout);- // Should include all hook typesassert!(hooks.contains(&"post-create"), "Missing post-create");assert!(hooks.contains(&"post-start"), "Missing post-start");assert!(hooks.contains(&"pre-commit"), "Missing pre-commit");@@ -844,73 +753,33 @@ fn test_complete_dev_run_hook_with_partial_input() {temp.commit("initial");// Test completion with partial input- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "beta", "run-hook", "po"])+ let output = temp+ .completion_cmd(&["wt", "beta", "run-hook", "po"]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- let hooks: Vec<&str> = stdout.lines().collect();+ let hooks = value_suggestions(&stdout);- // With clap fallback, we filter by prefixassert!(hooks.contains(&"post-create"));assert!(hooks.contains(&"post-start"));assert!(hooks.contains(&"post-merge"));- // Should NOT contain hooks that don't match the prefixassert!(!hooks.contains(&"pre-commit"));assert!(!hooks.contains(&"pre-merge"));}-#[test]-fn test_complete_dev_run_hook_without_trailing_empty() {- let temp = TestRepo::new();- temp.commit("initial");-- // Test completion WITHOUT trailing empty string (what fish actually sends)- // Regression test for bug where "wt beta run-hook<tab>" showed nothing- // but "wt beta run-hook ""<tab>" showed all hooks- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "beta", "run-hook"]) // No trailing ""- .output()- .unwrap();-- assert!(output.status.success());- let stdout = String::from_utf8_lossy(&output.stdout);- let hooks: Vec<&str> = stdout.lines().collect();-- // Should include all hook types even without trailing empty string- assert!(hooks.contains(&"post-create"), "Missing post-create");- assert!(hooks.contains(&"post-start"), "Missing post-start");- assert!(hooks.contains(&"pre-commit"), "Missing pre-commit");- assert!(hooks.contains(&"pre-merge"), "Missing pre-merge");- assert!(hooks.contains(&"post-merge"), "Missing post-merge");- assert_eq!(hooks.len(), 5, "Should have exactly 5 hook types");-}-#[test]fn test_complete_init_shows_shells() {let temp = TestRepo::new();temp.commit("initial");// Test completion for init command with no input- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "init", ""])- .output()- .unwrap();+ let output = temp.completion_cmd(&["wt", "init", ""]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- let shells: Vec<&str> = stdout.lines().collect();+ let shells = value_suggestions(&stdout);// Should show all shell typesassert!(shells.contains(&"bash"));@@ -923,47 +792,17 @@ fn test_complete_init_shows_shells() {assert!(shells.contains(&"xonsh"));}-#[test]-fn test_complete_init_without_trailing_empty() {- let temp = TestRepo::new();- temp.commit("initial");-- // Test completion WITHOUT trailing empty string (what fish actually sends)- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "init"]) // No trailing ""- .output()- .unwrap();-- assert!(output.status.success());- let stdout = String::from_utf8_lossy(&output.stdout);- let shells: Vec<&str> = stdout.lines().collect();-- // Should show all shell types even without trailing empty string- assert!(shells.contains(&"bash"));- assert!(shells.contains(&"fish"));- assert!(shells.contains(&"zsh"));-}-#[test]fn test_complete_init_partial() {let temp = TestRepo::new();temp.commit("initial");// Test completion with partial input "fi"- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "init", "fi"])- .output()- .unwrap();+ let output = temp.completion_cmd(&["wt", "init", "fi"]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- let shells: Vec<&str> = stdout.lines().collect();+ let shells = value_suggestions(&stdout);// With clap fallback, we filter by prefixassert!(shells.contains(&"fish"));@@ -977,17 +816,14 @@ fn test_complete_init_with_source_flag() {temp.commit("initial");// Test completion with --source flag: wt --source init <tab>- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "--source", "init", ""])+ let output = temp+ .completion_cmd(&["wt", "--source", "init", ""]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- let shells: Vec<&str> = stdout.lines().collect();+ let shells = value_suggestions(&stdout);// Should show all shell types, same as without --sourceassert!(shells.contains(&"bash"));@@ -1001,17 +837,14 @@ fn test_complete_config_shell_flag() {temp.commit("initial");// Test completion for config shell --shell flag- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "config", "shell", "--shell", "z"])+ let output = temp+ .completion_cmd(&["wt", "config", "shell", "--shell", "z"]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- let shells: Vec<&str> = stdout.lines().collect();+ let shells = value_suggestions(&stdout);// Should filter by prefixassert!(shells.contains(&"zsh"));@@ -1025,19 +858,14 @@ fn test_complete_config_shell_flag_with_source() {temp.commit("initial");// Test completion for config shell --shell flag with --source- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args([- "complete", "wt", "--source", "config", "shell", "--shell", "",- ])+ let output = temp+ .completion_cmd(&["wt", "--source", "config", "shell", "--shell", ""]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- let shells: Vec<&str> = stdout.lines().collect();+ let shells = value_suggestions(&stdout);// Should show all shell types, same as without --sourceassert!(shells.contains(&"bash"));@@ -1051,11 +879,8 @@ fn test_complete_list_format_flag() {temp.commit("initial");// Test completion for list --format flag- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "list", "--format", ""])+ let output = temp+ .completion_cmd(&["wt", "list", "--format", ""]).output().unwrap();@@ -1064,8 +889,9 @@ fn test_complete_list_format_flag() {// Each line is "name\tdescription" (fish format)// Just check that both format names appear- assert!(stdout.contains("table"));- assert!(stdout.contains("json"));+ let values = value_suggestions(&stdout);+ assert!(values.contains(&"table"));+ assert!(values.contains(&"json"));}#[test]@@ -1081,17 +907,14 @@ fn test_complete_switch_with_execute_flag() {// Test: wt switch --execute "code ." <cursor>// Should complete branches because --execute takes a value- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "switch", "--execute", "code .", ""])+ let output = temp+ .completion_cmd(&["wt", "switch", "--execute", "code .", ""]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- let branches: Vec<&str> = stdout.lines().collect();+ let branches = value_suggestions(&stdout);assert!(branches.iter().any(|b| b.contains("develop")));assert!(branches.iter().any(|b| b.contains("main")));}@@ -1109,17 +932,14 @@ fn test_complete_switch_with_execute_equals_format() {// Test: wt switch --execute="code ." <cursor>// Should complete branches- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "switch", "--execute=code .", ""])+ let output = temp+ .completion_cmd(&["wt", "switch", "--execute=code .", ""]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- let branches: Vec<&str> = stdout.lines().collect();+ let branches = value_suggestions(&stdout);assert!(branches.iter().any(|b| b.contains("feature")));assert!(branches.iter().any(|b| b.contains("main")));}@@ -1137,11 +957,8 @@ fn test_complete_switch_short_cluster_with_value() {// Test: wt switch -xcode <cursor>// -x takes value "code" (fused), should complete branches for positional- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "switch", "-xcode", ""])+ let output = temp+ .completion_cmd(&["wt", "switch", "-xcode", ""]).output().unwrap();@@ -1165,11 +982,8 @@ fn test_complete_switch_with_double_dash_terminator() {// Test: wt switch -- <cursor>// After --, everything is positional, should complete branches- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "switch", "--", ""])+ let output = temp+ .completion_cmd(&["wt", "switch", "--", ""]).output().unwrap();@@ -1193,18 +1007,17 @@ fn test_complete_switch_positional_already_provided() {// Test: wt switch existing <cursor>// Positional already provided, should NOT complete branches- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "switch", "existing", ""])+ let output = temp+ .completion_cmd(&["wt", "switch", "existing", ""]).output().unwrap();assert!(output.status.success());let stdout = String::from_utf8_lossy(&output.stdout);- // Should not suggest branches (stdout should be empty or not contain branches)- assert_eq!(stdout.trim(), "");+ assert!(+ only_option_suggestions(&stdout),+ "expected only option suggestions, got:\n{stdout}"+ );}#[test]@@ -1220,11 +1033,8 @@ fn test_complete_switch_completing_execute_value() {// Test: wt switch --execute <cursor>// Currently typing the value for --execute, should NOT complete branches- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "switch", "--execute", ""])+ let output = temp+ .completion_cmd(&["wt", "switch", "--execute", ""]).output().unwrap();@@ -1247,11 +1057,8 @@ fn test_complete_merge_with_flags() {// Test: wt merge --no-remove --force <cursor>// Should complete branches for positional (boolean flags don't consume arguments)- let mut cmd = wt_command();- temp.clean_cli_env(&mut cmd);- let output = cmd- .current_dir(temp.root_path())- .args(["complete", "wt", "merge", "--no-remove", "--force", ""])+ let output = temp+ .completion_cmd(&["wt", "merge", "--no-remove", "--force", ""]).output().unwrap();diff --git a/tests/integration_tests/internal_flag.rs b/tests/integration_tests/internal_flag.rsindex 259dc5438..5f56c15d6 100644--- a/tests/integration_tests/internal_flag.rs+++ b/tests/integration_tests/internal_flag.rs@@ -75,30 +75,3 @@ fn test_config_list_with_internal_flag() {assert_cmd_snapshot!(cmd);});}--/// Test that `complete` command works with --internal flag-///-/// Complete doesn't emit directives, but should work fine with --internal.-/// This verifies that completion output is properly handled in directive mode.-#[test]-fn test_complete_with_internal_flag() {- let mut repo = TestRepo::new();- repo.commit("Initial commit");- // Add a worktree so we have branch names to complete- repo.add_worktree("feature", "feature");-- let mut settings = Settings::clone_current();- settings.set_snapshot_path("../snapshots");-- settings.bind(|| {- let mut cmd = wt_command();- repo.clean_cli_env(&mut cmd);- cmd.arg("--internal")- .arg("complete")- .arg("wt")- .arg("switch")- .current_dir(repo.root_path());-- assert_cmd_snapshot!(cmd);- });-}diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rsindex e64e6bf56..552d0aa9e 100644--- a/tests/integration_tests/shell_wrapper.rs+++ b/tests/integration_tests/shell_wrapper.rs@@ -41,8 +41,16 @@ use std::sync::LazyLock;/// Regex for normalizing temporary directory paths in test snapshotsstatic TMPDIR_REGEX: LazyLock<regex::Regex> = LazyLock::new(|| {- regex::Regex::new(r"(/private/var/folders/[^/]+/[^/]+/T/\.tmp[^/]+|/tmp/\.tmp[^/]+)")- .expect("Invalid tmpdir regex pattern")+ regex::Regex::new(+ r#"(/private/var/folders/[^/]+/[^/]+/T/\.tmp[^\s/'"]+|/tmp/\.(?:tmp|psub)[^\s/'"]+)"#,+ )+ .expect("Invalid tmpdir regex pattern")+});++/// Regex that collapses repeated TMPDIR placeholders (caused by nested mktemp paths)+/// so `[TMPDIR][TMPDIR]/foo` becomes `[TMPDIR]/foo` and `[TMPDIR]/[TMPDIR]` becomes `[TMPDIR]`+static TMPDIR_PLACEHOLDER_COLLAPSE_REGEX: LazyLock<regex::Regex> = LazyLock::new(|| {+ regex::Regex::new(r"\[TMPDIR](?:/?\[TMPDIR])+").expect("Invalid TMPDIR placeholder regex")});/// Regex for normalizing workspace paths (dynamically built from CARGO_MANIFEST_DIR)@@ -96,10 +104,14 @@ impl ShellOutput {// Normalize commit hashes (7-character hex strings)let hash_normalized = COMMIT_HASH_REGEX.replace_all(&workspace_normalized, "[HASH]");+ // Collapse duplicate TMPDIR placeholders that can appear with nested mktemp paths.+ let tmpdir_collapsed =+ TMPDIR_PLACEHOLDER_COLLAPSE_REGEX.replace_all(&hash_normalized, "[TMPDIR]");+// Then normalize ANSI codes: remove redundant leading reset codes// This handles differences between macOS and Linux PTY ANSI generation- let has_trailing_newline = hash_normalized.ends_with('\n');- let mut result = hash_normalized+ let has_trailing_newline = tmpdir_collapsed.ends_with('\n');+ let mut result = tmpdir_collapsed.lines().map(|line| {// Strip leading \x1b[0m reset codes (may appear as ESC[0m in the output)@@ -1330,21 +1342,25 @@ approved-commands = ["echo 'fish background task'"]];let (combined, exit_code) = exec_in_pty(shell, &final_script, &worktrunk_source, &env_vars);+ let output = ShellOutput {+ combined,+ exit_code,+ };// Shell-agnostic assertions- assert_ne!(exit_code, 0, "{}: Command should fail", shell);+ assert_ne!(output.exit_code, 0, "{}: Command should fail", shell);// CRITICAL: Should see wt's actual error message about unrecognized subcommandassert!(- combined.contains("unrecognized subcommand"),+ output.combined.contains("unrecognized subcommand"),"{}: Should show actual wt error message 'unrecognized subcommand'.\nOutput:\n{}",shell,- combined+ output.combined);// CRITICAL: Should NOT see the old generic wrapper error messageassert!(- !combined.contains("Error: cargo build failed"),+ !output.combined.contains("Error: cargo build failed"),"{}: Should not contain old generic error message",shell);@@ -1352,7 +1368,7 @@ approved-commands = ["echo 'fish background task'"]// Consolidated snapshot - output should be identical across shells// (wt error messages are deterministic)insta::allow_duplicates! {- assert_snapshot!("source_flag_error_passthrough", combined);+ assert_snapshot!("source_flag_error_passthrough", output.normalized());}}}diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__source_flag_error_passthrough.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__source_flag_error_passthrough.snapindex 90177f437..b6e4eda0d 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__source_flag_error_passthrough.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__source_flag_error_passthrough.snap@@ -1,6 +1,6 @@---source: tests/integration_tests/shell_wrapper.rs-expression: combined+expression: output.normalized()---[1m[31merror:[0m unrecognized subcommand '[33mfoo[0m'diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snapindex 90f22dfbe..3f924f4ee 100644--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap@@ -1,5 +1,6 @@---source: tests/integration_tests/init.rs+assertion_line: 23info:program: wtargs:@@ -12,11 +13,10 @@ info:GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"GIT_CONFIG_GLOBAL: /dev/nullGIT_CONFIG_SYSTEM: /dev/null- GIT_EDITOR: ""LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpcSRq4c/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmps2V6eB/test-config.toml---success: trueexit_code: 0@@ -132,17 +132,10 @@ wt_exec() {return $result}- # Dynamic completion function- _wt_complete() {- local cur="${COMP_WORDS[COMP_CWORD]}"-- # Call wt complete with current command line- local completions=$(command "$_WORKTRUNK_CMD" complete "${COMP_WORDS[@]}" 2>/dev/null)- COMPREPLY=($(compgen -W "$completions" -- "$cur"))- }-- # Register dynamic completion- complete -F _wt_complete wt+ # Register Clap-based completions (auto-updates after wt upgrades)+ if completion_script=$(COMPLETE=bash "$_WORKTRUNK_CMD" 2>/dev/null); then+ eval "$completion_script"+ fifi# Static completions (commands and flags)@@ -167,9 +160,6 @@ _wt() {wt,beta)cmd="wt__beta";;- wt,complete)- cmd="wt__complete"- ;;wt,config)cmd="wt__config";;@@ -231,7 +221,7 @@ _wt() {case "${cmd}" inwt)- opts="-v -h -V --verbose --help --version init config beta list switch remove merge complete"+ opts="-v -h -V --verbose --help --version init config beta list switch remove merge"if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; thenCOMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )return 0@@ -370,20 +360,6 @@ _wt() {COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )return 0;;- wt__complete)- opts="-v -h --verbose --help [ARGS]..."- if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then- COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )- return 0- fi- case "${prev}" in- *)- COMPREPLY=()- ;;- esac- COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )- return 0- ;;wt__config)opts="-v -h --verbose --help init list refresh-cache shell"if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; thendiff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snapindex bf179fe7d..3207879db 100644--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpgUNDX9/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp5Ozdm0/test-config.toml---success: trueexit_code: 0@@ -149,34 +149,11 @@ if type -q wt; or set -q WORKTRUNK_BINreturn $resultend- # Dynamic completion function- function __wt_complete- # Call wt complete with current command line- set -l cmd (commandline -opc)- command $_WORKTRUNK_CMD complete $cmd 2>/dev/null+ # Register Clap-based completions (auto-updates after wt upgrades)+ set -l _wt_completion_script (COMPLETE=fish $_WORKTRUNK_CMD 2>/dev/null | string collect)+ if test -n "$_wt_completion_script"+ eval $_wt_completion_scriptend-- # Register dynamic completions- complete -c wt -n '__fish_seen_subcommand_from init' -f -a '(__wt_complete)' -d 'Shell to generate code for'- complete -c wt -n '__fish_seen_subcommand_from config' -f- complete -c wt -n '__fish_seen_subcommand_from config; and __fish_seen_subcommand_from init' -f- complete -c wt -n '__fish_seen_subcommand_from config; and __fish_seen_subcommand_from list' -f- complete -c wt -n '__fish_seen_subcommand_from config; and __fish_seen_subcommand_from refresh-cache' -f- complete -c wt -n '__fish_seen_subcommand_from config; and __fish_seen_subcommand_from shell' -f- complete -c wt -n '__fish_seen_subcommand_from beta' -f- complete -c wt -n '__fish_seen_subcommand_from beta; and __fish_seen_subcommand_from run-hook' -f -a '(__wt_complete)' -d 'Hook type to run'- complete -c wt -n '__fish_seen_subcommand_from beta; and __fish_seen_subcommand_from commit' -f- complete -c wt -n '__fish_seen_subcommand_from beta; and __fish_seen_subcommand_from squash' -f -a '(__wt_complete)' -d 'Target branch to squash against (defaults to default branch)'- complete -c wt -n '__fish_seen_subcommand_from beta; and __fish_seen_subcommand_from push' -f -a '(__wt_complete)' -d 'Target branch (defaults to default branch)'- complete -c wt -n '__fish_seen_subcommand_from beta; and __fish_seen_subcommand_from rebase' -f -a '(__wt_complete)' -d 'Target branch to rebase onto (defaults to default branch)'- complete -c wt -n '__fish_seen_subcommand_from beta; and __fish_seen_subcommand_from ask-approvals' -f- complete -c wt -n '__fish_seen_subcommand_from beta; and __fish_seen_subcommand_from clear-approvals' -f- complete -c wt -n '__fish_seen_subcommand_from beta; and __fish_seen_subcommand_from select' -f- complete -c wt -n '__fish_seen_subcommand_from list' -f- complete -c wt -n '__fish_seen_subcommand_from switch' -f -a '(__wt_complete)' -d 'Branch name, worktree path, '@' for current HEAD, or '-' for previous branch'- complete -c wt -n '__fish_seen_subcommand_from remove' -f -a '(__wt_complete)' -d 'Worktree names or branches to remove (use '@' for current, defaults to current if none specified)'- complete -c wt -n '__fish_seen_subcommand_from merge' -f -a '(__wt_complete)' -d 'Target branch to merge into (defaults to default branch)'- complete -c wt -n '__fish_seen_subcommand_from complete' -f -a '(__wt_complete)' -d 'Arguments to complete'end# Static completions (commands and flags)@@ -302,7 +279,5 @@ complete -c wt -n "__fish_wt_using_subcommand merge" -s f -l force -d 'Auto-apprcomplete -c wt -n "__fish_wt_using_subcommand merge" -l tracked-only -d 'Only stage tracked files (git add -u) instead of all files (git add -A)'complete -c wt -n "__fish_wt_using_subcommand merge" -s v -l verbose -d 'Enable verbose output (show git commands and debug info)'complete -c wt -n "__fish_wt_using_subcommand merge" -s h -l help -d 'Print help (see more with \'--help\')'-complete -c wt -n "__fish_wt_using_subcommand complete" -s v -l verbose -d 'Enable verbose output (show git commands and debug info)'-complete -c wt -n "__fish_wt_using_subcommand complete" -s h -l help -d 'Print help'----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snapindex 05d2222d8..2fee3fab7 100644--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap@@ -1,5 +1,6 @@---source: tests/integration_tests/init.rs+assertion_line: 23info:program: wtargs:@@ -12,11 +13,10 @@ info:GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"GIT_CONFIG_GLOBAL: /dev/nullGIT_CONFIG_SYSTEM: /dev/null- GIT_EDITOR: ""LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpCLX2oz/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpQyAnKf/test-config.toml---success: trueexit_code: 0@@ -132,25 +132,11 @@ wt_exec() {return $result}- # Dynamic completion function for zsh- _wt_complete() {- local -a completions- local -a words-- # Get current command line as array- words=("${(@)words}")-- # Call wt complete with current command line- completions=(${(f)"$(command "$_WORKTRUNK_CMD" complete "${words[@]}" 2>/dev/null)"})-- # Add completions- compadd -a completions- }-- # Register dynamic completion (only if compdef is available)- # In non-interactive shells or test environments, the completion system may not be loaded+ # Register Clap-based completions (auto-updates after wt upgrades)if (( $+functions[compdef] )); then- compdef _wt_complete wt+ local completion_script+ completion_script=$(COMPLETE=zsh "$_WORKTRUNK_CMD" 2>/dev/null)+ eval "$completion_script"fifi@@ -410,15 +396,6 @@ _arguments "${_arguments_options[@]}" : \'--help[Print help (see more with '\''--help'\'')]' \'::target -- Target branch to merge into (defaults to default branch):_default' \&& ret=0-;;-(complete)-_arguments "${_arguments_options[@]}" : \-'-v[Enable verbose output (show git commands and debug info)]' \-'--verbose[Enable verbose output (show git commands and debug info)]' \-'-h[Print help]' \-'--help[Print help]' \-'*::args -- Arguments to complete:_default' \-&& ret=0;;esac;;@@ -435,7 +412,6 @@ _wt_commands() {'switch:Switch to a worktree' \'remove:Finish current worktree, returning to primary if current' \'merge:Merge worktree into target branch' \-'complete:Internal completion helper (hidden)' \)_describe -t commands 'wt commands' commands "$@"}@@ -493,11 +469,6 @@ _wt__beta__squash_commands() {local commands; commands=()_describe -t commands 'wt beta squash commands' commands "$@"}-(( $+functions[_wt__complete_commands] )) ||-_wt__complete_commands() {- local commands; commands=()- _describe -t commands 'wt complete commands' commands "$@"-}(( $+functions[_wt__config_commands] )) ||_wt__config_commands() {local commands; commands=(diff --git a/tests/snapshots/integration__integration_tests__internal_flag__complete_with_internal_flag.snap b/tests/snapshots/integration__integration_tests__internal_flag__complete_with_internal_flag.snapdeleted file mode 100644index e80b46e5c..000000000--- a/tests/snapshots/integration__integration_tests__internal_flag__complete_with_internal_flag.snap+++ /dev/null@@ -1,29 +0,0 @@-----source: tests/integration_tests/internal_flag.rs-info:- program: wt- args:- - "--internal"- - complete- - wt- - switch- env:- CLICOLOR_FORCE: "1"- COLUMNS: "150"- GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"- GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"- GIT_CONFIG_GLOBAL: /dev/null- GIT_CONFIG_SYSTEM: /dev/null- GIT_EDITOR: ""- LANG: C- LC_ALL: C- SOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpsjIist/test-config.toml-----success: true-exit_code: 0------ stdout ------feature-main------- stderr -----