Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Use parsed command context for hook-name completion (#4560)
Maximilian Roos836ec72c4ffe
diff --git a/src/completion.rs b/src/completion.rsindex 2ec04a612..5fc2911c4 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -61,7 +61,6 @@ pub(crate) fn maybe_handle_env_completion() -> bool {worktrunk::config::suppress_warnings();let mut args: Vec<OsString> = std::env::args_os().collect();- CONTEXT.with(|ctx| *ctx.borrow_mut() = Some(CompletionContext { args: args.clone() }));// Remove the binary name and find the `--` separatorargs.remove(0);@@ -106,6 +105,12 @@ pub(crate) fn maybe_handle_env_completion() -> bool {// a config filename or directory. Reuse runtime parsing so attached flag// values and globals after built-in subcommands follow the same rules.let globals = crate::parse_early_globals(args.iter().take(index).cloned());+ CONTEXT.with(|ctx| {+ *ctx.borrow_mut() = Some(CompletionContext {+ args: args.clone(),+ hook_type: globals.hook_type,+ });+ });let current_dir = globals.directory.clone().or(current_dir);crate::apply_global_options(globals.directory, globals.config, globals.config_overrides);@@ -346,12 +351,8 @@ impl ValueCompleter for HookCommandCompleter {// bash-specific prefix filter in maybe_handle_env_completion() handles bash.// Get the hook type from the command line context- let hook_type = CONTEXT.with(|ctx| ctx.borrow().as_ref().and_then(detect_hook_type));-- let Some(hook_type_str) = hook_type else {- return Vec::new();- };- let Ok(hook_type) = hook_type_str.parse::<HookType>() else {+ let hook_type = CONTEXT.with(|ctx| ctx.borrow().as_ref().and_then(|ctx| ctx.hook_type));+ let Some(hook_type) = hook_type else {return Vec::new();};@@ -480,6 +481,7 @@ fn suppress_switch_branch_completion() -> bool {struct CompletionContext {args: Vec<OsString>,+ hook_type: Option<HookType>,}impl CompletionContext {@@ -490,33 +492,6 @@ impl CompletionContext {}}-/// Identify which hook type the user is completing a command name for by-/// scanning the command line for a hook-type argument. Returns the canonical-/// name, mapping the silent `pre-create`/`post-create` aliases to-/// `pre-start`/`post-start`.-///-/// The candidate list is derived from [`cli::HOOK_TYPE_NAMES`] rather than a-/// local copy, so a newly added hook type completes its command names without a-/// second edit here. `contains` is an exact match (not a substring test), so-/// iterating the full list has no shadowing hazard between names like-/// `pre-remove` and `post-remove`. `test_detect_hook_type_covers_all_names`-/// pins the coverage.-fn detect_hook_type(ctx: &CompletionContext) -> Option<&'static str> {- for &hook in cli::HOOK_TYPE_NAMES {- if ctx.contains(hook) {- return Some(hook);- }- }- // Silent aliases still complete, mapped to the canonical name.- if ctx.contains("pre-create") {- return Some("pre-start");- }- if ctx.contains("post-create") {- return Some("post-start");- }- None-}-// 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@@ -1021,50 +996,22 @@ fn hide_non_positional_options_for_completion(cmd: Command) -> Command {mod tests {use super::*;- /// Every canonical hook type must be detected so `wt hook <type> <Tab>`- /// completes its configured command names. A hook type listed in- /// HOOK_TYPE_NAMES but missing from `detect_hook_type`'s scan would- /// silently return no completions — this previously dropped `pre-switch`,- /// `post-switch`, and `post-remove`.+ /// Clap supplies canonical hook names, including silent aliases, without+ /// confusing option values or named filters with the selected hook type.#[test]- fn test_detect_hook_type_covers_all_names() {+ fn test_parsed_hook_type() {for &name in cli::HOOK_TYPE_NAMES {- let ctx = CompletionContext {- args: vec!["hook".into(), name.into()],- };- assert_eq!(- detect_hook_type(&ctx),- Some(name),- "hook type `{name}` should be detected for completion"- );- // The detected name must round-trip through HookType parsing,- // mirroring complete()'s downstream `parse::<HookType>()`.- assert!(- name.parse::<HookType>().is_ok(),- "hook type `{name}` should parse"- );+ let args = ["wt", "--config", "pre-switch", "hook", name, "post-start"];+ let globals = crate::parse_early_globals(args.into_iter().map(Into::into));+ assert_eq!(globals.hook_type, Some(name.parse().unwrap()), "{name}");}- }-- /// The silent `pre-create`/`post-create` aliases map to their canonical- /// names so they still complete command names.- #[test]- fn test_detect_hook_type_maps_silent_aliases() {for (alias, canonical) in [("pre-create", "pre-start"), ("post-create", "post-start")] {- let ctx = CompletionContext {- args: vec!["hook".into(), alias.into()],- };- assert_eq!(detect_hook_type(&ctx), Some(canonical));+ let args = ["wt", "hook", alias];+ let globals = crate::parse_early_globals(args.into_iter().map(Into::into));+ assert_eq!(globals.hook_type, Some(canonical.parse().unwrap()));}- }-- /// No hook-type argument on the line means no hook-command completion.- #[test]- fn test_detect_hook_type_none_without_hook() {- let ctx = CompletionContext {- args: vec!["switch".into(), "main".into()],- };- assert_eq!(detect_hook_type(&ctx), None);+ let globals = crate::parse_early_globals(["wt", "switch", "pre-switch"].map(Into::into));+ assert_eq!(globals.hook_type, None);}#[test]diff --git a/src/main.rs b/src/main.rsindex f6af8395e..b3593ba22 100644--- a/src/main.rs+++ b/src/main.rs@@ -836,6 +836,8 @@ struct EarlyGlobals {subcommand: Option<String>,/// Offset of an external command after clap has consumed global options.external_subcommand_index: Option<usize>,+ /// The parsed hook subcommand, excluding option values and command filters.+ hook_type: Option<worktrunk::git::HookType>,}/// Parse global options (`-C`, `--config`, `--config-set`), name the command,@@ -891,6 +893,10 @@ fn parse_early_globals(args: impl IntoIterator<Item = std::ffi::OsString>) -> Eaalias_help_context,subcommand: matches.subcommand_name().map(str::to_owned),external_subcommand_index,+ hook_type: matches+ .subcommand_matches("hook")+ .and_then(|hook| hook.subcommand_name())+ .and_then(|name| name.parse().ok()),}}diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rsindex 31be2b65a..6052876df 100644--- a/tests/integration_tests/completion.rs+++ b/tests/integration_tests/completion.rs@@ -2658,3 +2658,39 @@ fn test_completion_registration_falls_back_when_binary_name_is_invalid() {"an invalid binary name must fall back to `wt`, got:\n{stdout}");}++/// Hook types in option values, filters, or words after the cursor do not+/// change the hook whose command names are completed.+#[rstest]+fn test_hook_completion_uses_parsed_subcommand(repo: TestRepo) {+ let config = r#"+[pre-merge]+expected = "echo expected"+[pre-switch]+wrong-hook = "echo wrong"+"#;+ repo.write_test_config(config);+ std::fs::write(repo.root_path().join("pre-switch"), config).unwrap();++ for (args, index) in [+ (+ vec!["wt", "--config", "pre-switch", "hook", "pre-merge", ""],+ 5,+ ),+ (vec!["wt", "hook", "pre-merge", "pre-switch", ""], 4),+ (vec!["wt", "hook", "pre-merge", "", "pre-switch"], 3),+ ] {+ let output = repo+ .completion_cmd(&args)+ .env("_CLAP_COMPLETE_INDEX", index.to_string())+ .output()+ .unwrap();+ assert!(output.status.success(), "{args:?}: {output:?}");+ let stdout = String::from_utf8(output.stdout).unwrap();+ assert_eq!(+ value_suggestions(&stdout),+ ["expected"],+ "{args:?}: {stdout}"+ );+ }+}