diff --git a/crates/vp_global_cli/src/main.rs b/crates/vp_global_cli/src/main.rs index 00a3a021b5..1a5c4ea444 100644 --- a/crates/vp_global_cli/src/main.rs +++ b/crates/vp_global_cli/src/main.rs @@ -86,6 +86,80 @@ pub(crate) fn apply_chdir( Ok(target) } +/// Handle a `VP_COMPLETE` shell completion request. +/// +/// Mirrors `CompleteEnv::complete()`, but consumes a leading `-C ` from +/// the words being completed first. The shell glue invokes the completer as +/// `vp -- `, which hides `-C` from the pre-parse in `run` +/// and would leave cwd-sensitive completers (run tasks) in the invocation +/// directory. +/// +/// Returns the exit code when the request was handled (script registration or +/// candidate completion), or `None` when completion is disabled +/// (`VP_COMPLETE=` / `VP_COMPLETE=0`) and the normal command path should run. +fn complete_request(args: &[String]) -> Option { + env::var_os("VP_COMPLETE")?; + let mut args: Vec = args.to_vec(); + if let Some(separator) = args.iter().position(|arg| arg == "--") { + let words = &mut args[separator + 1..]; + if let Some(dir) = qualify_completion_chdir(words, completion_word_index(words)) + && let Ok(current) = vt_path::current_dir() + { + // Best-effort and silent: mid-typing values are often not (yet) dirs. + let _ = apply_chdir(¤t, &dir); + } + } + let current_dir = vt_path::current_dir().ok(); + match CompleteEnv::with_factory(command_for_completion) + .var("VP_COMPLETE") + .try_complete(args, current_dir.as_ref().map(|cwd| cwd.as_path())) + { + Ok(true) => Some(ExitCode::SUCCESS), + Ok(false) => None, + Err(error) => error.exit(), + } +} + +/// The zero-based index, into the completion words, of the word the cursor is +/// completing. Bash and zsh export `_CLAP_COMPLETE_INDEX`; the fish and +/// PowerShell writers always complete the last word. +fn completion_word_index(words: &[String]) -> usize { + env::var("_CLAP_COMPLETE_INDEX") + .ok() + .and_then(|index| index.parse().ok()) + .unwrap_or(words.len().saturating_sub(1)) +} + +/// Consume a leading `-C ` from completion words `[bin, ...]`, given the +/// zero-based `index` of the word the cursor is completing. +/// +/// clap_complete's engine matches words against subcommand names before it +/// consumes pending option values, so `vp -C dev run ...` would route into the +/// `vp dev` subcommand and complete nothing when the directory shares a name +/// with a subcommand. The separate `-C ` form is rewritten to a path +/// spelling (`dev` -> `./dev`), which resolves to the same directory but never +/// matches a subcommand name. +/// +/// Returns the directory the completed command will run in. `None` leaves the +/// words untouched: without a leading `-C`, or while the cursor is still +/// completing the `-C` flag or its value. +fn qualify_completion_chdir(words: &mut [String], index: usize) -> Option { + if words.len() < 2 { + return None; + } + let (dir, consumed) = parse_leading_chdir(&words[1..])?; + if index <= consumed { + return None; + } + // Attached forms (`-Cdev`, `-C=dev`) keep the value inside the flag token, + // which never matches a subcommand name on its own, and values already + // carrying path separators cannot collide either. + if consumed == 2 && !dir.starts_with(['.', '/']) && !dir.contains(['/', '\\']) { + words[2].insert_str(0, "./"); + } + Some(dir) +} + /// Normalize CLI arguments: /// - `vp list ...` / `vp ls ...` → `vp pm list ...` /// - `vp rebuild ...` → `vp pm rebuild ...` @@ -461,17 +535,15 @@ async fn run() -> ExitCode { } // Handle shell completion - // `complete()` exits before the normal `-C` handling below runs, so apply - // the target directory here too: cwd-sensitive completers (run tasks) - // should suggest from , where the completed command will run. - if env::var_os("VP_COMPLETE").is_some() - && let Some((dir, _)) = parse_leading_chdir(&args[1..]) - && let Ok(current) = vt_path::current_dir() - { - // Best-effort and silent: mid-typing values are often not (yet) dirs. - let _ = apply_chdir(¤t, &dir); + // `complete()` exits before the normal `-C` handling below runs, so a + // leading `-C ` must be consumed here too: cwd-sensitive completers + // (run tasks) should suggest from , where the completed command will + // run. The shell glue invokes the completer as `vp -- `, + // which hides `-C` from that pre-parse, so `complete_request` digs it out + // of the completion words instead. + if let Some(exit_code) = complete_request(&args) { + return exit_code; } - CompleteEnv::with_factory(command_for_completion).var("VP_COMPLETE").complete(); // Check for shim mode (invoked as node, npm, or npx) let argv0 = args.first().map(|s| s.as_str()).unwrap_or("vp"); @@ -665,7 +737,7 @@ mod tests { use super::{ extract_unknown_argument, has_pass_as_value_suggestion, is_affirmative_response, is_homebrew_recovery_command, normalize_args, parse_leading_chdir, - replace_top_level_typoed_subcommand, try_parse_args_from, + qualify_completion_chdir, replace_top_level_typoed_subcommand, try_parse_args_from, }; fn s(v: &[&str]) -> Vec { @@ -722,6 +794,59 @@ mod tests { Some(("apps/web".to_string(), consumed)) } + #[test] + fn qualify_completion_chdir_qualifies_subcommand_named_directory() { + // `vp -C dev run ...` must not let `dev` route into the `vp dev` + // subcommand while completing: the value becomes a path spelling that + // clap_complete's engine consumes as the `-C` value instead. + let mut words = s(&["vp", "-C", "dev", "run", "review-"]); + assert_eq!(qualify_completion_chdir(&mut words, 4).as_deref(), Some("dev")); + assert_eq!(words, s(&["vp", "-C", "./dev", "run", "review-"])); + } + + #[test] + fn qualify_completion_chdir_keeps_path_spellings_intact() { + for dir in ["./dev", "../dev", "web/sub", "/tmp/project"] { + let mut words = s(&["vp", "-C", dir, "run", "review-"]); + assert_eq!(qualify_completion_chdir(&mut words, 4).as_deref(), Some(dir)); + assert_eq!(words, s(&["vp", "-C", dir, "run", "review-"]), "{dir}"); + } + } + + #[test] + fn qualify_completion_chdir_keeps_attached_forms_intact() { + // `-Cdev` / `-C=dev` keep the value inside the flag token, which never + // matches a subcommand name on its own. + let mut words = s(&["vp", "-Cdev", "run", "review-"]); + assert_eq!(qualify_completion_chdir(&mut words, 3).as_deref(), Some("dev")); + assert_eq!(words, s(&["vp", "-Cdev", "run", "review-"])); + + let mut words = s(&["vp", "-C=dev", "run", "review-"]); + assert_eq!(qualify_completion_chdir(&mut words, 3).as_deref(), Some("dev")); + assert_eq!(words, s(&["vp", "-C=dev", "run", "review-"])); + } + + #[test] + fn qualify_completion_chdir_passes_through_mid_chdir_requests() { + // While the `-C` flag or its value is being completed, the words must + // stay untouched so the request completes normally. + let mut words = s(&["vp", "-C", "dev"]); + assert_eq!(qualify_completion_chdir(&mut words, 2), None); + assert_eq!(words, s(&["vp", "-C", "dev"])); + + let mut words = s(&["vp", "-C", ""]); + assert_eq!(qualify_completion_chdir(&mut words, 2), None); + assert_eq!(words, s(&["vp", "-C", ""])); + + let mut words = s(&["vp", "-C"]); + assert_eq!(qualify_completion_chdir(&mut words, 1), None); + assert_eq!(words, s(&["vp", "-C"])); + + let mut words = s(&["vp", "run", "review-"]); + assert_eq!(qualify_completion_chdir(&mut words, 2), None); + assert_eq!(words, s(&["vp", "run", "review-"])); + } + #[test] fn normalize_args_rewrites_bare_vp_node() { let input = s(&["vp", "node"]);