Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(alias): unify typo error format across config alias show/dry-run (#2306)
Maximilian Roos24181f251d99
diff --git a/src/commands/config/alias.rs b/src/commands/config/alias.rsindex a545bce2a..9f27c477f 100644--- a/src/commands/config/alias.rs+++ b/src/commands/config/alias.rs@@ -18,14 +18,16 @@//! natural home alongside `show`.use std::collections::{BTreeSet, HashMap};+use std::io::Write;use anyhow::Context;+use clap::error::{ContextKind, ContextValue, ErrorKind};use color_print::cformat;use worktrunk::config::{ALIAS_ARGS_KEY, CommandConfig, ProjectConfig, UserConfig, append_aliases,referenced_vars_for_config, template_references_var, validate_template_syntax,};-use worktrunk::git::Repository;+use worktrunk::git::{Repository, WorktrunkError};use worktrunk::styling::{format_bash_with_gutter, info_message, println};use crate::commands::alias::{AliasOptions, AliasSource, TOP_LEVEL_BUILTINS};@@ -50,6 +52,7 @@ pub fn handle_alias_show(name: String) -> anyhow::Result<()> {&user_config,project_config.as_ref(),&name,+ "show",));}@@ -100,6 +103,7 @@ pub fn handle_alias_dry_run(name: String, args: Vec<String>) -> anyhow::Result<(&user_config,project_config.as_ref(),&name,+ "dry-run",));}@@ -228,16 +232,35 @@ fn entries_for_name(entries}-/// Build an anyhow error for an unknown alias, with a clap-style "did you mean"-/// tail pulled from the merged alias name set.+/// Print an "unrecognized alias 'X'" error matching clap's `InvalidSubcommand`+/// layout — same `error:` / `tip:` / `Usage:` block and exit code 2 as+/// `wt <typo>` and `wt step <typo>`. `sub` is `"show"` or `"dry-run"`,+/// anchoring the error on the real clap subcommand so the Usage line reads+/// `Usage: wt config alias <sub> <NAME>`.///-/// Uses `anyhow::Error::context` so the top-level handler formats the first-/// line as a header and the suggestion list in the error gutter.+/// Built as a real `clap::Error` with `ErrorKind::InvalidSubcommand`, rendered+/// by clap, then string-substituted to say "alias" instead of "subcommand" —+/// the positional is an alias name, not a subcommand, so the tighter wording+/// reads more honestly at this surface. Going through clap's rendering gets+/// NO_COLOR / TTY detection, singular-vs-plural "similar" phrasing, and+/// styling correct automatically; modifying the final string is cheaper than+/// reimplementing those.+///+/// Substitutions are scoped to clap's fixed phrases, never the bare word+/// "subcommand" — otherwise an alias or typo containing the literal string+/// `subcommand` (e.g. `my-subcommand`) would be mangled when echoed into+/// the error. Plural `subcommands` is rewritten before singular `subcommand`+/// because `"similar subcommand"` is a prefix of `"similar subcommands"`.+///+/// Returns `AlreadyDisplayed { exit_code: 2 }` rather than calling+/// `process::exit`, so `main`'s `finish_command` still runs `terminate_output`+/// (ANSI reset for shell integration) and `diagnostic::write_if_verbose`.fn unknown_alias_error(repo: &Repository,user_config: &UserConfig,project_config: Option<&ProjectConfig>,name: &str,+ sub: &str,) -> anyhow::Error {let project_id = repo.project_identifier().ok();let mut merged = user_config.aliases(project_id.as_deref());@@ -245,16 +268,45 @@ fn unknown_alias_error(append_aliases(&mut merged, &pc.aliases);}let suggestions = did_you_mean(name, merged.into_keys());- let header = format!("unknown alias '{name}'");- if suggestions.is_empty() {- anyhow::anyhow!(header)- } else {- let mut detail = String::from("a similar alias exists:");- for s in &suggestions {- detail.push_str(&format!("\n {s}"));- }- anyhow::Error::msg(detail).context(header)++ let mut top = crate::cli::build_command();+ let sub_cmd = top+ .find_subcommand_mut("config")+ .expect("`config` subcommand is defined in the CLI")+ .find_subcommand_mut("alias")+ .expect("`config alias` subcommand is defined in the CLI")+ .find_subcommand_mut(sub)+ .unwrap_or_else(|| panic!("`config alias {sub}` subcommand is defined in the CLI"));+ // `render_usage` needs `bin_name`; clap only sets it on match, so when we+ // synthesize the error ahead of that, set it to the display_name+ // `apply_help_template_recursive` would apply.+ sub_cmd.set_bin_name(format!("wt config alias {sub}"));+ let usage = sub_cmd.render_usage();++ let mut err = clap::Error::new(ErrorKind::InvalidSubcommand).with_cmd(sub_cmd);+ err.insert(+ ContextKind::InvalidSubcommand,+ ContextValue::String(name.to_string()),+ );+ if !suggestions.is_empty() {+ err.insert(+ ContextKind::SuggestedSubcommand,+ ContextValue::Strings(suggestions),+ );}+ err.insert(ContextKind::Usage, ContextValue::StyledStr(usage));++ let rewritten = err+ .render()+ .ansi()+ .to_string()+ .replace("unrecognized subcommand", "unrecognized alias")+ .replace("similar subcommands", "similar aliases")+ .replace("similar subcommand", "similar alias");++ let mut stream = anstream::AutoStream::auto(std::io::stderr());+ let _ = write!(stream, "{rewritten}");+ WorktrunkError::AlreadyDisplayed { exit_code: 2 }.into()}/// Format one alias entry: `○ Alias <name> (<source>)[ <verb>]:` headerdiff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rsindex f6228ed47..4c067c86a 100644--- a/tests/integration_tests/step_alias.rs+++ b/tests/integration_tests/step_alias.rs@@ -1338,7 +1338,9 @@ deploy = "make deploy BRANCH={{ branch }}"));}-/// Unknown alias name triggers a did-you-mean suggestion.+/// Unknown alias name triggers a did-you-mean suggestion. Format mirrors+/// `wt <typo>` and `wt step <typo>`: clap-native `InvalidSubcommand` with a+/// `tip:` line — same shape at every alias-typo surface.#[rstest]fn test_config_alias_show_unknown_suggests(mut repo: TestRepo) {repo.write_project_config(@@ -1362,6 +1364,83 @@ hello = "echo hi"));}+/// Aliases or typos that literally contain `subcommand` must be echoed+/// verbatim — the word-substitution pass that rewrites clap's+/// "unrecognized subcommand" to "unrecognized alias" must only touch+/// clap's fixed phrases, not the user's input.+#[rstest]+fn test_config_alias_show_unknown_preserves_user_input(mut repo: TestRepo) {+ repo.write_project_config(+ r#"+[aliases]+"my-subcommand" = "echo hi"+"#,+ );+ repo.commit("Add alias config");+ let feature_path = repo.add_worktree("feature");++ let settings = setup_snapshot_settings(&repo);+ let _guard = settings.bind_to_scope();++ // Typo `my-subcommond` is close enough to `my-subcommand` to suggest it —+ // both the echoed typo and the suggestion must keep `subcommand` intact.+ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "config",+ &["alias", "show", "my-subcommond"],+ Some(&feature_path),+ ));+}++/// Single-match case: tip phrasing switches to the singular form+/// ("a similar alias exists") — mirrors clap's own singular rendering.+#[rstest]+fn test_config_alias_show_unknown_singular_suggestion(mut repo: TestRepo) {+ repo.write_project_config(+ r#"+[aliases]+deploy = "make deploy"+"#,+ );+ repo.commit("Add alias config");+ let feature_path = repo.add_worktree("feature");++ let settings = setup_snapshot_settings(&repo);+ let _guard = settings.bind_to_scope();++ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "config",+ &["alias", "show", "deplyo"],+ Some(&feature_path),+ ));+}++/// `wt config alias dry-run <typo>` produces the same clap-native typo error+/// as `show` — consistent format across both introspection subcommands.+#[rstest]+fn test_config_alias_dry_run_unknown_suggests(mut repo: TestRepo) {+ repo.write_project_config(+ r#"+[aliases]+deploy = "make deploy"+hello = "echo hi"+"#,+ );+ repo.commit("Add alias config");+ let feature_path = repo.add_worktree("feature");++ let settings = setup_snapshot_settings(&repo);+ let _guard = settings.bind_to_scope();++ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "config",+ &["alias", "dry-run", "deplyo"],+ Some(&feature_path),+ ));+}+/// Multi-step pipeline renders with per-step structure in the header.#[rstest]fn test_config_alias_show_pipeline(mut repo: TestRepo) {diff --git a/tests/snapshots/integration__integration_tests__step_alias__config_alias_dry_run_unknown_suggests.snap b/tests/snapshots/integration__integration_tests__step_alias__config_alias_dry_run_unknown_suggests.snapnew file mode 100644index 000000000..1328699f2--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_alias__config_alias_dry_run_unknown_suggests.snap@@ -0,0 +1,55 @@+---+source: tests/integration_tests/step_alias.rs+info:+ program: wt+ args:+ - config+ - alias+ - dry-run+ - deplyo+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ NO_COLOR: ""+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 2+----- stdout -----++----- stderr -----+[1m[31merror:[0m unrecognized alias '[33mdeplyo[0m'++ [32mtip:[0m some similar aliases exist: '[32mdeploy[0m', '[32mhello[0m'++[1m[4mUsage:[0m [1mwt config alias dry-run[0m <NAME> [1m[--[0m <ARGS>...[1m]++For more information, try '[1m--help[0m'.diff --git a/tests/snapshots/integration__integration_tests__step_alias__config_alias_show_unknown_no_suggestions.snap b/tests/snapshots/integration__integration_tests__step_alias__config_alias_show_unknown_no_suggestions.snapindex 9293dd1fe..d8959f25f 100644--- a/tests/snapshots/integration__integration_tests__step_alias__config_alias_show_unknown_no_suggestions.snap+++ b/tests/snapshots/integration__integration_tests__step_alias__config_alias_show_unknown_no_suggestions.snap@@ -42,8 +42,12 @@ info:XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"---success: false-exit_code: 1+exit_code: 2----- stdout ---------- stderr ------[31m✗[39m [31munknown alias 'zzzzzzzz'[39m+[1m[31merror:[0m unrecognized alias '[33mzzzzzzzz[0m'++[1m[4mUsage:[0m [1mwt config alias show[0m <NAME>++For more information, try '[1m--help[0m'.diff --git a/tests/snapshots/integration__integration_tests__step_alias__config_alias_show_unknown_preserves_user_input.snap b/tests/snapshots/integration__integration_tests__step_alias__config_alias_show_unknown_preserves_user_input.snapnew file mode 100644index 000000000..67ddf2ef4--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_alias__config_alias_show_unknown_preserves_user_input.snap@@ -0,0 +1,55 @@+---+source: tests/integration_tests/step_alias.rs+info:+ program: wt+ args:+ - config+ - alias+ - show+ - my-subcommond+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ NO_COLOR: ""+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 2+----- stdout -----++----- stderr -----+[1m[31merror:[0m unrecognized alias '[33mmy-subcommond[0m'++ [32mtip:[0m a similar alias exists: '[32mmy-subcommand[0m'++[1m[4mUsage:[0m [1mwt config alias show[0m <NAME>++For more information, try '[1m--help[0m'.diff --git a/tests/snapshots/integration__integration_tests__step_alias__config_alias_show_unknown_singular_suggestion.snap b/tests/snapshots/integration__integration_tests__step_alias__config_alias_show_unknown_singular_suggestion.snapnew file mode 100644index 000000000..55a962f6a--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_alias__config_alias_show_unknown_singular_suggestion.snap@@ -0,0 +1,55 @@+---+source: tests/integration_tests/step_alias.rs+info:+ program: wt+ args:+ - config+ - alias+ - show+ - deplyo+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ NO_COLOR: ""+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 2+----- stdout -----++----- stderr -----+[1m[31merror:[0m unrecognized alias '[33mdeplyo[0m'++ [32mtip:[0m a similar alias exists: '[32mdeploy[0m'++[1m[4mUsage:[0m [1mwt config alias show[0m <NAME>++For more information, try '[1m--help[0m'.diff --git a/tests/snapshots/integration__integration_tests__step_alias__config_alias_show_unknown_suggests.snap b/tests/snapshots/integration__integration_tests__step_alias__config_alias_show_unknown_suggests.snapindex 62e1a120d..fe0955dad 100644--- a/tests/snapshots/integration__integration_tests__step_alias__config_alias_show_unknown_suggests.snap+++ b/tests/snapshots/integration__integration_tests__step_alias__config_alias_show_unknown_suggests.snap@@ -42,11 +42,14 @@ info:XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"---success: false-exit_code: 1+exit_code: 2----- stdout ---------- stderr ------[31m✗[39m [31munknown alias 'deplyo'[39m-[107m [0m a similar alias exists:-[107m [0m deploy-[107m [0m hello+[1m[31merror:[0m unrecognized alias '[33mdeplyo[0m'++ [32mtip:[0m some similar aliases exist: '[32mdeploy[0m', '[32mhello[0m'++[1m[4mUsage:[0m [1mwt config alias show[0m <NAME>++For more information, try '[1m--help[0m'.