From 1fc704c7298fd3a898655531ae231d30581b3790 Mon Sep 17 00:00:00 2001 From: Caznix Date: Fri, 6 Dec 2024 11:19:12 -0500 Subject: [PATCH] check command similarity --- engine/src/core/repl/mod.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/engine/src/core/repl/mod.rs b/engine/src/core/repl/mod.rs index 85dce9a..1545816 100644 --- a/engine/src/core/repl/mod.rs +++ b/engine/src/core/repl/mod.rs @@ -62,6 +62,24 @@ pub struct CommandList { pub aliases: RwLock>, } +fn check_similarity(target: &str, strings: &[String]) -> Option { + strings + .iter().filter(|s| { + target.chars().zip(s.chars()).any(|(c1, c2)| c1 == c2) + }) + .min_by_key(|s| { + let mut diff_count = 0; + for (c1, c2) in target.chars().zip(s.chars()) { + if c1 != c2 { + diff_count += 1; + } + } + diff_count += target.len().abs_diff(s.len()); + diff_count + }) + .cloned() +} + impl CommandList { fn new() -> Self { CommandList { @@ -131,6 +149,25 @@ impl CommandList { } } else { eprintln!("Command: '{}' was not found", name.red().italic()); + + let most_similar = check_similarity( + &name, + &self + .commands + .read() + .iter() + .map(|cmd| cmd.name.to_string()) + .collect::>(), + ); + match most_similar { + Some(similar) => { + eprintln!( + "Did you mean: '{}'?", + similar.green().italic().bold() + ); + } + None => {} + } } } }