Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support unsetting/removing the default if an option/flag is set #2296

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 41 additions & 16 deletions src/build/arg/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ pub struct Arg<'help> {
pub(crate) validator_os: Option<Arc<Mutex<ValidatorOs<'help>>>>,
pub(crate) val_delim: Option<char>,
pub(crate) default_vals: Vec<&'help OsStr>,
pub(crate) default_vals_ifs: VecMap<(Id, Option<&'help OsStr>, &'help OsStr)>,
pub(crate) default_vals_ifs: VecMap<(Id, Option<&'help OsStr>, Option<&'help OsStr>)>,
pub(crate) default_missing_vals: Vec<&'help OsStr>,
pub(crate) env: Option<(&'help OsStr, Option<OsString>)>,
pub(crate) terminator: Option<&'help str>,
Expand Down Expand Up @@ -2527,7 +2527,7 @@ impl<'help> Arg<'help> {
/// .long("flag"))
/// .arg(Arg::new("other")
/// .long("other")
/// .default_value_if("flag", None, "default"))
/// .default_value_if("flag", None, Some("default")))
/// .get_matches_from(vec![
/// "prog", "--flag"
/// ]);
Expand All @@ -2544,7 +2544,7 @@ impl<'help> Arg<'help> {
/// .long("flag"))
/// .arg(Arg::new("other")
/// .long("other")
/// .default_value_if("flag", None, "default"))
/// .default_value_if("flag", None, Some("default")))
/// .get_matches_from(vec![
/// "prog"
/// ]);
Expand All @@ -2562,7 +2562,7 @@ impl<'help> Arg<'help> {
/// .long("opt"))
/// .arg(Arg::new("other")
/// .long("other")
/// .default_value_if("opt", Some("special"), "default"))
/// .default_value_if("opt", Some("special"), Some("default")))
/// .get_matches_from(vec![
/// "prog", "--opt", "special"
/// ]);
Expand All @@ -2581,38 +2581,60 @@ impl<'help> Arg<'help> {
/// .long("opt"))
/// .arg(Arg::new("other")
/// .long("other")
/// .default_value_if("opt", Some("special"), "default"))
/// .default_value_if("opt", Some("special"), Some("default")))
/// .get_matches_from(vec![
/// "prog", "--opt", "hahaha"
/// ]);
///
/// assert_eq!(m.value_of("other"), None);
/// ```
///
/// We can also remove a default if the flag was set by setting `default` to `None`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs better phrasing. It does not explain things properly as it is right now.

///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("prog")
/// .arg(Arg::new("flag")
/// .long("flag"))
/// .arg(Arg::new("other")
/// .long("other")
/// .default_value("default")
/// .default_value_if("flag", None, None))
/// .get_matches_from(vec![
/// "prog", "--flag"
/// ]);
///
/// assert_eq!(m.value_of("other"), None);
/// ```
/// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
/// [`Arg::default_value`]: ./struct.Arg.html#method.default_value
pub fn default_value_if<T: Key>(
pub fn default_value_if<T: Key, S: Into<Option<&'help str>>>(
self,
arg_id: T,
val: Option<&'help str>,
default: &'help str,
default: S,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

type param should be D

) -> Self {
self.default_value_if_os(arg_id, val.map(OsStr::new), OsStr::new(default))
self.default_value_if_os(
arg_id,
val.map(OsStr::new),
default.into().map(|s| OsStr::new(s)),
)
}

/// Provides a conditional default value in the exact same manner as [`Arg::default_value_if`]
/// only using [`OsStr`]s instead.
///
/// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if
/// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
pub fn default_value_if_os<T: Key>(
pub fn default_value_if_os<T: Key, S: Into<Option<&'help OsStr>>>(
mut self,
arg_id: T,
val: Option<&'help OsStr>,
default: &'help OsStr,
default: S,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

type params should be D

) -> Self {
let l = self.default_vals_ifs.len();
self.default_vals_ifs
.insert(l, (arg_id.into(), val, default));
.insert(l, (arg_id.into(), val, default.into()));
pksunkara marked this conversation as resolved.
Show resolved Hide resolved
self.takes_value(true)
}

Expand Down Expand Up @@ -2700,12 +2722,14 @@ impl<'help> Arg<'help> {
/// ```
/// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
/// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if
pub fn default_value_ifs<T: Key>(
pub fn default_value_ifs<T: Key, S: Into<Option<&'help str>> + Copy>(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function needs documentation addition.

mut self,
ifs: &[(T, Option<&'help str>, &'help str)],
ifs: &[(T, Option<&'help str>, S)],
) -> Self {
for (arg, val, default) in ifs {
self = self.default_value_if_os(arg, val.map(OsStr::new), OsStr::new(*default));
let default: Option<&'help str> = (*default).into();
self =
self.default_value_if_os(arg, val.map(OsStr::new), default.map(|s| OsStr::new(s)));
}
self
}
Expand All @@ -2715,11 +2739,12 @@ impl<'help> Arg<'help> {
///
/// [`Arg::default_value_ifs`]: ./struct.Arg.html#method.default_value_ifs
/// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
pub fn default_value_ifs_os<T: Key>(
pub fn default_value_ifs_os<T: Key, S: Into<Option<&'help OsStr>> + Copy>(
mut self,
ifs: &[(T, Option<&'help OsStr>, &'help OsStr)],
ifs: &[(T, Option<&'help OsStr>, S)],
) -> Self {
for (arg, val, default) in ifs {
let default: Option<&'help OsStr> = (*default).into();
self = self.default_value_if_os(arg.key(), *val, default);
}
self
Expand Down
4 changes: 3 additions & 1 deletion src/parse/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1486,7 +1486,9 @@ impl<'help, 'app> Parser<'help, 'app> {
};

if add {
self.add_val_to_arg(arg, &ArgStr::new(default), matcher, ty)?;
if let Some(default) = default {
self.add_val_to_arg(arg, &ArgStr::new(default), matcher, ty)?;
}
done = true;
break;
}
Expand Down
88 changes: 88 additions & 0 deletions tests/default_vals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,78 @@ fn default_if_arg_present_no_arg_with_value_with_default_user_override_fail() {
assert_eq!(m.value_of("arg").unwrap(), "other");
}

// Unsetting the default

#[test]
fn option_default_if_arg_present_with_value_no_default() {
let r = App::new("df")
.arg(Arg::from("--opt [FILE] 'some arg'"))
.arg(Arg::from("[arg] 'some arg'").default_value_if("opt", Some("value"), Some("default")))
.try_get_matches_from(vec!["", "--opt", "value"]);
assert!(r.is_ok());
let m = r.unwrap();
assert!(m.is_present("arg"));
assert_eq!(m.value_of("arg").unwrap(), "default");
}

#[test]
fn no_default_if_arg_present_with_value_no_default() {
let r = App::new("df")
.arg(Arg::from("--opt [FILE] 'some arg'"))
.arg(Arg::from("[arg] 'some arg'").default_value_if("opt", Some("value"), None))
.try_get_matches_from(vec!["", "--opt", "value"]);
assert!(r.is_ok());
let m = r.unwrap();
assert!(!m.is_present("arg"));
}

#[test]
fn no_default_if_arg_present_with_value_with_default() {
let r = App::new("df")
.arg(Arg::from("--opt [FILE] 'some arg'"))
.arg(
Arg::from("[arg] 'some arg'")
.default_value("default")
.default_value_if("opt", Some("value"), None),
)
.try_get_matches_from(vec!["", "--opt", "value"]);
assert!(r.is_ok());
let m = r.unwrap();
assert!(!m.is_present("arg"));
}

#[test]
fn no_default_if_arg_present_with_value_with_default_user_override() {
let r = App::new("df")
.arg(Arg::from("--opt [FILE] 'some arg'"))
.arg(
Arg::from("[arg] 'some arg'")
.default_value("default")
.default_value_if("opt", Some("value"), None),
)
.try_get_matches_from(vec!["", "--opt", "value", "other"]);
assert!(r.is_ok());
let m = r.unwrap();
assert!(m.is_present("arg"));
assert_eq!(m.value_of("arg").unwrap(), "other");
}

#[test]
fn no_default_if_arg_present_no_arg_with_value_with_default() {
let r = App::new("df")
.arg(Arg::from("--opt [FILE] 'some arg'"))
.arg(
Arg::from("[arg] 'some arg'")
.default_value("default")
.default_value_if("opt", Some("value"), None),
)
.try_get_matches_from(vec!["", "--opt", "other"]);
assert!(r.is_ok());
let m = r.unwrap();
assert!(m.is_present("arg"));
assert_eq!(m.value_of("arg").unwrap(), "default");
}

// Multiple conditions

#[test]
Expand All @@ -357,6 +429,22 @@ fn default_ifs_arg_present() {
assert_eq!(m.value_of("arg").unwrap(), "flg");
}

#[test]
fn no_default_ifs_arg_present() {
let r = App::new("df")
.arg(Arg::from("--opt [FILE] 'some arg'"))
.arg(Arg::from("--flag 'some arg'"))
.arg(
Arg::from("[arg] 'some arg'")
.default_value("first")
.default_value_ifs(&[("opt", Some("some"), Some("default")), ("flag", None, None)]),
)
.try_get_matches_from(vec!["", "--flag"]);
assert!(r.is_ok());
let m = r.unwrap();
assert!(!m.is_present("arg"));
}

#[test]
fn default_ifs_arg_present_user_override() {
let r = App::new("df")
Expand Down