Skip to content

Commit 389fbe8

Browse files
committed
feat(builder): Allow flags to take num_args=0..=1
1 parent c395d02 commit 389fbe8

File tree

4 files changed

+21
-10
lines changed

4 files changed

+21
-10
lines changed

clap_builder/src/builder/action.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -376,8 +376,8 @@ impl ArgAction {
376376
match self {
377377
Self::Set => ValueRange::FULL,
378378
Self::Append => ValueRange::FULL,
379-
Self::SetTrue => ValueRange::EMPTY,
380-
Self::SetFalse => ValueRange::EMPTY,
379+
Self::SetTrue => ValueRange::OPTIONAL,
380+
Self::SetFalse => ValueRange::OPTIONAL,
381381
Self::Count => ValueRange::EMPTY,
382382
Self::Help => ValueRange::EMPTY,
383383
Self::HelpShort => ValueRange::EMPTY,

clap_builder/src/builder/range.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,12 @@ impl ValueRange {
1818
end_inclusive: 1,
1919
};
2020

21+
#[cfg(debug_assertions)]
22+
pub(crate) const OPTIONAL: Self = Self {
23+
start_inclusive: 0,
24+
end_inclusive: 1,
25+
};
26+
2127
pub(crate) const FULL: Self = Self {
2228
start_inclusive: 0,
2329
end_inclusive: usize::MAX,

tests/builder/flags.rs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -225,19 +225,25 @@ fn leading_dash_stripped() {
225225

226226
#[test]
227227
fn optional_value() {
228-
let cmd = Command::new("flag").args([arg!(-f --flag "some flag").action(ArgAction::SetTrue)]);
228+
let cmd = Command::new("flag").args([arg!(-f --flag "some flag")
229+
.action(ArgAction::SetTrue)
230+
.num_args(0..=1)]);
229231

230232
let m = cmd.clone().try_get_matches_from(vec![""]).unwrap();
231233
assert!(!*m.get_one::<bool>("flag").expect("defaulted by clap"));
232234

233235
let m = cmd.clone().try_get_matches_from(vec!["", "-f"]).unwrap();
234236
assert!(*m.get_one::<bool>("flag").expect("defaulted by clap"));
235237

236-
cmd.clone()
237-
.try_get_matches_from(vec!["", "-f", "true"])
238-
.unwrap_err();
239-
240-
cmd.clone()
238+
let m = cmd
239+
.clone()
241240
.try_get_matches_from(vec!["", "-f", "false"])
242-
.unwrap_err();
241+
.unwrap();
242+
assert!(!*m.get_one::<bool>("flag").expect("defaulted by clap"));
243+
244+
let m = cmd
245+
.clone()
246+
.try_get_matches_from(vec!["", "-f", "true"])
247+
.unwrap();
248+
assert!(*m.get_one::<bool>("flag").expect("defaulted by clap"));
243249
}

tests/derive/flags.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,6 @@ fn unit_for_negation() {
331331
}
332332

333333
#[test]
334-
#[should_panic = "Argument `alice`'s action SetTrue is incompatible with `num_args(0..=1)`"]
335334
fn optional_value_flag() {
336335
#[derive(Parser, PartialEq, Eq, Debug)]
337336
struct Opt {

0 commit comments

Comments
 (0)