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

feat(derive): Make it possible to use ArgEnum with default_value #2612

Merged
merged 1 commit into from
Jul 26, 2021
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions clap_derive/src/derives/arg_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ pub fn gen_for_enum(name: &Ident, attrs: &[Attribute], e: &DataEnum) -> TokenStr
let lits = lits(&e.variants, &attrs);
let variants = gen_variants(&lits);
let from_str = gen_from_str(&lits);
let as_arg = gen_as_arg(&lits);

quote! {
#[allow(dead_code, unreachable_code, unused_variables)]
Expand All @@ -66,6 +67,7 @@ pub fn gen_for_enum(name: &Ident, attrs: &[Attribute], e: &DataEnum) -> TokenStr
impl clap::ArgEnum for #name {
#variants
#from_str
#as_arg
}
}
}
Expand Down Expand Up @@ -127,3 +129,16 @@ fn gen_from_str(lits: &[(TokenStream, Ident)]) -> TokenStream {
}
}
}

fn gen_as_arg(lits: &[(TokenStream, Ident)]) -> TokenStream {
let (lit, variant): (Vec<TokenStream>, Vec<Ident>) = lits.iter().cloned().unzip();

quote! {
fn as_arg(&self) -> Option<&'static str> {
match self {
#(Self::#variant => Some(#lit),)*
_ => None
}
}
}
}
46 changes: 46 additions & 0 deletions clap_derive/tests/arg_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,52 @@ fn basic() {
assert!(Opt::try_parse_from(&["", "fOo"]).is_err());
}

#[test]
fn default_value() {
#[derive(ArgEnum, PartialEq, Debug)]
enum ArgChoice {
Foo,
Bar,
}

impl Default for ArgChoice {
fn default() -> Self {
Self::Bar
}
}

impl std::fmt::Display for ArgChoice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
std::fmt::Display::fmt(self.as_arg().unwrap(), f)
}
}

#[derive(Clap, PartialEq, Debug)]
struct Opt {
#[clap(arg_enum, default_value)]
arg: ArgChoice,
}

assert_eq!(
Opt {
arg: ArgChoice::Foo
},
Opt::parse_from(&["", "foo"])
);
assert_eq!(
Opt {
arg: ArgChoice::Bar
},
Opt::parse_from(&["", "bar"])
);
assert_eq!(
Opt {
arg: ArgChoice::Bar
},
Opt::parse_from(&[""])
);
}

#[test]
fn multi_word_is_renamed_kebab() {
#[derive(ArgEnum, PartialEq, Debug)]
Expand Down
5 changes: 5 additions & 0 deletions src/derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,11 @@ pub trait ArgEnum: Sized {

/// Parse an argument into `Self`.
fn from_str(input: &str, case_insensitive: bool) -> Result<Self, String>;

/// The canonical argument value.
///
/// The value is `None` for skipped variants.
fn as_arg(&self) -> Option<&'static str>;
Copy link
Member

Choose a reason for hiding this comment

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

Isn't it better called as to_string or something similar? strum does something similar. https://docs.rs/strum/0.21.0/strum/derive.ToString.html

Copy link
Member Author

Choose a reason for hiding this comment

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

  • That trait allocates
  • I wanted to be clear that this conversion was to the raw argument value and not a general string conversion, which is why skiped values are not covered. People may choose to implement other traits, like Display or ToString on top of this though they have to panic or have a sentinel value when rendering a skipped value.

}

impl<T: Clap> Clap for Box<T> {
Expand Down