Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Use the requested repository and config for completion (#4551)
Maximilian Roos6c6691b8b507
diff --git a/src/completion.rs b/src/completion.rsindex f05089645..2ec04a612 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -60,18 +60,6 @@ pub(crate) fn maybe_handle_env_completion() -> bool {// warnings for the duration of this process.worktrunk::config::suppress_warnings();- // 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);- }-let mut args: Vec<OsString> = std::env::args_os().collect();CONTEXT.with(|ctx| *ctx.borrow_mut() = Some(CompletionContext { args: args.clone() }));@@ -106,6 +94,33 @@ pub(crate) fn maybe_handle_env_completion() -> bool {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());+ 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@@ -125,20 +140,25 @@ pub(crate) fn maybe_handle_env_completion() -> bool {// If the subcommand word matches a custom-subcommand binary, forward the// completion request to it (e.g., `wt sync --<tab>` → `wt-sync --<tab>`).- // args[0] is the binary name ("wt"), args[1] is the subcommand ("sync").- if args.len() >= 3 {- let subcommand = args[1].to_string_lossy();- // Built-ins and configured aliases both take precedence over PATH- // binaries at runtime, so completions must agree.+ // 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() && which::which(&binary).is_ok() {- // Forward args[1..] to the custom binary- if let Some(forwarded) = forward_completion_to_custom(&binary, &args[1..], &shell_name)- {- let _ = std::io::stdout().write_all(forwarded.as_bytes());- CONTEXT.with(|ctx| ctx.borrow_mut().take());- return true;- }+ 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;}}@@ -148,14 +168,6 @@ pub(crate) fn maybe_handle_env_completion() -> bool {let mut cmd = hide_non_positional_options_for_completion(cmd);cmd.build();- // 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);-// 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@@ -807,8 +819,14 @@ fn truncate_template(template: &str) -> &str {////// 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) -> Option<String> {- try_forward_completion_to_custom(binary, args, shell)+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()}@@ -821,18 +839,26 @@ 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..]);- // Adjust the completion index: subtract 1 since we removed the subcommand name+ // 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(1));-- let mut cmd = std::process::Command::new(binary);+ .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);@@ -1263,6 +1289,8 @@ mod tests {"/nonexistent/binary/xxxxxxxx_wt_test",&[OsString::from("test")],OsStr::new("bash"),+ 1,+ None,);assert!(result.is_none());}@@ -1286,7 +1314,7 @@ mod tests {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) {+ match try_forward_completion_to_custom(binary, args, shell, 1, None) {Err(e) if e.kind() == ErrorKind::ExecutableFileBusy => false,other => {result = Some(other);diff --git a/src/main.rs b/src/main.rsindex 6f0fefb7c..f6af8395e 100644--- a/src/main.rs+++ b/src/main.rs@@ -783,7 +783,8 @@ fn parse_cli() -> Cli {config_overrides,alias_help_context,subcommand,- } = parse_early_globals();+ ..+ } = parse_early_globals(std::env::args_os());apply_global_options(directory, config, config_overrides);// Handle --help with pager before clap processes it.@@ -833,6 +834,8 @@ struct EarlyGlobals {/// arrives, through the `external_subcommand` arm that carries user/// aliases, so those entry points can name it back in their own errors.subcommand: Option<String>,+ /// Offset of an external command after clap has consumed global options.+ external_subcommand_index: Option<usize>,}/// Parse global options (`-C`, `--config`, `--config-set`), name the command,@@ -849,13 +852,23 @@ struct EarlyGlobals {/// Using `cli::build_command()` rather than a hand-rolled mini-command keeps/// the global-flag definitions in one place (the derive on `Cli`), so renaming/// `-C` or adding a value-taking global doesn't silently desync this path.-fn parse_early_globals() -> EarlyGlobals {- let cmd = cli::build_command()+fn parse_early_globals(args: impl IntoIterator<Item = std::ffi::OsString>) -> EarlyGlobals {+ let args: Vec<_> = args.into_iter().collect();+ let mut cmd = cli::build_command().ignore_errors(true).disable_help_flag(true);- let Ok(matches) = cmd.try_get_matches_from(std::env::args_os()) else {+ let Ok(matches) = cmd.try_get_matches_from_mut(&args) else {return EarlyGlobals::default();};+ let external_subcommand_index = matches.subcommand().and_then(|(name, sub)| {+ if cmd.find_subcommand(name).is_some() {+ return None;+ }+ // Clap leaves every word after an external command unparsed, so its+ // raw tail locates the name without scanning global flags ourselves.+ let tail_len = sub.get_raw("").map_or(0, |args| args.len());+ args.len().checked_sub(tail_len + 1)+ });let directory = matches.get_one::<std::path::PathBuf>("directory").cloned();let config = matches.get_one::<std::path::PathBuf>("config").cloned();let config_overrides = matches@@ -877,6 +890,7 @@ fn parse_early_globals() -> EarlyGlobals {config_overrides,alias_help_context,subcommand: matches.subcommand_name().map(str::to_owned),+ external_subcommand_index,}}diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rsindex ede6b8ec5..31be2b65a 100644--- a/tests/integration_tests/completion.rs+++ b/tests/integration_tests/completion.rs@@ -1518,6 +1518,94 @@ fn test_complete_single_dash_shows_both_short_and_long_flags(repo: TestRepo) {}}+/// A completed -C option selects the repository used by branch completion.+#[rstest]+fn test_completion_respects_directory_option(repo: TestRepo) {+ let other = TestRepo::with_initial_commit();+ other.create_branch("only-in-selected-repo");+ repo.create_branch("only-in-original-repo");+ let path = other.root_path().to_str().unwrap();+ for args in [+ vec!["wt", "-C", path, "switch", ""],+ vec!["wt", "switch", "-C", path, ""],+ ] {+ let output = repo+ .completion_cmd(&args)+ .env("WORKTRUNK_VERBOSE", "2")+ .output()+ .unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8(output.stdout).unwrap();+ assert!(stdout.contains("only-in-selected-repo"), "{stdout}");+ assert!(!stdout.contains("only-in-original-repo"), "{stdout}");+ assert!(other.root_path().join(".git/wt/logs/trace.log").exists());+ assert!(!repo.root_path().join(".git/wt/logs/trace.log").exists());+ }+}++/// Relative path values use the same selected cwd as the eventual command.+#[rstest]+fn test_completion_respects_directory_for_paths(repo: TestRepo) {+ let other = TestRepo::with_initial_commit();+ std::fs::create_dir(other.root_path().join("selected-directory")).unwrap();+ std::fs::create_dir(repo.root_path().join("original-directory")).unwrap();+ let output = repo+ .completion_cmd(&[+ "wt",+ "-C",+ other.root_path().to_str().unwrap(),+ "switch",+ "feature",+ "--path",+ "",+ ])+ .output()+ .unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8(output.stdout).unwrap();+ assert!(stdout.contains("selected-directory"), "{stdout}");+ assert!(!stdout.contains("original-directory"), "{stdout}");+}++/// Completion uses explicit config files and inline overrides, while a value+/// still being edited at the cursor does not replace the active config.+#[rstest]+fn test_completion_respects_config_options(repo: TestRepo) {+ repo.write_test_config("[aliases]\noriginal-alias = 'echo original'\n");+ let config_dir = crate::common::test_tempdir();+ let config = config_dir.path().join("config.toml");+ std::fs::write(&config, "[aliases]\nselected-alias = 'echo selected'\n").unwrap();+ let path = config.to_str().unwrap();+ let attached = format!("--config={path}");+ for args in [+ vec!["wt", "--config", path, ""],+ vec!["wt", &attached, ""],+ vec![+ "wt",+ "--config-set",+ "aliases.selected-alias='echo inline'",+ "",+ ],+ ] {+ let output = repo.completion_cmd(&args).output().unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8(output.stdout).unwrap();+ assert!(stdout.contains("selected-alias"), "{stdout}");+ }++ // The shell reports a cursor in the middle of an existing command line.+ // Its later --config words must not affect the alias candidates here.+ let output = repo+ .completion_cmd(&["wt", "", "--config", path])+ .env("_CLAP_COMPLETE_INDEX", "1")+ .output()+ .unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8(output.stdout).unwrap();+ assert!(stdout.contains("original-alias"), "{stdout}");+ assert!(!stdout.contains("selected-alias"), "{stdout}");+}+/// `wt config alias show <TAB>` and `wt config alias dry-run <TAB>` complete/// with the merged user + project alias name set.#[rstest]@@ -2223,6 +2311,64 @@ fn test_complete_custom_subcommand_listed(repo: TestRepo) {);}+/// Global options belong to wt; the external completer receives its own argv,+/// cursor position, and the selected working directory.+#[cfg(unix)]+#[rstest]+fn test_complete_custom_subcommand_after_globals(repo: TestRepo) {+ use std::os::unix::fs::PermissionsExt;++ let other = TestRepo::with_initial_commit();+ let relative_bin = std::path::Path::new("completion-bin");+ let ext_dir = repo.root_path().join(relative_bin);+ std::fs::create_dir(&ext_dir).unwrap();+ let other_bin = other.root_path().join(relative_bin);+ std::fs::create_dir(&other_bin).unwrap();+ let wrong_script = other_bin.join("wt-testext");+ std::fs::write(&wrong_script, "#!/bin/sh\nprintf wrong-executable\n").unwrap();+ std::fs::set_permissions(&wrong_script, std::fs::Permissions::from_mode(0o755)).unwrap();+ let script = ext_dir.join("wt-testext");+ std::fs::write(+ &script,+ r#"#!/bin/sh+printf 'index:%s\n' "$_CLAP_COMPLETE_INDEX"+printf 'arg:%s\n' "$@"+printf 'cwd:%s\n' "$PWD"+"#,+ )+ .unwrap();+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();+ let args = [+ "wt",+ "-C",+ other.root_path().to_str().unwrap(),+ "testext",+ "value",+ "--",+ ];+ let mut cmd = repo.completion_cmd(&args);+ prepend_path(&mut cmd, relative_bin);+ let output = cmd.output().unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8(output.stdout).unwrap();+ assert_eq!(+ stdout,+ format!(+ "index:2\narg:--\narg:wt-testext\narg:value\narg:--\ncwd:{}\n",+ other.root_path().display()+ )+ );++ // With the cursor back on the command name, offer wt command names.+ // Existing arguments to its right must not trigger external completion.+ let mut cmd = repo.completion_cmd(&args);+ prepend_path(&mut cmd, relative_bin);+ let output = cmd.env("_CLAP_COMPLETE_INDEX", "3").output().unwrap();+ let stdout = String::from_utf8(output.stdout).unwrap();+ assert!(stdout.contains("testext"), "{stdout}");+ assert!(!stdout.contains("index:"), "{stdout}");+}+/// Completion for a custom subcommand's flags forwards to the `wt-*` binary.#[cfg(unix)]#[rstest]@@ -2275,20 +2421,29 @@ printf '%s\n%s\n%s' '--custom-flag' '--another' "retired:${WORKTRUNK_DIRECTIVE_F}/// Alias completions must win over an executable with the same name, just-/// like dispatch. The losing executable must not run even on a Tab press.+/// like dispatch, including aliases from the repository selected by -C.+/// The losing executable must not run even on a Tab press.#[cfg(unix)]#[rstest]-#[case(false)]-#[case(true)]-fn test_complete_alias_shadows_custom_binary(repo: TestRepo, #[case] project: bool) {+#[case(false, false)]+#[case(true, false)]+#[case(false, true)]+#[case(true, true)]+fn test_complete_alias_shadows_custom_binary(+ repo: TestRepo,+ #[case] project: bool,+ #[case] select_other: bool,+) {use std::os::unix::fs::PermissionsExt;+ let other = TestRepo::with_initial_commit();+ let selected = if select_other { &other } else { &repo };let config = r#"[aliases]co = "wt switch {{ args }}""#;if project {- repo.write_project_config(config);+ selected.write_project_config(config);} else {repo.write_test_config(config);}@@ -2305,7 +2460,18 @@ printf -- '--external-flag\n'.unwrap();std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();- let mut cmd = repo.completion_cmd(&["wt", "co", "--"]);+ let args = if select_other {+ vec![+ "wt",+ "-C",+ selected.root_path().to_str().unwrap(),+ "co",+ "--",+ ]+ } else {+ vec!["wt", "co", "--"]+ };+ let mut cmd = repo.completion_cmd(&args);prepend_path(&mut cmd, ext_dir.path());cmd.env("WORKTRUNK_TEST_COMPLETION_MARKER", &marker);let output = cmd.output().unwrap();