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<Option<T>> field types #190

Merged
merged 6 commits into from
May 29, 2019
Merged
Show file tree
Hide file tree
Changes from 2 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
50 changes: 47 additions & 3 deletions structopt-derive/src/attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ use heck::{CamelCase, KebabCase, MixedCase, ShoutySnakeCase, SnakeCase};
use proc_macro2::{Span, TokenStream};
use std::{env, mem};
use syn::Type::Path;
use syn::{self, Attribute, Ident, LitStr, MetaList, MetaNameValue, TypePath};
use syn::{
self, AngleBracketedGenericArguments, Attribute, GenericArgument, Ident, LitStr, MetaList,
MetaNameValue, PathArguments, PathSegment, TypePath,
};

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Kind {
Expand All @@ -23,6 +26,7 @@ pub enum Ty {
Bool,
Vec,
Option,
OptionOption,
Other,
}
#[derive(Debug)]
Expand Down Expand Up @@ -400,7 +404,13 @@ impl Attrs {
{
match segments.iter().last().unwrap().ident.to_string().as_str() {
"bool" => Ty::Bool,
"Option" => Ty::Option,
"Option" => match sub_type(ty) {
Some(t) => match Attrs::ty_from_field(t) {
Ty::Option => Ty::OptionOption,
_ => Ty::Option,
},
None => Ty::Option,
},
sphynx marked this conversation as resolved.
Show resolved Hide resolved
"Vec" => Ty::Vec,
_ => Ty::Other,
}
Expand Down Expand Up @@ -430,7 +440,11 @@ impl Attrs {
if !res.methods.iter().all(|m| m.name == "help") {
panic!("methods in attributes is not allowed for subcommand");
}
res.kind = Kind::Subcommand(Self::ty_from_field(&field.ty));
let ty = Self::ty_from_field(&field.ty);
if ty == Ty::OptionOption {
panic!("Option<Option<T>> type is not allowed for subcommand")
}
res.kind = Kind::Subcommand(ty);
}
Kind::Arg(_) => {
let mut ty = Self::ty_from_field(&field.ty);
Expand All @@ -457,6 +471,12 @@ impl Attrs {
panic!("required is meaningless for Option")
}
}
Ty::OptionOption => {
// If it's a positional argument.
if !(res.has_method("long") || res.has_method("short")) {
panic!("Option<Option<T>> type is meaningless for positional argument")
}
}
_ => (),
}
res.kind = Kind::Arg(ty);
Expand Down Expand Up @@ -495,3 +515,27 @@ impl Attrs {
self.casing
}
}

pub fn sub_type(t: &syn::Type) -> Option<&syn::Type> {
let segs = match *t {
syn::Type::Path(TypePath {
path: syn::Path { ref segments, .. },
..
}) => segments,
_ => return None,
};
match *segs.iter().last().unwrap() {
PathSegment {
arguments:
PathArguments::AngleBracketed(AngleBracketedGenericArguments { ref args, .. }),
..
} if args.len() == 1 => {
if let GenericArgument::Type(ref ty) = args[0] {
Some(ty)
} else {
None
}
}
_ => None,
}
}
37 changes: 12 additions & 25 deletions structopt-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ extern crate proc_macro2;

mod attrs;

use attrs::{Attrs, CasingStyle, Kind, Parser, Ty};
use attrs::{Attrs, CasingStyle, Kind, Parser, Ty, sub_type};
use proc_macro2::{Span, TokenStream};
use syn::punctuated::Punctuated;
use syn::token::Comma;
Expand All @@ -46,30 +46,6 @@ pub fn structopt(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
gen.into()
}

fn sub_type(t: &syn::Type) -> Option<&syn::Type> {
let segs = match *t {
syn::Type::Path(TypePath {
path: syn::Path { ref segments, .. },
..
}) => segments,
_ => return None,
};
match *segs.iter().last().unwrap() {
PathSegment {
arguments:
PathArguments::AngleBracketed(AngleBracketedGenericArguments { ref args, .. }),
..
} if args.len() == 1 => {
if let GenericArgument::Type(ref ty) = args[0] {
Some(ty)
} else {
None
}
}
_ => None,
}
}

/// Generate a block of code to add arguments/subcommands corresponding to
/// the `fields` to an app.
fn gen_augmentation(
Expand Down Expand Up @@ -129,6 +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),
_ => &field.ty,
};

Expand Down Expand Up @@ -158,6 +135,9 @@ fn gen_augmentation(
let modifier = match ty {
Ty::Bool => quote!( .takes_value(false).multiple(false) ),
Ty::Option => quote!( .takes_value(true).multiple(false) #validator ),
Ty::OptionOption => {
quote! ( .takes_value(true).multiple(false).min_values(0).max_values(1) #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 @@ -229,6 +209,13 @@ fn gen_constructor(fields: &Punctuated<Field, Comma>, parent_attribute: &Attrs)
matches.#value_of(#name)
.map(#parse)
},
Ty::OptionOption => quote! {
if matches.is_present(#name) {
Some(matches.#value_of(#name).map(#parse))
} else {
None
}
},
Ty::Vec => quote! {
matches.#values_of(#name)
.map(|v| v.map(#parse).collect())
Expand Down
60 changes: 60 additions & 0 deletions tests/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,63 @@ fn option_from_str() {
assert_eq!(Opt { a: None }, Opt::from_iter(&["test"]));
assert_eq!(Opt { a: Some(A) }, Opt::from_iter(&["test", "foo"]));
}

#[test]
fn optional_argument_for_optional_option() {
#[derive(StructOpt, PartialEq, Debug)]
struct Opt {
#[structopt(short = "a")]
arg: Option<Option<i32>>,
}
assert_eq!(
Opt { arg: Some(Some(42)) },
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a42"]))
);
assert_eq!(
Opt { arg: Some(None) },
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a"]))
);
assert_eq!(
Opt { arg: None },
Opt::from_clap(&Opt::clap().get_matches_from(&["test"]))
);
assert!(Opt::clap()
.get_matches_from_safe(&["test", "-a42", "-a24"])
.is_err());
}

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

#[structopt(long = "field")]
field: Option<Option<String>>,
}
assert_eq!(
Opt { arg: Some(Some(42)), field: Some(Some("f".into())) },
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a42", "--field", "f"]))
);
assert_eq!(
Opt { arg: Some(Some(42)), field: Some(None) },
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a42", "--field"]))
);
assert_eq!(
Opt { arg: Some(None), field: Some(None) },
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "--field"]))
);
assert_eq!(
Opt { arg: Some(None), field: Some(Some("f".into())) },
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "--field", "f"]))
);
assert_eq!(
Opt { arg: None, field: Some(None) },
Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--field"]))
);
assert_eq!(
Opt { arg: None, field: None },
Opt::from_clap(&Opt::clap().get_matches_from(&["test"]))
);
}