Skip to content

Commit

Permalink
fix(derive): Support SubcommandsNegateReqs
Browse files Browse the repository at this point in the history
Before there was no way to make `SubcommandsNegateReqs` with
`clap_derive` because it required a required field with a sentinel value
for when the required part was negated.  We blocked that.

This turned out simpler than I expected.

This came out of the discussion for clap-rs#2255 but that issue is more
specifically about the panic, so not closing it.
  • Loading branch information
epage committed Oct 5, 2021
1 parent 62eff1f commit 5697507
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
3 changes: 0 additions & 3 deletions clap_derive/src/attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -717,9 +717,6 @@ impl Attrs {
if let Some(m) = res.find_method("default_value") {
abort!(m.name, "default_value is meaningless for Option")
}
if let Some(m) = res.find_method("required") {
abort!(m.name, "required is meaningless for Option")
}
}
Ty::OptionOption => {
if res.is_positional() {
Expand Down
39 changes: 39 additions & 0 deletions clap_derive/tests/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,3 +298,42 @@ fn two_optional_vecs() {

assert_eq!(Opt { arg: None, b: None }, Opt::parse_from(&["test"]));
}

#[test]
fn required_option_type() {
#[derive(Debug, PartialEq, Eq, Clap)]
#[clap(setting(clap::AppSettings::SubcommandsNegateReqs))]
struct Opt {
#[clap(required = true)]
req_str: Option<String>,

#[clap(subcommand)]
cmd: Option<SubCommands>,
}

#[derive(Debug, PartialEq, Eq, Clap)]
enum SubCommands {
ExSub {
#[clap(short, long, parse(from_occurrences))]
verbose: u8,
},
}

assert_eq!(
Opt {
req_str: Some(("arg").into()),
cmd: None,
},
Opt::parse_from(&["test", "arg"])
);

assert_eq!(
Opt {
req_str: None,
cmd: Some(SubCommands::ExSub { verbose: 1 }),
},
Opt::parse_from(&["test", "ex-sub", "-v"])
);

assert!(Opt::try_parse_from(&["test"]).is_err());
}

0 comments on commit 5697507

Please sign in to comment.