Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(commands): share InvalidSubcommand error builder across typo sites (#2308)
Maximilian Roos3e0320ed671f
diff --git a/src/commands/alias.rs b/src/commands/alias.rsindex 68d1ecb90..f5a3c4724 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -33,7 +33,6 @@use std::collections::{BTreeMap, BTreeSet};use anyhow::{Context, bail};-use clap::error::{ContextKind, ContextValue, ErrorKind};use color_print::cformat;use worktrunk::config::{ALIAS_ARGS_KEY, CommandConfig, HookStep, ProjectConfig, UserConfig, append_aliases,@@ -47,8 +46,8 @@ use crate::commands::command_executor::{CommandContext, CommandOrigin, FailureStrategy, ForegroundStep, PreparedCommand, PreparedStep,build_hook_context, execute_pipeline_foreground,};-use crate::commands::did_you_mean;use crate::commands::hooks::{format_pipeline_summary_from_names, step_names_from_config};+use crate::commands::{build_invalid_subcommand_error, similar_subcommands};use crate::output::DirectivePassthrough;/// Built-in `wt step` subcommand names. Aliases with these names are@@ -272,7 +271,7 @@ fn alias_needs_approval(/// the visible built-in `wt step` subcommands and the user's configured/// aliases — `SuggestedSubcommand` takes arbitrary strings, so aliases show/// up in the `tip:` line for typos like `wt step deplyo` → `'deploy'`.-fn unknown_step_command_error(name: &str, alias_names: &[&str]) -> anyhow::Error {+fn unknown_step_command_error(name: &str, alias_names: &[String]) -> anyhow::Error {let mut top = crate::cli::build_command();let step_cmd = top.find_subcommand_mut("step")@@ -283,29 +282,8 @@ fn unknown_step_command_error(name: &str, alias_names: &[&str]) -> anyhow::Error// <COMMAND>` instead of `Usage: wt step [COMMAND]`. Set it to the same// display_name applied by `apply_help_template_recursive`.step_cmd.set_bin_name("wt step");- let usage = step_cmd.render_usage();-- let builtins = step_cmd- .get_subcommands()- .filter(|c| !c.is_hide_set())- .map(|c| c.get_name().to_string())- .filter(|n| n != "help");- let candidates = builtins.chain(alias_names.iter().map(|s| s.to_string()));- let suggestions = did_you_mean(name, candidates);-- let mut err = clap::Error::new(ErrorKind::InvalidSubcommand).with_cmd(step_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));- crate::enhance_clap_error(err)+ let suggestions = similar_subcommands(name, step_cmd, alias_names);+ crate::enhance_clap_error(build_invalid_subcommand_error(step_cmd, name, suggestions))}/// Format the "Running alias …" announcement.@@ -425,10 +403,10 @@ pub fn step_alias(args: Vec<String>, global_yes: bool) -> anyhow::Result<()> {// gets `tip: ... 'deploy'` when `deploy` is user-defined. The// Aliases block in `wt step --help` is the full discovery surface —// the error just needs to point there via `Usage: wt step [COMMAND]`.- let alias_names: Vec<&str> = aliases+ let alias_names: Vec<String> = aliases.keys().filter(|k| !BUILTIN_STEP_COMMANDS.contains(&k.as_str()))- .map(|k| k.as_str())+ .cloned().collect();return Err(unknown_step_command_error(&name, &alias_names));};diff --git a/src/commands/config/alias.rs b/src/commands/config/alias.rsindex 9f27c477f..7fdc739ad 100644--- a/src/commands/config/alias.rs+++ b/src/commands/config/alias.rs@@ -21,7 +21,6 @@ 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,@@ -31,6 +30,7 @@ use worktrunk::git::{Repository, WorktrunkError};use worktrunk::styling::{format_bash_with_gutter, info_message, println};use crate::commands::alias::{AliasOptions, AliasSource, TOP_LEVEL_BUILTINS};+use crate::commands::build_invalid_subcommand_error;use crate::commands::command_executor::{CommandContext, build_hook_context, expand_shell_template,};@@ -281,20 +281,7 @@ fn unknown_alias_error(// 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 err = build_invalid_subcommand_error(sub_cmd, name, suggestions);let rewritten = err.render()diff --git a/src/commands/custom.rs b/src/commands/custom.rsindex d8f504911..31aeb84b4 100644--- a/src/commands/custom.rs+++ b/src/commands/custom.rs@@ -29,11 +29,12 @@ use std::path::{Path, PathBuf};use std::process::Command;use anyhow::{Context, Result};-use clap::error::{ContextKind, ContextValue, ErrorKind};use worktrunk::git::WorktrunkError;use crate::cli::build_command;-use crate::commands::{alias_names_for_suggestions, did_you_mean, try_alias};+use crate::commands::{+ alias_names_for_suggestions, build_invalid_subcommand_error, similar_subcommands, try_alias,+};use crate::enhance_clap_error;/// Handle a `Commands::Custom` invocation.@@ -119,24 +120,9 @@ pub(crate) fn handle_custom_command(/// matching the discovery surface of `wt --help`.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 alias_names = alias_names_for_suggestions();let suggestions = similar_subcommands(name, &cmd, &alias_names);- if !suggestions.is_empty() {- err.insert(- ContextKind::SuggestedSubcommand,- ContextValue::Strings(suggestions),- );- }- err.insert(- ContextKind::Usage,- ContextValue::StyledStr(cmd.render_usage()),- );- err+ build_invalid_subcommand_error(&mut cmd, name, suggestions)}/// Spawn the custom binary, inheriting stdio, and propagate its exit code.@@ -172,19 +158,6 @@ fn run_custom(path: &Path, args: &[OsString], working_dir: Option<&Path>) -> ResErr(WorktrunkError::AlreadyDisplayed { exit_code: code }.into())}-/// Return visible built-in subcommand names and configured alias names-/// similar to `name`. Dedupe matters here: an alias configured with the-/// same name as a built-in would otherwise appear twice in the candidate-/// pool and surface duplicated in the `tip:` line.-fn similar_subcommands(name: &str, cli_cmd: &clap::Command, alias_names: &[String]) -> Vec<String> {- let builtins = cli_cmd- .get_subcommands()- .filter(|c| !c.is_hide_set())- .map(|c| c.get_name().to_string())- .filter(|candidate| candidate != "help");- did_you_mean(name, builtins.chain(alias_names.iter().cloned()))-}-#[cfg(test)]mod tests {use super::*;diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 3f27ef0a2..c5269bf13 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -102,6 +102,56 @@ pub(crate) fn did_you_mean(.collect()}+/// Return visible subcommand names of `parent` plus `alias_names`, filtered to+/// those similar to `name`. Hidden subcommands (e.g., deprecated aliases) and+/// clap's implicit `help` are excluded. Shared by the top-level (`wt <typo>`)+/// and `wt step <typo>` suggestion paths — both surfaces want "visible+/// built-ins + configured aliases" as the candidate pool.+pub(crate) fn similar_subcommands(+ name: &str,+ parent: &clap::Command,+ alias_names: &[String],+) -> Vec<String> {+ let builtins = parent+ .get_subcommands()+ .filter(|c| !c.is_hide_set())+ .map(|c| c.get_name().to_string())+ .filter(|candidate| candidate != "help");+ did_you_mean(name, builtins.chain(alias_names.iter().cloned()))+}++/// Build a clap `InvalidSubcommand` error anchored on `anchor`, populating the+/// standard `InvalidSubcommand` / `SuggestedSubcommand` / `Usage` context so+/// clap's native formatter produces the `error:` / `tip:` / `Usage:` block.+///+/// `anchor` must have its `bin_name` set before this call so the rendered+/// `Usage:` line reads e.g. `wt step <COMMAND>` rather than the bare leaf+/// name. Top-level callers can rely on `build_command()`'s display_name; nested+/// anchors (`wt step`, `wt config alias <sub>`) need an explicit+/// `anchor.set_bin_name(...)` first.+pub(crate) fn build_invalid_subcommand_error(+ anchor: &mut clap::Command,+ name: &str,+ suggestions: Vec<String>,+) -> clap::Error {+ use clap::error::{ContextKind, ContextValue, ErrorKind};++ let usage = anchor.render_usage();+ let mut err = clap::Error::new(ErrorKind::InvalidSubcommand).with_cmd(anchor);+ 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));+ err+}+/// Force concurrent steps to run serially. Test-only escape hatch — set via/// `WORKTRUNK_TEST_SERIAL_CONCURRENT=1` to make output ordering deterministic/// for snapshot tests, mirroring how `RAYON_NUM_THREADS=1` is used elsewhere.