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 3ec2f0f commit 80ec011
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 @@ -10,10 +10,5 @@ fn main() {
)
.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 @@ -193,15 +193,15 @@ pub enum ArgAction {
/// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap();
/// assert!(matches.contains_id("flag"));
/// 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.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 @@ -112,6 +112,37 @@ impl ArgMatches {
MatchesError::unwrap(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 80ec011

Please sign in to comment.