Merge pull request #2775 from patrick-gu/master

Apply `value_delimiter` to default values
This commit is contained in:
Pavan Kumar Sunkara 2021-09-19 00:55:39 +01:00 committed by GitHub
commit a42a97a566
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 2 deletions

View file

@ -1685,6 +1685,21 @@ impl<'help, 'app> Parser<'help, 'app> {
debug!("Parser::add_value: doesn't have conditional defaults"); debug!("Parser::add_value: doesn't have conditional defaults");
} }
fn process_default_vals(arg: &Arg<'_>, default_vals: &[&OsStr]) -> Vec<OsString> {
if let Some(delim) = arg.val_delim {
let mut vals = vec![];
for val in default_vals {
let val = RawOsStr::new(val);
for val in val.split(delim) {
vals.push(val.to_os_str().into_owned());
}
}
vals
} else {
default_vals.iter().map(OsString::from).collect()
}
}
if !arg.default_vals.is_empty() { if !arg.default_vals.is_empty() {
debug!("Parser::add_value:iter:{}: has default vals", arg.name); debug!("Parser::add_value:iter:{}: has default vals", arg.name);
if matcher.get(&arg.id).is_some() { if matcher.get(&arg.id).is_some() {
@ -1695,7 +1710,7 @@ impl<'help, 'app> Parser<'help, 'app> {
self.add_multiple_vals_to_arg( self.add_multiple_vals_to_arg(
arg, arg,
arg.default_vals.iter().map(OsString::from), process_default_vals(arg, &arg.default_vals).into_iter(),
matcher, matcher,
ty, ty,
false, false,
@ -1723,7 +1738,7 @@ impl<'help, 'app> Parser<'help, 'app> {
); );
self.add_multiple_vals_to_arg( self.add_multiple_vals_to_arg(
arg, arg,
arg.default_missing_vals.iter().map(OsString::from), process_default_vals(arg, &arg.default_missing_vals).into_iter(),
matcher, matcher,
ty, ty,
false, false,

View file

@ -651,3 +651,38 @@ fn required_args_with_default_values() {
.arg(Arg::new("arg").required(true).default_value("value")) .arg(Arg::new("arg").required(true).default_value("value"))
.try_get_matches(); .try_get_matches();
} }
#[test]
fn with_value_delimiter() {
let app = App::new("multiple_values").arg(
Arg::new("option")
.long("option")
.about("multiple options")
.value_delimiter(';')
.default_value("first;second"),
);
let matches = app.get_matches_from(vec![""]);
assert_eq!(
matches.values_of("option").unwrap().collect::<Vec<_>>(),
["first", "second"]
);
}
#[test]
fn missing_with_value_delimiter() {
let app = App::new("program").arg(
Arg::new("option")
.long("option")
.value_delimiter(';')
.default_missing_values(&["value1;value2;value3", "value4;value5"]),
);
let matches = app.get_matches_from(vec!["program", "--option"]);
assert_eq!(
matches.values_of("option").unwrap().collect::<Vec<_>>(),
["value1", "value2", "value3", "value4", "value5"]
);
}