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 Sep 25, 2023
1 parent e5c6993 commit c2b8ec3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
25 changes: 15 additions & 10 deletions clap_builder/src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,19 +544,24 @@ 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<_>>();
let mut iter = self.cmd.get_subcommands().filter_map(|s| {
if s.get_name().starts_with(arg) {
return Some(s.get_name());
}

if v.len() == 1 {
return Some(v[0]);
}
// Use find here instead of chaining the iterator because we want to accept
// conflicts in aliases.
s.get_all_aliases().find(|s| s.starts_with(arg))
});

// If there is any ambiguity, fallback to non-infer subcommand
// search.
if let name @ Some(_) = iter.next() {
if iter.next().is_none() {
return name;
}
}
}
// Don't use an else here because we want inference to support exact matching even if
// there are conflicts.
if let Some(sc) = self.cmd.find_subcommand(arg) {
return Some(sc.get_name());
}
Expand Down
5 changes: 3 additions & 2 deletions tests/builder/app_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,9 @@ 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"]);
assert!(m.is_err(), "{:#?}", m.unwrap());
.try_get_matches_from(vec!["prog", "te"])
.unwrap();
assert_eq!(m.subcommand_name(), Some("test"));
}

#[test]
Expand Down

0 comments on commit c2b8ec3

Please sign in to comment.