]>
git.proxmox.com Git - rustc.git/blob - vendor/clap/src/parse/features/suggestions.rs
1 #[cfg(feature = "suggestions")]
2 use std
::cmp
::Ordering
;
5 use crate::build
::Command
;
7 /// Produces multiple strings from a given list of possible values which are similar
8 /// to the passed in value `v` within a certain confidence by least confidence.
9 /// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield
10 /// `Some("foo")`, whereas "blark" would yield `None`.
11 #[cfg(feature = "suggestions")]
12 pub(crate) fn did_you_mean
<T
, I
>(v
: &str, possible_values
: I
) -> Vec
<String
>
15 I
: IntoIterator
<Item
= T
>,
17 let mut candidates
: Vec
<(f64, String
)> = possible_values
19 .map(|pv
| (strsim
::jaro_winkler(v
, pv
.as_ref()), pv
.as_ref().to_owned()))
20 .filter(|(confidence
, _
)| *confidence
> 0.8)
22 candidates
.sort_by(|a
, b
| a
.0.partial_cmp(&b
.0).unwrap_or(Ordering
::Equal
));
23 candidates
.into_iter().map(|(_
, pv
)| pv
).collect()
26 #[cfg(not(feature = "suggestions"))]
27 pub(crate) fn did_you_mean
<T
, I
>(_
: &str, _
: I
) -> Vec
<String
>
30 I
: IntoIterator
<Item
= T
>,
35 /// Returns a suffix that can be empty, or is the standard 'did you mean' phrase
36 pub(crate) fn did_you_mean_flag
<'a
, 'help
, I
, T
>(
38 remaining_args
: &[&str],
40 subcommands
: impl IntoIterator
<Item
= &'a
mut Command
<'help
>>,
41 ) -> Option
<(String
, Option
<String
>)>
45 I
: IntoIterator
<Item
= T
>,
47 use crate::mkeymap
::KeyType
;
49 match did_you_mean(arg
, longs
).pop() {
50 Some(candidate
) => Some((candidate
, None
)),
53 .filter_map(|subcommand
| {
56 let longs
= subcommand
.get_keymap().keys().filter_map(|a
| {
57 if let KeyType
::Long(v
) = a
{
58 Some(v
.to_string_lossy().into_owned())
64 let subcommand_name
= subcommand
.get_name();
66 let candidate
= did_you_mean(arg
, longs
).pop()?
;
67 let score
= remaining_args
.iter().position(|x
| *x
== subcommand_name
)?
;
68 Some((score
, (candidate
, Some(subcommand_name
.to_string()))))
70 .min_by_key(|(x
, _
)| *x
)
71 .map(|(_
, suggestion
)| suggestion
),
75 #[cfg(all(test, features = "suggestions"))]
80 fn possible_values_match() {
81 let p_vals
= ["test", "possible", "values"];
82 assert_eq
!(did_you_mean("tst", p_vals
.iter()), Some("test"));
86 fn possible_values_match() {
87 let p_vals
= ["test", "temp"];
88 assert_eq
!(did_you_mean("te", p_vals
.iter()), Some("test"));
92 fn possible_values_nomatch() {
93 let p_vals
= ["test", "possible", "values"];
94 assert
!(did_you_mean("hahaahahah", p_vals
.iter()).is_none());
99 let p_vals
= ["test", "possible", "values"];
101 did_you_mean_flag("tst", p_vals
.iter(), []),