mirror of
https://github.com/clap-rs/clap
synced 2024-11-10 14:54:15 +00:00
feat(parser): Provide convenience accessor for Counts
This commit is contained in:
parent
3ec2f0f795
commit
80ec011b6e
3 changed files with 36 additions and 10 deletions
|
@ -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"));
|
||||
}
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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.
|
||||
|
|
Loading…
Reference in a new issue