Skip to content

Commit

Permalink
feat(parser): Provide convenience accessor for Counts
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Sep 2, 2022
1 parent 3c91438 commit d2a1f5a
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 10 deletions.
7 changes: 1 addition & 6 deletions examples/tutorial_builder/03_01_flag_count.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,5 @@ fn main() {
.arg(arg!(-v - -verbose).action(ArgAction::Count))
.get_matches();

println!(
"verbose: {:?}",
matches
.get_one::<u8>("verbose")
.expect("Count always defaulted")
);
println!("verbose: {:?}", matches.get_count("verbose"));
}
8 changes: 4 additions & 4 deletions src/builder/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,16 +183,16 @@ pub enum ArgAction {
/// assert!(matches.contains_id("flag"));
/// assert_eq!(matches.occurrences_of("flag"), 0);
/// assert_eq!(
/// matches.get_one::<u8>("flag").copied(),
/// Some(2)
/// matches.get_count("flag"),
/// 2
/// );
///
/// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap();
/// assert!(matches.contains_id("flag"));
/// assert_eq!(matches.occurrences_of("flag"), 0);
/// assert_eq!(
/// matches.get_one::<u8>("flag").copied(),
/// Some(0)
/// matches.get_count("flag"),
/// 0
/// );
/// ```
Count,
Expand Down
31 changes: 31 additions & 0 deletions src/parser/matches/arg_matches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,37 @@ impl ArgMatches {
MatchesError::unwrap(&internal_id, self.try_get_one(id))
}

/// Gets the value of a specific [`ArgAction::Count`][crate::ArgAction::Count] flag
///
/// # Panic
///
/// If the argument's action is not [`ArgAction::Count`][crate::ArgAction::Count]
///
/// # Examples
///
/// ```rust
/// # use clap::Command;
/// # use clap::Arg;
/// let cmd = Command::new("mycmd")
/// .arg(
/// Arg::new("flag")
/// .long("flag")
/// .action(clap::ArgAction::Count)
/// );
///
/// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap();
/// assert_eq!(
/// matches.get_count("flag"),
/// 2
/// );
/// ```
#[track_caller]
pub fn get_count(&self, id: &str) -> u8 {
*self
.get_one::<u8>(id)
.expect("ArgAction::Count is defaulted")
}

/// Iterate over values of a specific option or positional argument.
///
/// i.e. an argument that takes multiple values at runtime.
Expand Down

0 comments on commit d2a1f5a

Please sign in to comment.