Skip to content

Commit

Permalink
feat: suggest fuzzy matches in case of unrecognized arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
aminya committed Nov 12, 2023
1 parent 7c4d1e6 commit b05506b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
1 change: 1 addition & 0 deletions argh/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ readme = "README.md"
[dependencies]
argh_shared = { version = "0.1.12", path = "../argh_shared" }
argh_derive = { version = "0.1.12", path = "../argh_derive" }
rust-fuzzy-search = "0.1.1"

[dev-dependencies]
once_cell = "1.10.0"
Expand Down
30 changes: 27 additions & 3 deletions argh/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,8 @@ pub type SubCommandInfo = argh_shared::SubCommandInfo<'static>;

pub use argh_shared::{ErrorCodeInfo, FlagInfo, FlagInfoKind, Optionality, PositionalInfo};

use rust_fuzzy_search::fuzzy_search_best_n;

/// Structured information about the command line arguments.
pub trait ArgsInfo {
/// Returns the argument info.
Expand Down Expand Up @@ -972,7 +974,13 @@ impl<'a> ParseStructOptions<'a> {
.arg_to_slot
.iter()
.find_map(|&(name, pos)| if name == arg { Some(pos) } else { None })
.ok_or_else(|| unrecognized_argument(arg))?;
.ok_or_else(|| {
unrecognized_argument(
arg,
self.arg_to_slot,
&vec!["--help".to_owned(), "help".to_owned()],
)
})?;

match self.slots[pos] {
ParseStructOption::Flag(ref mut b) => b.set_flag(arg),
Expand All @@ -992,8 +1000,24 @@ impl<'a> ParseStructOptions<'a> {
}
}

fn unrecognized_argument(x: &str) -> String {
["Unrecognized argument: ", x, "\n"].concat()
fn unrecognized_argument(
given: &str,
arg_to_slot: &[(&str, usize)],
extra_suggestions: &[String],
) -> String {
// get the list of available arguments
let available = arg_to_slot
.iter()
.map(|(name, _pos)| *name)
.chain(extra_suggestions.iter().map(|s| s.as_str()))
.collect::<Vec<&str>>();

if available.is_empty() {
return format!("Unrecognized argument: \"{}\"", given);
}

let suggestions = fuzzy_search_best_n(given, &available, 1);
format!("Unrecognized argument: \"{}\". Did you mean \"{}\"?", given, suggestions[0].0)
}

// `--` or `-` options, including a mutable reference to their value.
Expand Down

0 comments on commit b05506b

Please sign in to comment.