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 Option<Vec<T>> field type #191

Merged
merged 1 commit into from
May 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
* Support optional vectors of arguments for distinguishing between `-o 1 2`, `-o` and no option provided at all
by [@sphynx](https://github.com/sphynx)
([#180](https://github.com/TeXitoi/structopt/issues/188))

# v0.2.16 (2019-05-29)

* Support `Option<Option<T>>` type for fields by [@sphynx](https://github.com/sphynx)
Expand Down
7 changes: 7 additions & 0 deletions examples/example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ struct Opt {
help = "Log file, stdout if no file, no logging if not present"
)]
log: Option<Option<String>>,

/// An optional list of values, will be `None` if not present on
/// the command line, will be `Some(vec![])` if no argument is
/// provided (i.e. `--optv`) and will be `Some(Some(String))` if
/// argument list is provided (e.g. `--optv a b c`).
#[structopt(long = "optv")]
optv: Option<Vec<String>>,
}

fn main() {
Expand Down
7 changes: 7 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,15 @@
//! `Option<T: FromStr>` | optional positional argument or option | `.takes_value(true).multiple(false)`
//! `Option<Option<T: FromStr>>` | optional option with optional value | `.takes_value(true).multiple(false).min_values(0).max_values(1)`
//! `Vec<T: FromStr>` | list of options or the other positional arguments | `.takes_value(true).multiple(true)`
//! `Option<Vec<T: FromStr>` | optional list of options | `.takes_values(true).multiple(true).min_values(0)`
//! `T: FromStr` | required option or positional argument | `.takes_value(true).multiple(false).required(!has_default)`
//!
//! Note that `Option<Option<T>>` allows to express options like
//! `[--opt=[val]]` which can have three values: `None` if `--opt` was
//! not mentioned, `Some(None)` if it was mentioned, but didn't have
//! value (`--opt`) and `Some(Some(val))` for `--opt=val` case.
//! Similar reasoning also applies to `Option<Vec<T>>`.
//!
//! The `FromStr` trait is used to convert the argument to the given
//! type, and the `Arg::validator` method is set to a method using
//! `to_string()` (`FromStr::Err` must implement `std::fmt::Display`).
Expand Down
21 changes: 19 additions & 2 deletions structopt-derive/src/attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub enum Ty {
Vec,
Option,
OptionOption,
OptionVec,
Other,
}
#[derive(Debug)]
Expand Down Expand Up @@ -406,6 +407,7 @@ impl Attrs {
"bool" => Ty::Bool,
"Option" => match sub_type(ty).map(Attrs::ty_from_field) {
Some(Ty::Option) => Ty::OptionOption,
Some(Ty::Vec) => Ty::OptionVec,
_ => Ty::Option,
},
"Vec" => Ty::Vec,
Expand Down Expand Up @@ -437,10 +439,18 @@ impl Attrs {
if !res.methods.iter().all(|m| m.name == "help") {
panic!("methods in attributes is not allowed for subcommand");
}

let ty = Self::ty_from_field(&field.ty);
if ty == Ty::OptionOption {
panic!("Option<Option<T>> type is not allowed for subcommand")
match ty {
Ty::OptionOption => {
panic!("Option<Option<T>> type is not allowed for subcommand");
}
Ty::OptionVec => {
panic!("Option<Vec<T>> type is not allowed for subcommand");
}
_ => (),
}

res.kind = Kind::Subcommand(ty);
}
Kind::Arg(_) => {
Expand Down Expand Up @@ -474,6 +484,13 @@ impl Attrs {
panic!("Option<Option<T>> type is meaningless for positional argument")
}
}
Ty::OptionVec => {
// If it's a positional argument.
if !(res.has_method("long") || res.has_method("short")) {
panic!("Option<Vec<T>> type is meaningless for positional argument")
}
}

_ => (),
}
res.kind = Kind::Arg(ty);
Expand Down
14 changes: 13 additions & 1 deletion structopt-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ fn gen_augmentation(
Kind::Arg(ty) => {
let convert_type = match ty {
Ty::Vec | Ty::Option => sub_type(&field.ty).unwrap_or(&field.ty),
Ty::OptionOption => sub_type(&field.ty).and_then(sub_type).unwrap_or(&field.ty),
Ty::OptionOption | Ty::OptionVec => sub_type(&field.ty).and_then(sub_type).unwrap_or(&field.ty),
_ => &field.ty,
};

Expand Down Expand Up @@ -138,6 +138,9 @@ fn gen_augmentation(
Ty::OptionOption => {
quote! ( .takes_value(true).multiple(false).min_values(0).max_values(1) #validator )
}
Ty::OptionVec => {
quote! ( .takes_value(true).multiple(true).min_values(0) #validator )
}
Ty::Vec => quote!( .takes_value(true).multiple(true) #validator ),
Ty::Other if occurrences => quote!( .takes_value(false).multiple(true) ),
Ty::Other => {
Expand Down Expand Up @@ -216,6 +219,15 @@ fn gen_constructor(fields: &Punctuated<Field, Comma>, parent_attribute: &Attrs)
None
}
},
Ty::OptionVec => quote! {
if matches.is_present(#name) {
Some(matches.#values_of(#name)
.map(|v| v.map(#parse).collect())
.unwrap_or_else(Vec::new))
} else {
None
}
},
Ty::Vec => quote! {
matches.#values_of(#name)
.map(|v| v.map(#parse).collect())
Expand Down
104 changes: 104 additions & 0 deletions tests/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,3 +231,107 @@ fn two_option_options() {
Opt::from_clap(&Opt::clap().get_matches_from(&["test"]))
);
}

#[test]
fn optional_vec() {
#[derive(StructOpt, PartialEq, Debug)]
struct Opt {
#[structopt(short = "a")]
arg: Option<Vec<i32>>,
}
assert_eq!(
Opt { arg: Some(vec![1]) },
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "1"]))
);

assert_eq!(
Opt {
arg: Some(vec![1, 2])
},
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a1", "-a2"]))
);

assert_eq!(
Opt {
arg: Some(vec![1, 2])
},
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a1", "-a2", "-a"]))
);

assert_eq!(
Opt {
arg: Some(vec![1, 2])
},
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a1", "-a", "-a2"]))
);

assert_eq!(
Opt {
arg: Some(vec![1, 2])
},
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "1", "2"]))
);

assert_eq!(
Opt {
arg: Some(vec![1, 2, 3])
},
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "1", "2", "-a", "3"]))
);

assert_eq!(
Opt { arg: Some(vec![]) },
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a"]))
);

assert_eq!(
Opt { arg: Some(vec![]) },
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "-a"]))
);

assert_eq!(
Opt { arg: None },
Opt::from_clap(&Opt::clap().get_matches_from(&["test"]))
);
}

#[test]
fn two_optional_vecs() {
#[derive(StructOpt, PartialEq, Debug)]
struct Opt {
#[structopt(short = "a")]
arg: Option<Vec<i32>>,

#[structopt(short = "b")]
b: Option<Vec<i32>>,
}

assert_eq!(
Opt {
arg: Some(vec![1]),
b: Some(vec![])
},
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "1", "-b"]))
);

assert_eq!(
Opt {
arg: Some(vec![1]),
b: Some(vec![])
},
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "-b", "-a1"]))
);

assert_eq!(
Opt {
arg: Some(vec![1, 2]),
b: Some(vec![1, 2])
},
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a1", "-a2", "-b1", "-b2"]))
);

assert_eq!(
Opt { arg: None, b: None },
Opt::from_clap(&Opt::clap().get_matches_from(&["test"]))
);
}