fix: Make long subcommand flag inference consistent

Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
This commit is contained in:
Alex Saveau 2023-09-21 20:32:12 -07:00
parent c2b8ec3bd3
commit a76789eb8b
No known key found for this signature in database
GPG key ID: 3F8D5B16EB169D48
2 changed files with 22 additions and 22 deletions

View file

@ -573,28 +573,29 @@ impl<'cmd> Parser<'cmd> {
fn possible_long_flag_subcommand(&self, arg: &str) -> Option<&str> { fn possible_long_flag_subcommand(&self, arg: &str) -> Option<&str> {
debug!("Parser::possible_long_flag_subcommand: arg={arg:?}"); debug!("Parser::possible_long_flag_subcommand: arg={arg:?}");
if self.cmd.is_infer_subcommands_set() { if self.cmd.is_infer_subcommands_set() {
let options = self let mut iter = self.cmd.get_subcommands().filter_map(|sc| {
.cmd sc.get_long_flag().and_then(|long| {
.get_subcommands() if long.starts_with(arg) {
.fold(Vec::new(), |mut options, sc| { Some(sc.get_name())
if let Some(long) = sc.get_long_flag() { } else {
if long.starts_with(arg) { sc.get_all_long_flag_aliases().find_map(|alias| {
options.push(long); if alias.starts_with(arg) {
} Some(sc.get_name())
options.extend(sc.get_all_aliases().filter(|alias| alias.starts_with(arg))) } else {
None
}
})
} }
options })
}); });
if options.len() == 1 {
return Some(options[0]);
}
for sc in options { if let name @ Some(_) = iter.next() {
if sc == arg { if iter.next().is_none() {
return Some(sc); return name;
} }
} }
} else if let Some(sc_name) = self.cmd.find_long_subcmd(arg) { }
if let Some(sc_name) = self.cmd.find_long_subcmd(arg) {
return Some(sc_name); return Some(sc_name);
} }
None None

View file

@ -264,7 +264,6 @@ fn infer_subcommands_pass_conflicting_aliases() {
} }
#[test] #[test]
#[should_panic(expected = "internal error")]
fn infer_long_flag_pass_conflicting_aliases() { fn infer_long_flag_pass_conflicting_aliases() {
let m = Command::new("prog") let m = Command::new("prog")
.infer_subcommands(true) .infer_subcommands(true)
@ -273,12 +272,12 @@ fn infer_long_flag_pass_conflicting_aliases() {
.long_flag("test") .long_flag("test")
.long_flag_aliases(["testa", "t", "testb"]), .long_flag_aliases(["testa", "t", "testb"]),
) )
.try_get_matches_from(vec!["prog", "--te"]); .try_get_matches_from(vec!["prog", "--te"])
assert!(m.is_err(), "{:#?}", m.unwrap()); .unwrap();
assert_eq!(m.subcommand_name(), Some("c"));
} }
#[test] #[test]
#[should_panic(expected = "internal error")]
fn infer_long_flag() { fn infer_long_flag() {
let m = Command::new("prog") let m = Command::new("prog")
.infer_subcommands(true) .infer_subcommands(true)