Skip to content

Commit

Permalink
fix(parser): Dont report missing flags as present
Browse files Browse the repository at this point in the history
When we switched flags to `ArgAction::SetTrue`,
we overlooked updating `args_present`.
Because of the default value for `ArgAction::SetTrue`,
`args_present` will always report true when a flag is defined.

I went with the trivial implementation for now.  We could proactively
track this but was unsure about correctness vs overhead and so I thought
I'd have those using it pay for it.

Looking over uses on github, this will fix a couple bugs but should
otherwise be unnoticeable.

Fixes #5860
  • Loading branch information
epage committed Feb 11, 2025
1 parent 225e0d8 commit 0ef80bb
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 2 deletions.
4 changes: 3 additions & 1 deletion clap_builder/src/parser/matches/arg_matches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -575,7 +575,9 @@ impl ArgMatches {
/// .unwrap();
/// assert!(! m.args_present());
pub fn args_present(&self) -> bool {
!self.args.is_empty()
self.args
.values()
.any(|v| v.source().map(|s| s.is_explicit()).unwrap_or(false))
}

/// Report where argument value came from
Expand Down
4 changes: 4 additions & 0 deletions clap_builder/src/util/flat_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ impl<K: PartialEq + Eq, V> FlatMap<K, V> {
self.keys.iter()
}

pub(crate) fn values(&self) -> std::slice::Iter<'_, V> {
self.values.iter()
}

pub(crate) fn iter(&self) -> Iter<'_, K, V> {
Iter {
keys: self.keys.iter(),
Expand Down
2 changes: 1 addition & 1 deletion tests/builder/arg_matches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ fn args_present_flag() {
let c = Command::new("test").arg(Arg::new("flag").long("flag").action(ArgAction::SetTrue));

let m = c.clone().try_get_matches_from(["test"]).unwrap();
assert!(m.args_present());
assert!(!m.args_present());

let m = c.clone().try_get_matches_from(["test", "--flag"]).unwrap();
assert!(m.args_present());
Expand Down

0 comments on commit 0ef80bb

Please sign in to comment.