Skip to content

Commit bf06e6f

Browse files
authored
Merge pull request #5974 from kryvashek/support-clearing-args-matches
Support clearing args matches
2 parents 9ebef15 + 5d357ad commit bf06e6f

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

clap_builder/src/parser/matches/arg_matches.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1226,6 +1226,18 @@ impl ArgMatches {
12261226
let presence = self.args.contains_key(id);
12271227
Ok(presence)
12281228
}
1229+
1230+
/// Clears the values for the given `id`
1231+
///
1232+
/// Alternative to [`try_remove_*`][ArgMatches::try_remove_one] when the type is not known.
1233+
///
1234+
/// Returns `Err([``MatchesError``])` if the given `id` isn't valid for current `ArgMatches` instance.
1235+
///
1236+
/// Returns `Ok(true)` if there were any matches with the given `id`, `Ok(false)` otherwise.
1237+
pub fn try_clear_id(&mut self, id: &str) -> Result<bool, MatchesError> {
1238+
ok!(self.verify_arg(id));
1239+
Ok(self.args.remove_entry(id).is_some())
1240+
}
12291241
}
12301242

12311243
// Private methods
@@ -2052,4 +2064,37 @@ mod tests {
20522064
let b = b_index.into_iter().zip(b_value).rev().collect::<Vec<_>>();
20532065
dbg!(b);
20542066
}
2067+
2068+
#[test]
2069+
fn delete_id_without_returning() {
2070+
let mut matches = crate::Command::new("myprog")
2071+
.arg(crate::Arg::new("a").short('a').action(ArgAction::Append))
2072+
.arg(crate::Arg::new("b").short('b').action(ArgAction::Append))
2073+
.arg(crate::Arg::new("c").short('c').action(ArgAction::Append))
2074+
.try_get_matches_from(vec!["myprog", "-b1", "-a1", "-b2"])
2075+
.unwrap();
2076+
let matches_ids_count = matches.ids().count();
2077+
assert_eq!(matches_ids_count, 2);
2078+
2079+
let _ = matches
2080+
.try_clear_id("d")
2081+
.expect_err("should fail due to there is no arg 'd'");
2082+
2083+
let c_was_presented = matches
2084+
.try_clear_id("c")
2085+
.expect("doesn't fail because there is no matches for 'c' argument");
2086+
assert!(!c_was_presented);
2087+
let matches_ids_count = matches.ids().count();
2088+
assert_eq!(matches_ids_count, 2);
2089+
2090+
let b_was_presented = matches.try_clear_id("b").unwrap();
2091+
assert!(b_was_presented);
2092+
let matches_ids_count = matches.ids().count();
2093+
assert_eq!(matches_ids_count, 1);
2094+
2095+
let a_was_presented = matches.try_clear_id("a").unwrap();
2096+
assert!(a_was_presented);
2097+
let matches_ids_count = matches.ids().count();
2098+
assert_eq!(matches_ids_count, 0);
2099+
}
20552100
}

0 commit comments

Comments
 (0)