Skip to content

Commit

Permalink
fix(parser): Ensure subcommand flags can conflict
Browse files Browse the repository at this point in the history
Fixes #5297
  • Loading branch information
epage committed Jan 11, 2024
1 parent a7e04a5 commit f529ec3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
11 changes: 11 additions & 0 deletions clap_builder/src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
24 changes: 20 additions & 4 deletions tests/builder/conflicts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit f529ec3

Please sign in to comment.