From 50a58e98eb95ef5352908600ee970efd35b92a0b Mon Sep 17 00:00:00 2001 From: Ed Page Date: Tue, 1 Feb 2022 15:17:49 -0600 Subject: [PATCH] feat(parser): Check if args were present In clap2, `ArgMatches.args` was public but hidden. We made it private in clap3, giving us more implementation flexibility but many people relied on it, like to short-circuit defaulting, providing their own `ArgRequiredElseHelp`, etc. The main problem was how to expose this - If we think of `ArgMatches` as a container (a DAG), should we have an `is_empty` and what all is included in that, like subcommands? - If we focus on only args, what term how do we refer to this to convey the right intent? In the end, I realized that this aligns most with our existing `is_present` check and reporting if args are present fits the best within the existing API. I looked into also exposing iterating over the args (`present_arg_ids`) but we have no way to expose the Id. The Id is currently private and if we made it public, it can't be used to access any arg because it can't implement `Key`. This supersedes #3265 --- src/parse/matches/arg_matches.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/parse/matches/arg_matches.rs b/src/parse/matches/arg_matches.rs index edbdb91c9a3..4f4b25b51c2 100644 --- a/src/parse/matches/arg_matches.rs +++ b/src/parse/matches/arg_matches.rs @@ -80,6 +80,29 @@ pub struct ArgMatches { } impl ArgMatches { + /// Check if any args were present on the command line + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let mut app = App::new("myapp") + /// .arg(Arg::new("output") + /// .takes_value(true)); + /// + /// let m = app + /// .try_get_matches_from_mut(vec!["myapp", "something"]) + /// .unwrap(); + /// assert!(m.args_present()); + /// + /// let m = app + /// .try_get_matches_from_mut(vec!["myapp"]) + /// .unwrap(); + /// assert!(! m.args_present()); + pub fn args_present(&self) -> bool { + !self.args.is_empty() + } + /// Gets the value of a specific option or positional argument. /// /// i.e. an argument that [takes an additional value][crate::Arg::takes_value] at runtime.