Skip to content

Commit

Permalink
refactor(assert): Be more specific than action.takes_values
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Feb 14, 2025
1 parent 80ea3e7 commit 32c119e
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 12 deletions.
15 changes: 15 additions & 0 deletions clap_builder/src/builder/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,21 @@ impl ArgAction {
}
}

#[cfg(debug_assertions)]
pub(crate) fn max_num_args(&self) -> ValueRange {
match self {
Self::Set => ValueRange::FULL,
Self::Append => ValueRange::FULL,
Self::SetTrue => ValueRange::EMPTY,
Self::SetFalse => ValueRange::EMPTY,
Self::Count => ValueRange::EMPTY,
Self::Help => ValueRange::EMPTY,
Self::HelpShort => ValueRange::EMPTY,
Self::HelpLong => ValueRange::EMPTY,
Self::Version => ValueRange::EMPTY,
}
}

pub(crate) fn default_num_args(&self) -> ValueRange {
match self {
Self::Set => ValueRange::SINGLE,
Expand Down
17 changes: 8 additions & 9 deletions clap_builder/src/builder/debug_asserts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -690,15 +690,14 @@ fn assert_arg(arg: &Arg) {
arg.get_id(),
);

if arg.is_takes_value_set() {
assert!(
arg.get_action().takes_values(),
"Argument `{}`'s action {:?} is incompatible with `num_args({:?})`",
arg.get_id(),
arg.get_action(),
arg.get_num_args().unwrap_or(1.into())
);
}
assert!(
arg.get_num_args().unwrap_or(1.into()).max_values()
<= arg.get_action().max_num_args().max_values(),
"Argument `{}`'s action {:?} is incompatible with `num_args({:?})`",
arg.get_id(),
arg.get_action(),
arg.get_num_args().unwrap_or(1.into())
);
if let Some(action_type_id) = arg.get_action().value_type_id() {
assert_eq!(
action_type_id,
Expand Down
9 changes: 6 additions & 3 deletions clap_builder/src/builder/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ impl ValueRange {
end_inclusive: 1,
};

pub(crate) const FULL: Self = Self {
start_inclusive: 0,
end_inclusive: usize::MAX,
};

/// Create a range
///
/// # Panics
Expand Down Expand Up @@ -135,9 +140,7 @@ impl From<std::ops::Range<usize>> for ValueRange {

impl From<std::ops::RangeFull> for ValueRange {
fn from(_: std::ops::RangeFull) -> Self {
let start_inclusive = 0;
let end_inclusive = usize::MAX;
Self::raw(start_inclusive, end_inclusive)
Self::FULL
}
}

Expand Down

0 comments on commit 32c119e

Please sign in to comment.