Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

refactor(suggestions): extract shared `did_you_mean` helper (#2268)

Maximilian Roos42acd55fa6ce
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index edefe9209..25ee70dc5 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -35,7 +35,6 @@ use std::collections::{BTreeMap, HashMap};
use anyhow::{Context, bail};
use clap::error::{ContextKind, ContextValue, ErrorKind};
use color_print::cformat;
-use strsim::jaro_winkler;
use worktrunk::config::{
CommandConfig, HookStep, ProjectConfig, UserConfig, append_aliases, template_references_var,
validate_template_syntax,
@@ -48,6 +47,7 @@ use crate::commands::command_executor::{
CommandContext, CommandOrigin, FailureStrategy, ForegroundStep, PreparedCommand, PreparedStep,
build_hook_context, execute_pipeline_foreground, expand_shell_template,
};
+use crate::commands::did_you_mean;
use crate::commands::hooks::format_pipeline_summary_from_names;
use crate::output::DirectivePassthrough;
@@ -175,9 +175,6 @@ 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'`.
-///
-/// Uses the same `jaro_winkler > 0.7` threshold as clap's internal
-/// `did_you_mean` so the tip line reads identically to the top-level path.
fn unknown_step_command_exit(name: &str, alias_names: &[&str]) -> ! {
let mut top = crate::cli::build_command();
let step_cmd = top
@@ -191,21 +188,13 @@ fn unknown_step_command_exit(name: &str, alias_names: &[&str]) -> ! {
step_cmd.set_bin_name("wt step");
let usage = step_cmd.render_usage();
- let mut candidates: Vec<&str> = step_cmd
+ let builtins = step_cmd
.get_subcommands()
.filter(|c| !c.is_hide_set())
- .map(|c| c.get_name())
- .filter(|&n| n != "help")
- .collect();
- candidates.extend(alias_names);
-
- let mut scored: Vec<(f64, String)> = candidates
- .into_iter()
- .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));
- let suggestions: Vec<String> = scored.into_iter().map(|(_, n)| n).collect();
+ .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(
diff --git a/src/commands/external.rs b/src/commands/external.rs
index 456e13eba..0b70555a7 100644
--- a/src/commands/external.rs
+++ b/src/commands/external.rs
@@ -28,11 +28,10 @@ use std::process::Command;
use anyhow::{Context, Result};
use clap::error::{ContextKind, ContextValue, ErrorKind};
-use strsim::jaro_winkler;
use worktrunk::git::WorktrunkError;
use crate::cli::build_command;
-use crate::commands::{alias_names_for_suggestions, try_alias};
+use crate::commands::{alias_names_for_suggestions, did_you_mean, try_alias};
use crate::enhance_and_exit_error;
/// Handle a `Commands::External` invocation.
@@ -167,30 +166,16 @@ fn run_external(path: &Path, args: &[OsString], working_dir: Option<&Path>) -> R
}
/// Return visible built-in subcommand names and configured alias 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, plus aliases.
+/// 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");
- let candidates = builtins.chain(alias_names.iter().cloned());
- let mut scored: Vec<(f64, String)> = candidates
- .map(|candidate| (jaro_winkler(name, &candidate), candidate))
- .filter(|(score, _)| *score > 0.7)
- .collect();
- scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
- // Dedupe while preserving sort order (an alias with the same name as a
- // built-in would otherwise appear twice).
- let mut seen = std::collections::HashSet::new();
- scored
- .into_iter()
- .filter(|(_, n)| seen.insert(n.clone()))
- .map(|(_, n)| n)
- .collect()
+ did_you_mean(name, builtins.chain(alias_names.iter().cloned()))
}
#[cfg(test)]
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index d8c13ac9b..1ec122ace 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -78,6 +78,29 @@ pub(crate) fn format_command_label(command_type: &str, name: Option<&str>) -> St
}
}
+/// Return candidates similar to `query`, sorted by descending Jaro–Winkler
+/// similarity, filtered by `score > 0.7`, and deduplicated while preserving
+/// order. The 0.7 threshold matches clap's internal `did_you_mean` so
+/// wt-synthesized "unrecognized subcommand" tips read identically to clap's
+/// native output — keep them aligned if clap ever changes it.
+pub(crate) fn did_you_mean(
+ query: &str,
+ candidates: impl IntoIterator<Item = String>,
+) -> Vec<String> {
+ let mut scored: Vec<(f64, String)> = candidates
+ .into_iter()
+ .map(|candidate| (strsim::jaro_winkler(query, &candidate), candidate))
+ .filter(|(score, _)| *score > 0.7)
+ .collect();
+ scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
+ let mut seen = std::collections::HashSet::new();
+ scored
+ .into_iter()
+ .filter(|(_, n)| seen.insert(n.clone()))
+ .map(|(_, n)| n)
+ .collect()
+}
+
/// 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.