fix(parser): Ensure subcommand flags can conflict

Fixes #5297
This commit is contained in:
Ed Page 2024-01-11 10:25:57 -06:00
parent a7e04a53e4
commit f529ec398c
2 changed files with 31 additions and 4 deletions

View file

@ -454,6 +454,17 @@ impl<'cmd> Parser<'cmd> {
}
if let Some(ref pos_sc_name) = subcmd_name {
if self.cmd.is_args_conflicts_with_subcommands_set() && valid_arg_found {
return Err(ClapError::subcommand_conflict(
self.cmd,
pos_sc_name.clone(),
matcher
.arg_ids()
.map(|id| self.cmd.find(id).unwrap().to_string())
.collect(),
Usage::new(self.cmd).create_usage_with_title(&[]),
));
}
let sc_name = self
.cmd
.find_subcommand(pos_sc_name)

View file

@ -727,25 +727,41 @@ For more information, try '--help'.
#[test]
#[cfg(feature = "error-context")]
fn flag_conflicts_with_subcommand_long_flag() {
static CONFLICT_ERR: &str = "\
error: the subcommand 'sub' cannot be used with '--hello'
Usage: test [OPTIONS]
test <COMMAND>
For more information, try '--help'.
";
let cmd = Command::new("test")
.args_conflicts_with_subcommands(true)
.arg(arg!(--hello))
.subcommand(Command::new("sub").long_flag("sub"));
let res = cmd.try_get_matches_from(vec!["", "--hello", "--sub"]);
assert!(res.is_ok(), "error: {:?}", res.unwrap_err().kind());
utils::assert_output(cmd, "test --hello --sub", CONFLICT_ERR, true);
}
#[test]
#[cfg(feature = "error-context")]
fn flag_conflicts_with_subcommand_short_flag() {
static CONFLICT_ERR: &str = "\
error: the subcommand 'sub' cannot be used with '--hello'
Usage: test [OPTIONS]
test <COMMAND>
For more information, try '--help'.
";
let cmd = Command::new("test")
.args_conflicts_with_subcommands(true)
.arg(arg!(--hello))
.subcommand(Command::new("sub").short_flag('s'));
let res = cmd.try_get_matches_from(vec!["", "--hello", "-s"]);
assert!(res.is_ok(), "error: {:?}", res.unwrap_err().kind());
utils::assert_output(cmd, "test --hello -s", CONFLICT_ERR, true);
}
#[test]