-
Notifications
You must be signed in to change notification settings - Fork 152
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
Add raw attributes #26
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
// Copyright (c) 2017 Guillaume Pinot <texitoi(a)texitoi.eu> | ||
// | ||
// This work is free. You can redistribute it and/or modify it under | ||
// the terms of the Do What The Fuck You Want To Public License, | ||
// Version 2, as published by Sam Hocevar. See the COPYING file for | ||
// more details. | ||
|
||
extern crate structopt; | ||
#[macro_use] | ||
extern crate structopt_derive; | ||
|
||
use structopt::StructOpt; | ||
use structopt::clap::AppSettings; | ||
|
||
/// An example of raw attributes | ||
#[derive(StructOpt, Debug)] | ||
#[structopt(global_settings_raw = "&[AppSettings::ColoredHelp, AppSettings::VersionlessSubcommands]")] | ||
struct Opt { | ||
/// Output file | ||
#[structopt(short = "o", long = "output")] | ||
output: String, | ||
|
||
/// admin_level to consider | ||
#[structopt(short = "l", long = "level", aliases_raw = "&[\"set-level\", \"lvl\"]")] | ||
level: Vec<String>, | ||
|
||
/// Files to process | ||
/// | ||
/// `level` is required if a file is called `FILE`. | ||
#[structopt(name = "FILE", requires_if_raw = "\"FILE\", \"level\"")] | ||
files: Vec<String>, | ||
} | ||
|
||
fn main() { | ||
let opt = Opt::from_args(); | ||
println!("{:?}", opt); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -48,6 +48,8 @@ | |
//! through specifying it as an attribute. | ||
//! The `name` attribute can be used to customize the | ||
//! `Arg::with_name()` call (defaults to the field name). | ||
//! For functions that do not take a `&str` as argument, the attribute can be | ||
//! called `function_name_raw`, e. g. `aliases_raw = "&[\"alias\"]"`. | ||
//! | ||
//! The type of the field gives the kind of argument: | ||
//! | ||
|
@@ -385,14 +387,15 @@ fn gen_augmentation(fields: &[Field], app_var: &Ident) -> quote::Tokens { | |
Ty::Vec => quote!( .takes_value(true).multiple(true).#validator ), | ||
Ty::Other => { | ||
let required = extract_attrs(&field.attrs, AttrSource::Field) | ||
.find(|&(ref i, _)| i.as_ref() == "default_value") | ||
.find(|&(ref i, _)| i.as_ref() == "default_value" | ||
|| i.as_ref() == "default_value_raw") | ||
.is_none(); | ||
quote!( .takes_value(true).multiple(false).required(#required).#validator ) | ||
}, | ||
}; | ||
let from_attr = extract_attrs(&field.attrs, AttrSource::Field) | ||
.filter(|&(ref i, _)| i.as_ref() != "name") | ||
.map(|(i, l)| quote!(.#i(#l))); | ||
.map(|(i, l)| gen_attr_call(&i, &l)); | ||
quote!( .arg(_structopt::clap::Arg::with_name(stringify!(#name)) #modifier #(#from_attr)*) ) | ||
}); | ||
|
||
|
@@ -404,6 +407,21 @@ fn gen_augmentation(fields: &[Field], app_var: &Ident) -> quote::Tokens { | |
}} | ||
} | ||
|
||
/// Interpret the value of `*_raw` attributes as code and the rest as strings. | ||
fn gen_attr_call(key: &syn::Ident, val: &syn::Lit) -> quote::Tokens { | ||
if let Lit::Str(ref val, _) = *val { | ||
let key = key.as_ref(); | ||
if key.ends_with("_raw") { | ||
let key = Ident::from(&key[..(key.len() - 4)]); | ||
// Call method without quoting the string | ||
let ts = syn::parse_token_trees(val) | ||
.expect(&format!("bad parameter {} = {}: the parameter must be valid rust code", key, val)); | ||
return quote!(.#key(#(#ts)*)); | ||
} | ||
} | ||
quote!(.#key(#val)) | ||
} | ||
|
||
fn gen_constructor(fields: &[Field]) -> quote::Tokens { | ||
let fields = fields.iter().map(|field| { | ||
let field_name = field.ident.as_ref().unwrap(); | ||
|
@@ -480,12 +498,28 @@ fn format_author(raw_authors: Lit) -> Lit { | |
Lit::Str(authors, StrStyle::Cooked) | ||
} | ||
|
||
fn gen_clap(struct_attrs: &[Attribute], subcmd_required: bool) -> quote::Tokens { | ||
let struct_attrs: Vec<_> = extract_attrs(struct_attrs, AttrSource::Struct).collect(); | ||
let name = from_attr_or_env(&struct_attrs, "name", "CARGO_PKG_NAME"); | ||
let version = from_attr_or_env(&struct_attrs, "version", "CARGO_PKG_VERSION"); | ||
let author = format_author(from_attr_or_env(&struct_attrs, "author", "CARGO_PKG_AUTHORS")); | ||
let about = from_attr_or_env(&struct_attrs, "about", "CARGO_PKG_DESCRIPTION"); | ||
fn gen_clap(attrs: &[Attribute]) -> quote::Tokens { | ||
let attrs: Vec<_> = extract_attrs(attrs, AttrSource::Struct).collect(); | ||
let name = from_attr_or_env(&attrs, "name", "CARGO_PKG_NAME"); | ||
let version = from_attr_or_env(&attrs, "version", "CARGO_PKG_VERSION"); | ||
let author = format_author(from_attr_or_env(&attrs, "author", "CARGO_PKG_AUTHORS")); | ||
let about = from_attr_or_env(&attrs, "about", "CARGO_PKG_DESCRIPTION"); | ||
let settings = attrs.iter() | ||
.filter(|&&(ref i, _)| !["name", "version", "author", "about"].contains(&i.as_ref())) | ||
.map(|&(ref i, ref l)| gen_attr_call(i, l)) | ||
.collect::<Vec<_>>(); | ||
|
||
quote! { | ||
_structopt::clap::App::new(#name) | ||
.version(#version) | ||
.author(#author) | ||
.about(#about) | ||
#( #settings )* | ||
} | ||
} | ||
|
||
fn gen_clap_struct(struct_attrs: &[Attribute], subcmd_required: bool) -> quote::Tokens { | ||
let gen = gen_clap(struct_attrs); | ||
let setting = if subcmd_required { | ||
quote!( .setting(_structopt::clap::AppSettings::SubcommandRequired) ) | ||
} else { | ||
|
@@ -494,12 +528,8 @@ fn gen_clap(struct_attrs: &[Attribute], subcmd_required: bool) -> quote::Tokens | |
|
||
quote! { | ||
fn clap<'a, 'b>() -> _structopt::clap::App<'a, 'b> { | ||
let app = _structopt::clap::App::new(#name) | ||
.version(#version) | ||
.author(#author) | ||
.about(#about) | ||
#setting | ||
; | ||
let app = #gen | ||
#setting; | ||
Self::augment_clap(app) | ||
} | ||
} | ||
|
@@ -516,19 +546,11 @@ fn gen_augment_clap(fields: &[Field]) -> quote::Tokens { | |
} | ||
|
||
fn gen_clap_enum(enum_attrs: &[Attribute]) -> quote::Tokens { | ||
let enum_attrs: Vec<_> = extract_attrs(enum_attrs, AttrSource::Struct).collect(); | ||
let name = from_attr_or_env(&enum_attrs, "name", "CARGO_PKG_NAME"); | ||
let version = from_attr_or_env(&enum_attrs, "version", "CARGO_PKG_VERSION"); | ||
let author = format_author(from_attr_or_env(&enum_attrs, "author", "CARGO_PKG_AUTHORS")); | ||
let about = from_attr_or_env(&enum_attrs, "about", "CARGO_PKG_DESCRIPTION"); | ||
|
||
let gen = gen_clap(enum_attrs); | ||
quote! { | ||
fn clap<'a, 'b>() -> _structopt::clap::App<'a, 'b> { | ||
let app = _structopt::clap::App::new(#name) | ||
.version(#version) | ||
.author(#author) | ||
.about(#about) | ||
.setting(_structopt::clap::AppSettings::SubcommandRequired); | ||
let app = #gen | ||
.setting(_structopt::clap::AppSettings::SubcommandRequiredElseHelp); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. That's OK for me. @williamyaoh OK? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Seems like it makes whoops, work account derp |
||
Self::augment_clap(app) | ||
} | ||
} | ||
|
@@ -552,7 +574,7 @@ fn gen_augment_clap_enum(variants: &[Variant]) -> quote::Tokens { | |
}; | ||
let from_attr = extract_attrs(&variant.attrs, AttrSource::Struct) | ||
.filter(|&(ref i, _)| i != "name") | ||
.map(|(i, l)| quote!( .#i(#l) )); | ||
.map(|(i, l)| gen_attr_call(&i, &l)); | ||
|
||
quote! { | ||
.subcommand({ | ||
|
@@ -620,7 +642,7 @@ fn impl_structopt_for_struct(name: &Ident, fields: &[Field], attrs: &[Attribute] | |
_ => is_subcommand(field) | ||
} | ||
}); | ||
let clap = gen_clap(attrs, subcmd_required); | ||
let clap = gen_clap_struct(attrs, subcmd_required); | ||
let augment_clap = gen_augment_clap(fields); | ||
let from_clap = gen_from_clap(name, fields); | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
// Copyright (c) 2017 Guillaume Pinot <texitoi(a)texitoi.eu> | ||
// | ||
// This work is free. You can redistribute it and/or modify it under | ||
// the terms of the Do What The Fuck You Want To Public License, | ||
// Version 2, as published by Sam Hocevar. See the COPYING file for | ||
// more details. | ||
|
||
extern crate structopt; | ||
#[macro_use] | ||
extern crate structopt_derive; | ||
|
||
use structopt::StructOpt; | ||
use structopt::clap::AppSettings; | ||
|
||
// Check if the global settings compile | ||
#[derive(StructOpt, Debug, PartialEq, Eq)] | ||
#[structopt(global_settings_raw = "&[AppSettings::ColoredHelp]")] | ||
struct Opt { | ||
#[structopt(long = "x", display_order_raw = "2", next_line_help_raw = "true", | ||
default_value_raw = "\"0\"", require_equals_raw = "true")] | ||
x: i32, | ||
|
||
#[structopt(short = "l", long = "level", aliases_raw = "&[\"set-level\", \"lvl\"]")] | ||
level: String, | ||
|
||
#[structopt(long = "values")] | ||
values: Vec<i32>, | ||
|
||
#[structopt(name = "FILE", requires_if_raw = "\"FILE\", \"values\"")] | ||
files: Vec<String>, | ||
} | ||
|
||
#[test] | ||
fn test_raw_slice() { | ||
assert_eq!(Opt { x: 0, level: "1".to_string(), files: Vec::new(), values: vec![] }, | ||
Opt::from_clap(Opt::clap().get_matches_from(&["test", "-l", "1"]))); | ||
assert_eq!(Opt { x: 0, level: "1".to_string(), files: Vec::new(), values: vec![] }, | ||
Opt::from_clap(Opt::clap().get_matches_from(&["test", "--level", "1"]))); | ||
assert_eq!(Opt { x: 0, level: "1".to_string(), files: Vec::new(), values: vec![] }, | ||
Opt::from_clap(Opt::clap().get_matches_from(&["test", "--set-level", "1"]))); | ||
assert_eq!(Opt { x: 0, level: "1".to_string(), files: Vec::new(), values: vec![] }, | ||
Opt::from_clap(Opt::clap().get_matches_from(&["test", "--lvl", "1"]))); | ||
} | ||
|
||
#[test] | ||
fn test_raw_multi_args() { | ||
assert_eq!(Opt { x: 0, level: "1".to_string(), files: vec!["file".to_string()], values: vec![] }, | ||
Opt::from_clap(Opt::clap().get_matches_from(&["test", "-l", "1", "file"]))); | ||
assert_eq!(Opt { x: 0, level: "1".to_string(), files: vec!["FILE".to_string()], values: vec![1] }, | ||
Opt::from_clap(Opt::clap().get_matches_from(&["test", "-l", "1", "--values", "1", "--", "FILE"]))); | ||
} | ||
|
||
#[test] | ||
fn test_raw_multi_args_fail() { | ||
let result = Opt::clap().get_matches_from_safe(&["test", "-l", "1", "--", "FILE"]); | ||
assert!(result.is_err()); | ||
} | ||
|
||
#[test] | ||
fn test_raw_bool() { | ||
assert_eq!(Opt { x: 1, level: "1".to_string(), files: vec![], values: vec![] }, | ||
Opt::from_clap(Opt::clap().get_matches_from(&["test", "-l", "1", "--x=1"]))); | ||
let result = Opt::clap().get_matches_from_safe(&["test", "-l", "1", "--x", "1"]); | ||
assert!(result.is_err()); | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍 great factoring