Skip to content

Commit

Permalink
fix: Resolve conflicting name inference if from aliases
Browse files Browse the repository at this point in the history
Signed-off-by: Alex Saveau <[email protected]>
  • Loading branch information
Alex Saveau committed Jul 19, 2023
1 parent 18f0ad4 commit 2a7d6f1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
20 changes: 12 additions & 8 deletions clap_builder/src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -530,14 +530,18 @@ impl<'cmd> Parser<'cmd> {
if self.cmd.is_infer_subcommands_set() {
// For subcommand `test`, we accepts it's prefix: `t`, `te`,
// `tes` and `test`.
let v = self
.cmd
.all_subcommand_names()
.filter(|s| s.starts_with(arg))
.collect::<Vec<_>>();

if v.len() == 1 {
return Some(v[0]);
let mut iter = self.cmd.get_subcommands().filter_map(|s| {
if s.get_name().starts_with(arg) {
return Some(s.get_name());
}

s.get_all_aliases().find(|s| s.starts_with(arg))
});

if let name @ Some(_) = iter.next() {
if iter.next().is_none() {
return name;
}
}

// If there is any ambiguity, fallback to non-infer subcommand
Expand Down
10 changes: 10 additions & 0 deletions tests/builder/app_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,16 @@ fn infer_subcommands_pass_exact_match() {
assert_eq!(m.subcommand_name(), Some("test"));
}

#[test]
fn infer_subcommands_pass_conflicting_aliases() {
let m = Command::new("prog")
.infer_subcommands(true)
.subcommand(Command::new("test").aliases(["testa", "t", "testb"]))
.try_get_matches_from(vec!["prog", "te"])
.unwrap();
assert_eq!(m.subcommand_name(), Some("test"));
}

#[cfg(feature = "suggestions")]
#[test]
fn infer_subcommands_fail_suggestions() {
Expand Down

0 comments on commit 2a7d6f1

Please sign in to comment.