Skip to content

Commit 5d357ad

Browse files
asakhkryvashek
authored andcommitted
feat(parser): Added ArgMatches::try_clear_id()
Resolves [#5973](#5973)
1 parent 45d4088 commit 5d357ad

File tree

1 file changed

+23
-17
lines changed

1 file changed

+23
-17
lines changed

clap_builder/src/parser/matches/arg_matches.rs

Lines changed: 23 additions & 17 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
@@ -2065,30 +2077,24 @@ mod tests {
20652077
assert_eq!(matches_ids_count, 2);
20662078

20672079
let _ = matches
2068-
.try_remove_occurrences::<bool>("d")
2080+
.try_clear_id("d")
20692081
.expect_err("should fail due to there is no arg 'd'");
20702082

2071-
let values = matches.try_remove_occurrences::<bool>("c").expect(
2072-
"doesn't fail because there is no matches for 'c' argument thus nothing to downcast",
2073-
);
2074-
assert!(values.is_none());
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);
20752087
let matches_ids_count = matches.ids().count();
20762088
assert_eq!(matches_ids_count, 2);
20772089

2078-
let _ = matches
2079-
.try_remove_occurrences::<()>("b")
2080-
.expect_err("should fail due to impossible downcasting to ()");
2090+
let b_was_presented = matches.try_clear_id("b").unwrap();
2091+
assert!(b_was_presented);
20812092
let matches_ids_count = matches.ids().count();
2082-
assert_eq!(matches_ids_count, 2);
2083-
2084-
trait Remover: Any + Sync + Debug + 'static {
2085-
fn _noop(&self);
2086-
}
2093+
assert_eq!(matches_ids_count, 1);
20872094

2088-
let _ = matches
2089-
.try_remove_occurrences::<&dyn Remover>("a")
2090-
.expect_err("should fail due to impossible downcasting to &dyn Remover");
2095+
let a_was_presented = matches.try_clear_id("a").unwrap();
2096+
assert!(a_was_presented);
20912097
let matches_ids_count = matches.ids().count();
2092-
assert_eq!(matches_ids_count, 2);
2098+
assert_eq!(matches_ids_count, 0);
20932099
}
20942100
}

0 commit comments

Comments
 (0)