Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Restore clap-native error for unrecognized subcommands (#2212)
Maximilian Roos7c03072e81ec
diff --git a/src/commands/external.rs b/src/commands/external.rsindex 867dd5dae..e2e441156 100644--- a/src/commands/external.rs+++ b/src/commands/external.rs@@ -7,12 +7,13 @@//!//! Behaviour://!-//! 1. If the name matches a nested subcommand (e.g. `squash` → `wt step squash`),-//! print the suggestion and exit — preserves the existing hint behaviour.-//! 2. Otherwise, resolve `wt-<name>` via `which`. If found, run it with the-//! remaining args, inheriting stdio, and propagate the exit code.-//! 3. If not found, print a git-style "not a wt command" error, with a-//! best-match suggestion computed from the list of built-in subcommands.+//! 1. Resolve `wt-<name>` via `which`. If found, run it with the remaining+//! args, inheriting stdio, and propagate the exit code.+//! 2. If not found, synthesize clap's native `InvalidSubcommand` error and+//! route it through `enhance_and_exit_error` so the output matches what+//! clap would have produced without `external_subcommand` — same+//! formatting, suggestions, Usage line, and nested-subcommand tip (e.g.+//! `wt squash` → `perhaps wt step squash?`).//!//! Built-in subcommands always take precedence — clap only dispatches//! `Commands::External` when no built-in matched, so there is no way for an@@ -23,13 +24,12 @@ use std::path::{Path, PathBuf};use std::process::Command;use anyhow::{Context, Result};-use clap::CommandFactory;-use color_print::cformat;-use strsim::levenshtein;+use clap::error::{ContextKind, ContextValue, ErrorKind};+use strsim::jaro_winkler;use worktrunk::git::WorktrunkError;-use worktrunk::styling::{eprintln, error_message, hint_message};-use crate::cli::{Cli, suggest_nested_subcommand};+use crate::cli::build_command;+use crate::enhance_and_exit_error;/// Handle a `Commands::External` invocation.///@@ -38,11 +38,11 @@ use crate::cli::{Cli, suggest_nested_subcommand};/// flag — applied as the child's current directory so global `-C` works the/// same for external subcommands as it does for built-ins.///-/// On success (child exit code 0), returns `Ok(())`. On non-zero exit or when-/// the command isn't found, returns `WorktrunkError::AlreadyDisplayed` with-/// the appropriate exit code so `main` can propagate it without printing an-/// extra error line (the child, or this module, has already reported the-/// failure). Exit code 1 for "not found" matches git's behaviour.+/// On success (child exit code 0), returns `Ok(())`. On non-zero exit, returns+/// `WorktrunkError::AlreadyDisplayed` with the child's exit code so `main`+/// can propagate it without printing an extra error line. When the command+/// isn't found on PATH, diverges via `enhance_and_exit_error` with clap's+/// standard exit code 2.pub(crate) fn handle_external_command(args: Vec<OsString>,working_dir: Option<PathBuf>,@@ -63,29 +63,52 @@ pub(crate) fn handle_external_command(})?.to_owned();- // Nested subcommand suggestion takes precedence: `wt squash` should still- // hint at `wt step squash` rather than searching PATH for `wt-squash`.- let cli_cmd = Cli::command();- if let Some(suggestion) = suggest_nested_subcommand(&cli_cmd, &name) {- eprintln!(- "{}",- error_message(cformat!("Unrecognized subcommand '<cyan,bold>{name}</>'"))- );- eprintln!(- "{}",- hint_message(cformat!("Perhaps <cyan,bold>{suggestion}</>?"))- );- eprintln!("{}", hint_message(help_hint()));- return Err(WorktrunkError::AlreadyDisplayed { exit_code: 2 }.into());+ // Try the PATH lookup first. If a `wt-<name>` binary exists, it takes+ // precedence over clap's "unrecognized subcommand" error path — but *not*+ // over built-ins, because clap only dispatches `External` when no built-in+ // matched. Nested-subcommand hints (`wt squash` → `wt step squash`) are+ // applied by `enhance_and_exit_error` when we fall through below, so a+ // name that matches a nested subcommand still gets its tip even though+ // we look at PATH first (nested names aren't expected to collide with+ // real `wt-*` binaries, and if they do the on-PATH binary wins — same as+ // git's behaviour).+ let binary = format!("wt-{name}");+ if let Ok(path) = which::which(&binary) {+ return run_external(&path, &rest, working_dir.as_deref());}- let binary = format!("wt-{name}");- let Ok(path) = which::which(&binary) else {- print_not_found(&name, &cli_cmd);- return Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into());- };+ // Not on PATH — emit clap's native `InvalidSubcommand` error. Routing+ // through `enhance_and_exit_error` keeps the rendering consistent with+ // every other clap error (same tip/Usage formatting) and layers the+ // wt-specific nested-subcommand hint on top.+ enhance_and_exit_error(unrecognized_subcommand_error(&name));+}- run_external(&path, &rest, working_dir.as_deref())+/// Build a `clap::Error` that mirrors what clap itself would have raised for+/// an unrecognized top-level subcommand if we weren't capturing via+/// `#[command(external_subcommand)]`. Populates `InvalidSubcommand`,+/// `SuggestedSubcommand`, and `Usage` context so clap's rich formatter+/// produces its native output (the "tip:" line and "Usage:" block come from+/// these context entries).+fn unrecognized_subcommand_error(name: &str) -> clap::Error {+ let mut cmd = build_command();+ let mut err = clap::Error::new(ErrorKind::InvalidSubcommand).with_cmd(&cmd);+ err.insert(+ ContextKind::InvalidSubcommand,+ ContextValue::String(name.to_string()),+ );+ let suggestions = similar_subcommands(name, &cmd);+ if !suggestions.is_empty() {+ err.insert(+ ContextKind::SuggestedSubcommand,+ ContextValue::Strings(suggestions),+ );+ }+ err.insert(+ ContextKind::Usage,+ ContextValue::StyledStr(cmd.render_usage()),+ );+ err}/// Spawn the external binary, inheriting stdio, and propagate its exit code.@@ -121,46 +144,22 @@ fn run_external(path: &Path, args: &[OsString], working_dir: Option<&Path>) -> RErr(WorktrunkError::AlreadyDisplayed { exit_code: code }.into())}-/// Print a git-style "not a wt command" error, with an optional typo suggestion.-fn print_not_found(name: &str, cli_cmd: &clap::Command) {- eprintln!(- "{}",- error_message(cformat!("'<cyan,bold>{name}</>' is not a wt command"))- );- if let Some(suggestion) = closest_subcommand(name, cli_cmd) {- eprintln!(- "{}",- hint_message(cformat!(- "The most similar command is <cyan,bold>{suggestion}</>"- ))- );- }- eprintln!("{}", hint_message(help_hint()));-}--/// The "For more information, try `wt --help`" tail shared by both-/// unrecognized-subcommand branches. Mirrors the suggestion clap emitted-/// before we took over this error path.-fn help_hint() -> String {- cformat!("For more information, try '<cyan,bold>wt --help</>'.")-}--/// Return the closest visible built-in subcommand name by Levenshtein distance,-/// or `None` if nothing is reasonably close.-fn closest_subcommand(name: &str, cli_cmd: &clap::Command) -> Option<String> {- // Threshold chosen to mirror clap's internal `did_you_mean`: allow up to- // a third of the input length in edits, but always tolerate at least one.- let max_distance = (name.len() / 3).max(1);-- cli_cmd+/// Return visible built-in subcommand names similar to `name`, sorted by+/// descending confidence. Mirrors clap's internal `did_you_mean` (Jaro–Winkler+/// similarity with a 0.7 threshold) so the `tip:` line reads the same as it+/// would have without `#[command(external_subcommand)]` intercepting the+/// error.+fn similar_subcommands(name: &str, cli_cmd: &clap::Command) -> Vec<String> {+ let mut scored: Vec<(f64, String)> = cli_cmd.get_subcommands().filter(|c| !c.is_hide_set()).map(|c| c.get_name()).filter(|&candidate| candidate != "help")- .map(|candidate| (candidate, levenshtein(name, candidate)))- .filter(|&(_, dist)| dist <= max_distance)- .min_by_key(|&(_, dist)| dist)- .map(|(candidate, _)| candidate.to_string())+ .map(|candidate| (jaro_winkler(name, candidate), candidate.to_string()))+ .filter(|(score, _)| *score > 0.7)+ .collect();+ scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));+ scored.into_iter().map(|(_, name)| name).collect()}#[cfg(test)]@@ -168,26 +167,28 @@ mod tests {use super::*;#[test]- fn closest_subcommand_finds_typo() {- let cmd = Cli::command();+ fn similar_subcommands_finds_typo() {+ let cmd = build_command();+ let suggestions = similar_subcommands("siwtch", &cmd);assert_eq!(- closest_subcommand("siwtch", &cmd).as_deref(),- Some("switch")+ suggestions.first().map(String::as_str),+ Some("switch"),+ "got: {suggestions:?}");}#[test]- fn closest_subcommand_ignores_unrelated() {- let cmd = Cli::command();- assert_eq!(closest_subcommand("zzzzzzzz", &cmd), None);+ fn similar_subcommands_ignores_unrelated() {+ let cmd = build_command();+ assert!(similar_subcommands("zzzzzzzz", &cmd).is_empty());}#[test]- fn closest_subcommand_skips_hidden() {+ fn similar_subcommands_skips_hidden() {// `select` is hidden (deprecated); it should not be suggested even// though an exact-match candidate exists.- let cmd = Cli::command();- assert_eq!(closest_subcommand("select", &cmd), None);+ let cmd = build_command();+ assert!(!similar_subcommands("select", &cmd).contains(&"select".to_string()));}#[cfg(unix)]diff --git a/src/main.rs b/src/main.rsindex c8c89e3fc..2be8e11a7 100644--- a/src/main.rs+++ b/src/main.rs@@ -72,7 +72,7 @@ use worktrunk::HookType;/// Enhance clap errors with command-specific hints, then exit.////// For unrecognized subcommands that match nested commands, suggests the full path.-fn enhance_and_exit_error(err: clap::Error) -> ! {+pub(crate) fn enhance_and_exit_error(err: clap::Error) -> ! {// For unrecognized subcommands, check if they match a nested subcommand// e.g., `wt squash` -> suggest `wt step squash`if err.kind() == ClapErrorKind::InvalidSubcommanddiff --git a/tests/integration_tests/external.rs b/tests/integration_tests/external.rsindex 4f8810db1..64269de0c 100644--- a/tests/integration_tests/external.rs+++ b/tests/integration_tests/external.rs@@ -60,7 +60,7 @@ fn external_subcommand_runs_wt_prefixed_binary_on_path() {}#[test]-fn external_subcommand_not_found_prints_hint_and_exits_nonzero() {+fn external_subcommand_not_found_prints_clap_error() {let mut cmd = wt_command();// Clear PATH so no `wt-*` binaries can be discovered, then add a single// empty dir so `which` has somewhere to look.@@ -70,11 +70,16 @@ fn external_subcommand_not_found_prints_hint_and_exits_nonzero() {let output = cmd.output().expect("failed to run wt");assert!(!output.status.success(), "expected failure");- assert_eq!(output.status.code(), Some(1));- let stderr = String::from_utf8_lossy(&output.stderr);+ // clap's standard InvalidSubcommand exit code.+ assert_eq!(output.status.code(), Some(2));+ let stderr = strip_ansi(&String::from_utf8_lossy(&output.stderr));+ assert!(+ stderr.contains("unrecognized subcommand 'definitely-not-a-wt-subcommand'"),+ "stderr should use clap's native error format: {stderr}"+ );assert!(- stderr.contains("is not a wt command"),- "stderr missing hint: {stderr}"+ stderr.contains("Usage:") && stderr.contains("try '--help'"),+ "stderr should include Usage block and --help suggestion: {stderr}");}@@ -87,22 +92,22 @@ fn external_subcommand_typo_suggests_closest_builtin() {let output = cmd.output().expect("failed to run wt");assert!(!output.status.success());- let stderr = String::from_utf8_lossy(&output.stderr);+ let stderr = strip_ansi(&String::from_utf8_lossy(&output.stderr));assert!(- stderr.contains("most similar command"),- "stderr missing similar-command hint: {stderr}"+ stderr.contains("tip:") && stderr.contains("similar subcommand"),+ "stderr missing clap's similar-subcommand tip: {stderr}");assert!(- stderr.contains("switch"),+ stderr.contains("'switch'"),"stderr should suggest 'switch': {stderr}");}#[test]fn external_subcommand_nested_suggestion_wins_over_path_lookup() {- // `wt squash` should suggest `wt step squash` even if `wt-squash` were on- // PATH. We don't place one there because that's the point — nested- // suggestion pre-empts the PATH lookup.+ // `wt squash` should suggest `wt step squash` even though `wt-squash` is+ // not on PATH. The nested tip is layered on top of clap's standard+ // unrecognized-subcommand error.let mut cmd = wt_command();let empty = TempDir::new().unwrap();cmd.env("PATH", empty.path());@@ -111,13 +116,34 @@ fn external_subcommand_nested_suggestion_wins_over_path_lookup() {let output = cmd.output().expect("failed to run wt");assert!(!output.status.success());assert_eq!(output.status.code(), Some(2));- let stderr = String::from_utf8_lossy(&output.stderr);+ let stderr = strip_ansi(&String::from_utf8_lossy(&output.stderr));assert!(stderr.contains("wt step squash"),"stderr should suggest 'wt step squash': {stderr}");}+/// Strip ANSI escape sequences so test assertions can match rendered text+/// without worrying about colour codes clap inserts.+fn strip_ansi(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ let mut chars = s.chars();+ while let Some(c) = chars.next() {+ if c == '\u{1b}' {+ // CSI: ESC [ ... letter. Drop everything up to (and including)+ // the terminator (any ASCII letter).+ for next in chars.by_ref() {+ if next.is_ascii_alphabetic() {+ break;+ }+ }+ } else {+ out.push(c);+ }+ }+ out+}+#[test]fn external_subcommand_propagates_exit_code() {let dir = mock_bin_dir(diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rsindex ede6b607d..623214956 100644--- a/tests/integration_tests/shell_wrapper.rs+++ b/tests/integration_tests/shell_wrapper.rs@@ -1609,8 +1609,8 @@ approved-commands = ["echo 'fish background task'"]// CRITICAL: Should see wt's actual error message about an unknown subcommandassert!(- output.combined.contains("is not a wt command"),- "{}: Should show actual wt error message 'is not a wt command'.\nOutput:\n{}",+ output.combined.contains("unrecognized subcommand"),+ "{}: Should show clap's 'unrecognized subcommand' error.\nOutput:\n{}",shell,output.combined);diff --git a/tests/snapshots/integration__integration_tests__help__nested_subcommand_hook_pre_merge.snap b/tests/snapshots/integration__integration_tests__help__nested_subcommand_hook_pre_merge.snapindex dc9fafda7..8435b93eb 100644--- a/tests/snapshots/integration__integration_tests__help__nested_subcommand_hook_pre_merge.snap+++ b/tests/snapshots/integration__integration_tests__help__nested_subcommand_hook_pre_merge.snap@@ -31,6 +31,12 @@ exit_code: 2----- stdout ---------- stderr ------[31m✗[39m [31mUnrecognized subcommand '[36m[1mpre-merge[39m[22m'[39m-[2m↳[22m [2mPerhaps [36m[1mwt hook pre-merge[39m[22m?[22m-[2m↳[22m [2mFor more information, try '[36m[1mwt --help[39m[22m'.[22m+[1m[31merror:[0m unrecognized subcommand '[1m[33mpre-merge[0m'++ [1m[32mtip:[0m a similar subcommand exists: '[1m[32mremove[0m'++[1m[32mUsage:[0m [1m[36mwt[0m [36m[OPTIONS][0m [36m[COMMAND][0m++For more information, try '[1m[36m--help[0m'.++ [33mtip:[39m perhaps [36m[1mwt hook pre-merge[39m[22m?diff --git a/tests/snapshots/integration__integration_tests__help__nested_subcommand_hook_pre_start.snap b/tests/snapshots/integration__integration_tests__help__nested_subcommand_hook_pre_start.snapindex dd33eddd4..c6557561d 100644--- a/tests/snapshots/integration__integration_tests__help__nested_subcommand_hook_pre_start.snap+++ b/tests/snapshots/integration__integration_tests__help__nested_subcommand_hook_pre_start.snap@@ -31,6 +31,10 @@ exit_code: 2----- stdout ---------- stderr ------[31m✗[39m [31mUnrecognized subcommand '[36m[1mpre-start[39m[22m'[39m-[2m↳[22m [2mPerhaps [36m[1mwt hook pre-start[39m[22m?[22m-[2m↳[22m [2mFor more information, try '[36m[1mwt --help[39m[22m'.[22m+[1m[31merror:[0m unrecognized subcommand '[1m[33mpre-start[0m'++[1m[32mUsage:[0m [1m[36mwt[0m [36m[OPTIONS][0m [36m[COMMAND][0m++For more information, try '[1m[36m--help[0m'.++ [33mtip:[39m perhaps [36m[1mwt hook pre-start[39m[22m?diff --git a/tests/snapshots/integration__integration_tests__help__nested_subcommand_step_commit.snap b/tests/snapshots/integration__integration_tests__help__nested_subcommand_step_commit.snapindex b4a05baed..e4325f964 100644--- a/tests/snapshots/integration__integration_tests__help__nested_subcommand_step_commit.snap+++ b/tests/snapshots/integration__integration_tests__help__nested_subcommand_step_commit.snap@@ -31,6 +31,10 @@ exit_code: 2----- stdout ---------- stderr ------[31m✗[39m [31mUnrecognized subcommand '[36m[1mcommit[39m[22m'[39m-[2m↳[22m [2mPerhaps [36m[1mwt step commit[39m[22m?[22m-[2m↳[22m [2mFor more information, try '[36m[1mwt --help[39m[22m'.[22m+[1m[31merror:[0m unrecognized subcommand '[1m[33mcommit[0m'++[1m[32mUsage:[0m [1m[36mwt[0m [36m[OPTIONS][0m [36m[COMMAND][0m++For more information, try '[1m[36m--help[0m'.++ [33mtip:[39m perhaps [36m[1mwt step commit[39m[22m?diff --git a/tests/snapshots/integration__integration_tests__help__nested_subcommand_step_squash.snap b/tests/snapshots/integration__integration_tests__help__nested_subcommand_step_squash.snapindex 48e79a005..c8c4743d6 100644--- a/tests/snapshots/integration__integration_tests__help__nested_subcommand_step_squash.snap+++ b/tests/snapshots/integration__integration_tests__help__nested_subcommand_step_squash.snap@@ -31,6 +31,10 @@ exit_code: 2----- stdout ---------- stderr ------[31m✗[39m [31mUnrecognized subcommand '[36m[1msquash[39m[22m'[39m-[2m↳[22m [2mPerhaps [36m[1mwt step squash[39m[22m?[22m-[2m↳[22m [2mFor more information, try '[36m[1mwt --help[39m[22m'.[22m+[1m[31merror:[0m unrecognized subcommand '[1m[33msquash[0m'++[1m[32mUsage:[0m [1m[36mwt[0m [36m[OPTIONS][0m [36m[COMMAND][0m++For more information, try '[1m[36m--help[0m'.++ [33mtip:[39m perhaps [36m[1mwt step squash[39m[22m?diff --git a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__source_flag_error_passthrough.snap b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__source_flag_error_passthrough.snapindex 7eb341ed3..7644133b4 100644--- a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__source_flag_error_passthrough.snap+++ b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__source_flag_error_passthrough.snap@@ -3,5 +3,10 @@ source: tests/integration_tests/shell_wrapper.rsexpression: "&output.combined"----[31m✗[39m [31m'[36m[1mfoo[39m[22m' is not a wt command[39m-[2m↳[22m [2mFor more information, try '[36m[1mwt --help[39m[22m'.[22m+[1m[31merror:[0m unrecognized subcommand '[1m[33mfoo[0m'++ [1m[32mtip:[0m a similar subcommand exists: '[1m[32mhook[0m'++[1m[32mUsage:[0m [1m[36mwt[0m [36m[OPTIONS][0m [36m[COMMAND]++For more information, try '[1m[36m--help[0m'.