Skip to content

Commit

Permalink
fix(parser): Apply conditional defaults
Browse files Browse the repository at this point in the history
Now that we can store constants for flags, we can apply defaults for
flags too.

Fixes #3294
  • Loading branch information
epage committed Jun 1, 2022
1 parent 67f47c5 commit 06ea572
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 6 deletions.
7 changes: 1 addition & 6 deletions src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1385,12 +1385,7 @@ impl<'help, 'cmd> Parser<'help, 'cmd> {
fn add_defaults(&self, matcher: &mut ArgMatcher) -> ClapResult<()> {
debug!("Parser::add_defaults");

for arg in self.cmd.get_opts() {
debug!("Parser::add_defaults:iter:{}:", arg.name);
self.add_default_value(arg, matcher)?;
}

for arg in self.cmd.get_positionals() {
for arg in self.cmd.get_arguments() {
debug!("Parser::add_defaults:iter:{}:", arg.name);
self.add_default_value(arg, matcher)?;
}
Expand Down
49 changes: 49 additions & 0 deletions tests/builder/action.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use clap::builder::ArgAction;
use clap::Arg;
use clap::Command;

#[test]
fn set_true_with_default_value_if_present() {
let cmd = Command::new("test")
.arg(
Arg::new("mammal")
.long("mammal")
.action(ArgAction::SetTrue)
.default_value_if("dog", None, Some("true")),
)
.arg(Arg::new("dog").long("dog").action(ArgAction::SetTrue));

let matches = cmd.clone().try_get_matches_from(["test", "--dog"]).unwrap();
assert_eq!(*matches.get_one::<bool>("dog").unwrap(), true);
assert_eq!(*matches.get_one::<bool>("mammal").unwrap(), true);

let matches = cmd
.clone()
.try_get_matches_from(["test", "--mammal"])
.unwrap();
assert_eq!(matches.get_one::<bool>("dog"), None);
assert_eq!(*matches.get_one::<bool>("mammal").unwrap(), true);
}

#[test]
fn set_true_with_default_value_if_value() {
let cmd = Command::new("test")
.arg(
Arg::new("mammal")
.long("mammal")
.action(ArgAction::SetTrue)
.default_value_if("dog", Some("true"), Some("true")),
)
.arg(Arg::new("dog").long("dog").action(ArgAction::SetTrue));

let matches = cmd.clone().try_get_matches_from(["test", "--dog"]).unwrap();
assert_eq!(*matches.get_one::<bool>("dog").unwrap(), true);
assert_eq!(*matches.get_one::<bool>("mammal").unwrap(), true);

let matches = cmd
.clone()
.try_get_matches_from(["test", "--mammal"])
.unwrap();
assert_eq!(matches.get_one::<bool>("dog"), None);
assert_eq!(*matches.get_one::<bool>("mammal").unwrap(), true);
}
1 change: 1 addition & 0 deletions tests/builder/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod action;
mod app_from_crate;
mod app_settings;
mod arg_aliases;
Expand Down

0 comments on commit 06ea572

Please sign in to comment.