Fixes arg having required_if on default values

This commit is contained in:
Pavan Kumar Sunkara 2021-10-26 20:44:28 +01:00
parent 130dcbfdd9
commit a88562c12b
No known key found for this signature in database
GPG key ID: 7149B807A81DE336
2 changed files with 47 additions and 6 deletions

View file

@ -4,7 +4,7 @@ use crate::{
output::Usage,
parse::{
errors::{Error, ErrorKind, Result as ClapResult},
ArgMatcher, MatchedArg, ParseState, Parser,
ArgMatcher, MatchedArg, ParseState, Parser, ValueType,
},
util::{ChildGraph, Id},
INTERNAL_ERROR_MSG, INVALID_UTF8,
@ -564,16 +564,21 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
for a in self.p.app.args.args() {
for (other, val) in &a.r_ifs {
if let Some(ma) = matcher.get(other) {
if ma.contains_val(val) && !matcher.contains(&a.id) {
if ma.contains_val(val)
&& !matches!(ma.ty, ValueType::DefaultValue)
&& !matcher.contains(&a.id)
{
return self.missing_required_error(matcher, vec![a.id.clone()]);
}
}
}
let match_all = a
.r_ifs_all
.iter()
.all(|(other, val)| matcher.get(other).map_or(false, |ma| ma.contains_val(val)));
let match_all = a.r_ifs_all.iter().all(|(other, val)| {
matcher.get(other).map_or(false, |ma| {
ma.contains_val(val) && !matches!(ma.ty, ValueType::DefaultValue)
})
});
if match_all && !a.r_ifs_all.is_empty() && !matcher.contains(&a.id) {
return self.missing_required_error(matcher, vec![a.id.clone()]);
}

View file

@ -1160,3 +1160,39 @@ fn group_requires_with_default_value() {
assert_eq!(m.value_of("opt"), Some("default"));
assert!(!m.is_present("flag"));
}
#[test]
fn required_if_eq_on_default_value() {
let result = App::new("prog")
.arg(Arg::new("opt").long("opt").default_value("default"))
.arg(
Arg::new("flag")
.long("flag")
.required_if_eq("opt", "default"),
)
.try_get_matches_from(vec!["myprog"]);
assert!(result.is_ok(), "{:?}", result.unwrap());
let m = result.unwrap();
assert_eq!(m.value_of("opt"), Some("default"));
assert!(!m.is_present("flag"));
}
#[test]
fn required_if_eq_all_on_default_value() {
let result = App::new("prog")
.arg(Arg::new("opt").long("opt").default_value("default"))
.arg(
Arg::new("flag")
.long("flag")
.required_if_eq_all(&[("opt", "default")]),
)
.try_get_matches_from(vec!["myprog"]);
assert!(result.is_ok(), "{:?}", result.unwrap());
let m = result.unwrap();
assert_eq!(m.value_of("opt"), Some("default"));
assert!(!m.is_present("flag"));
}