From d2a1f5a8f86be5cf8374db2f56533a6b8e93a624 Mon Sep 17 00:00:00 2001 From: Ed Page Date: Thu, 1 Sep 2022 19:19:55 -0500 Subject: [PATCH] feat(parser): Provide convenience accessor for Counts --- examples/tutorial_builder/03_01_flag_count.rs | 7 +---- src/builder/action.rs | 8 ++--- src/parser/matches/arg_matches.rs | 31 +++++++++++++++++++ 3 files changed, 36 insertions(+), 10 deletions(-) diff --git a/examples/tutorial_builder/03_01_flag_count.rs b/examples/tutorial_builder/03_01_flag_count.rs index 059a3f30256..7f23649d685 100644 --- a/examples/tutorial_builder/03_01_flag_count.rs +++ b/examples/tutorial_builder/03_01_flag_count.rs @@ -5,10 +5,5 @@ fn main() { .arg(arg!(-v - -verbose).action(ArgAction::Count)) .get_matches(); - println!( - "verbose: {:?}", - matches - .get_one::("verbose") - .expect("Count always defaulted") - ); + println!("verbose: {:?}", matches.get_count("verbose")); } diff --git a/src/builder/action.rs b/src/builder/action.rs index ab331429092..71a91a8b1b3 100644 --- a/src/builder/action.rs +++ b/src/builder/action.rs @@ -183,16 +183,16 @@ pub enum ArgAction { /// assert!(matches.contains_id("flag")); /// assert_eq!(matches.occurrences_of("flag"), 0); /// assert_eq!( - /// matches.get_one::("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::("flag").copied(), - /// Some(0) + /// matches.get_count("flag"), + /// 0 /// ); /// ``` Count, diff --git a/src/parser/matches/arg_matches.rs b/src/parser/matches/arg_matches.rs index d0df68441ff..69f96b92502 100644 --- a/src/parser/matches/arg_matches.rs +++ b/src/parser/matches/arg_matches.rs @@ -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::(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.