Merge pull request #232 from kbknapp/rustfmt

Runs rustfmt against code base
This commit is contained in:
Kevin K. 2015-09-06 21:50:03 -04:00
commit 7b01df6957
17 changed files with 685 additions and 383 deletions

File diff suppressed because it is too large Load diff

View file

@ -158,7 +158,7 @@ pub enum ClapErrorType {
/// .multiple(false)) /// .multiple(false))
/// .get_matches_from_safe(vec!["", "--debug", "--debug"]); /// .get_matches_from_safe(vec!["", "--debug", "--debug"]);
/// ``` /// ```
UnexpectedMultipleUsage UnexpectedMultipleUsage,
} }
/// Command line argument parser error /// Command line argument parser error
@ -167,7 +167,7 @@ pub struct ClapError {
/// Formated error message /// Formated error message
pub error: String, pub error: String,
/// Command line argument parser error type /// Command line argument parser error type
pub error_type: ClapErrorType pub error_type: ClapErrorType,
} }
impl Error for ClapError { impl Error for ClapError {
@ -177,7 +177,9 @@ impl Error for ClapError {
} }
impl fmt::Display for ClapError { impl fmt::Display for ClapError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self,
f: &mut fmt::Formatter)
-> fmt::Result {
write!(f, "{}", self.error) write!(f, "{}", self.error)
} }
} }

View file

@ -7,15 +7,18 @@ use strsim;
/// `Some("foo")`, whereas "blark" would yield `None`. /// `Some("foo")`, whereas "blark" would yield `None`.
#[cfg(feature = "suggestions")] #[cfg(feature = "suggestions")]
#[cfg_attr(feature = "lints", allow(needless_lifetimes))] #[cfg_attr(feature = "lints", allow(needless_lifetimes))]
pub fn did_you_mean<'a, T, I>(v: &str, possible_values: I) -> Option<&'a str> pub fn did_you_mean<'a, T, I>(v: &str,
possible_values: I)
-> Option<&'a str>
where T: AsRef<str> + 'a, where T: AsRef<str> + 'a,
I: IntoIterator<Item=&'a T> { I: IntoIterator<Item = &'a T>
{
let mut candidate: Option<(f64, &str)> = None; let mut candidate: Option<(f64, &str)> = None;
for pv in possible_values.into_iter() { for pv in possible_values.into_iter() {
let confidence = strsim::jaro_winkler(v, pv.as_ref()); let confidence = strsim::jaro_winkler(v, pv.as_ref());
if confidence > 0.8 && (candidate.is_none() || if confidence > 0.8 &&
(candidate.as_ref().unwrap().0 < confidence)) { (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {
candidate = Some((confidence, pv.as_ref())); candidate = Some((confidence, pv.as_ref()));
} }
} }
@ -26,9 +29,12 @@ pub fn did_you_mean<'a, T, I>(v: &str, possible_values: I) -> Option<&'a str>
} }
#[cfg(not(feature = "suggestions"))] #[cfg(not(feature = "suggestions"))]
pub fn did_you_mean<'a, T, I>(_: &str, _: I) -> Option<&'a str> pub fn did_you_mean<'a, T, I>(_: &str,
_: I)
-> Option<&'a str>
where T: AsRef<str> + 'a, where T: AsRef<str> + 'a,
I: IntoIterator<Item=&'a T> { I: IntoIterator<Item = &'a T>
{
None None
} }

View file

@ -101,7 +101,7 @@ pub struct Arg<'n, 'l, 'h, 'g, 'p, 'r> {
pub validator: Option<Rc<Fn(String) -> Result<(), String>>>, pub validator: Option<Rc<Fn(String) -> Result<(), String>>>,
/// A list of names for other arguments that *mutually override* this flag /// A list of names for other arguments that *mutually override* this flag
#[doc(hidden)] #[doc(hidden)]
pub overrides: Option<Vec<&'r str>> pub overrides: Option<Vec<&'r str>>,
} }
impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> { impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
@ -144,7 +144,7 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
global: false, global: false,
empty_vals: true, empty_vals: true,
validator: None, validator: None,
overrides: None overrides: None,
} }
} }
@ -365,7 +365,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
} }
Arg { Arg {
name: name.unwrap_or_else(|| panic!("Missing flag name in \"{}\", check from_usage call", u)), name: name.unwrap_or_else(|| {
panic!("Missing flag name in \"{}\", check from_usage call", u)
}),
short: short, short: short,
long: long, long: long,
help: help, help: help,
@ -376,8 +378,16 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
possible_vals: None, possible_vals: None,
blacklist: None, blacklist: None,
requires: None, requires: None,
num_vals: if num_names > 1 { Some(num_names) } else { None }, num_vals: if num_names > 1 {
val_names: if val_names.len() > 1 {Some(val_names)}else{None}, Some(num_names)
} else {
None
},
val_names: if val_names.len() > 1 {
Some(val_names)
} else {
None
},
max_vals: None, max_vals: None,
min_vals: None, min_vals: None,
group: None, group: None,
@ -408,7 +418,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # Arg::with_name("conifg") /// # Arg::with_name("conifg")
/// .short("c") /// .short("c")
/// # ).get_matches(); /// # ).get_matches();
pub fn short(mut self, s: &str) -> Self { pub fn short(mut self,
s: &str)
-> Self {
self.short = s.trim_left_matches(|c| c == '-').chars().nth(0); self.short = s.trim_left_matches(|c| c == '-').chars().nth(0);
self self
} }
@ -432,7 +444,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # Arg::with_name("conifg") /// # Arg::with_name("conifg")
/// .long("config") /// .long("config")
/// # ).get_matches(); /// # ).get_matches();
pub fn long(mut self, l: &'l str) -> Self { pub fn long(mut self,
l: &'l str)
-> Self {
self.long = Some(l.trim_left_matches(|c| c == '-')); self.long = Some(l.trim_left_matches(|c| c == '-'));
self self
} }
@ -450,7 +464,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # Arg::with_name("conifg") /// # Arg::with_name("conifg")
/// .help("The config file used by the myprog") /// .help("The config file used by the myprog")
/// # ).get_matches(); /// # ).get_matches();
pub fn help(mut self, h: &'h str) -> Self { pub fn help(mut self,
h: &'h str)
-> Self {
self.help = Some(h); self.help = Some(h);
self self
} }
@ -474,7 +490,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # Arg::with_name("conifg") /// # Arg::with_name("conifg")
/// .required(true) /// .required(true)
/// # ).get_matches(); /// # ).get_matches();
pub fn required(mut self, r: bool) -> Self { pub fn required(mut self,
r: bool)
-> Self {
self.required = r; self.required = r;
self self
} }
@ -494,7 +512,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # let myprog = App::new("myprog").arg(Arg::with_name("conifg") /// # let myprog = App::new("myprog").arg(Arg::with_name("conifg")
/// .conflicts_with("debug") /// .conflicts_with("debug")
/// # ).get_matches(); /// # ).get_matches();
pub fn conflicts_with(mut self, name: &'r str) -> Self { pub fn conflicts_with(mut self,
name: &'r str)
-> Self {
if let Some(ref mut vec) = self.blacklist { if let Some(ref mut vec) = self.blacklist {
vec.push(name); vec.push(name);
} else { } else {
@ -519,10 +539,12 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # let myprog = App::new("myprog").arg(Arg::with_name("conifg") /// # let myprog = App::new("myprog").arg(Arg::with_name("conifg")
/// .conflicts_with_all(&config_conflicts) /// .conflicts_with_all(&config_conflicts)
/// # ).get_matches(); /// # ).get_matches();
pub fn conflicts_with_all<T, I>(mut self, names: I) pub fn conflicts_with_all<T, I>(mut self,
names: I)
-> Self -> Self
where T: AsRef<str> + 'r, where T: AsRef<str> + 'r,
I: IntoIterator<Item=&'r T> { I: IntoIterator<Item = &'r T>
{
if let Some(ref mut vec) = self.blacklist { if let Some(ref mut vec) = self.blacklist {
names.into_iter().map(|s| vec.push(s.as_ref())).collect::<Vec<_>>(); names.into_iter().map(|s| vec.push(s.as_ref())).collect::<Vec<_>>();
} else { } else {
@ -541,7 +563,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # let myprog = App::new("myprog").arg(Arg::with_name("conifg") /// # let myprog = App::new("myprog").arg(Arg::with_name("conifg")
/// .mutually_overrides_with("debug") /// .mutually_overrides_with("debug")
/// # ).get_matches(); /// # ).get_matches();
pub fn mutually_overrides_with(mut self, name: &'r str) -> Self { pub fn mutually_overrides_with(mut self,
name: &'r str)
-> Self {
if let Some(ref mut vec) = self.overrides { if let Some(ref mut vec) = self.overrides {
vec.push(name); vec.push(name);
} else { } else {
@ -561,10 +585,12 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # let myprog = App::new("myprog").arg(Arg::with_name("conifg") /// # let myprog = App::new("myprog").arg(Arg::with_name("conifg")
/// .mutually_overrides_with_all(&config_overrides) /// .mutually_overrides_with_all(&config_overrides)
/// # ).get_matches(); /// # ).get_matches();
pub fn mutually_overrides_with_all<T, I>(mut self, names: I) pub fn mutually_overrides_with_all<T, I>(mut self,
names: I)
-> Self -> Self
where T: AsRef<str> + 'r, where T: AsRef<str> + 'r,
I: IntoIterator<Item=&'r T> { I: IntoIterator<Item = &'r T>
{
if let Some(ref mut vec) = self.overrides { if let Some(ref mut vec) = self.overrides {
names.into_iter().map(|s| vec.push(s.as_ref())).collect::<Vec<_>>(); names.into_iter().map(|s| vec.push(s.as_ref())).collect::<Vec<_>>();
} else { } else {
@ -586,7 +612,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # let myprog = App::new("myprog").arg(Arg::with_name("conifg") /// # let myprog = App::new("myprog").arg(Arg::with_name("conifg")
/// .requires("debug") /// .requires("debug")
/// # ).get_matches(); /// # ).get_matches();
pub fn requires(mut self, name: &'r str) -> Self { pub fn requires(mut self,
name: &'r str)
-> Self {
if let Some(ref mut vec) = self.requires { if let Some(ref mut vec) = self.requires {
vec.push(name); vec.push(name);
} else { } else {
@ -610,10 +638,12 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # let myprog = App::new("myprog").arg(Arg::with_name("conifg") /// # let myprog = App::new("myprog").arg(Arg::with_name("conifg")
/// .requires_all(&config_reqs) /// .requires_all(&config_reqs)
/// # ).get_matches(); /// # ).get_matches();
pub fn requires_all<T, I>(mut self, names: I) pub fn requires_all<T, I>(mut self,
names: I)
-> Self -> Self
where T: AsRef<str> + 'r, where T: AsRef<str> + 'r,
I: IntoIterator<Item=&'r T> { I: IntoIterator<Item = &'r T>
{
if let Some(ref mut vec) = self.requires { if let Some(ref mut vec) = self.requires {
names.into_iter().map(|s| vec.push(s.as_ref())).collect::<Vec<_>>(); names.into_iter().map(|s| vec.push(s.as_ref())).collect::<Vec<_>>();
} else { } else {
@ -637,7 +667,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # Arg::with_name("conifg") /// # Arg::with_name("conifg")
/// .takes_value(true) /// .takes_value(true)
/// # ).get_matches(); /// # ).get_matches();
pub fn takes_value(mut self, tv: bool) -> Self { pub fn takes_value(mut self,
tv: bool)
-> Self {
self.takes_value = tv; self.takes_value = tv;
self self
} }
@ -659,7 +691,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # Arg::with_name("conifg") /// # Arg::with_name("conifg")
/// .index(1) /// .index(1)
/// # ).get_matches(); /// # ).get_matches();
pub fn index(mut self, idx: u8) -> Self { pub fn index(mut self,
idx: u8)
-> Self {
self.index = Some(idx); self.index = Some(idx);
self self
} }
@ -682,7 +716,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # Arg::with_name("debug") /// # Arg::with_name("debug")
/// .multiple(true) /// .multiple(true)
/// # ).get_matches(); /// # ).get_matches();
pub fn multiple(mut self, multi: bool) -> Self { pub fn multiple(mut self,
multi: bool)
-> Self {
self.multiple = multi; self.multiple = multi;
self self
} }
@ -707,7 +743,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # Arg::with_name("debug") /// # Arg::with_name("debug")
/// .global(true) /// .global(true)
/// # ).get_matches(); /// # ).get_matches();
pub fn global(mut self, g: bool) -> Self { pub fn global(mut self,
g: bool)
-> Self {
self.global = g; self.global = g;
self self
} }
@ -727,7 +765,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # Arg::with_name("debug") /// # Arg::with_name("debug")
/// .empty_values(true) /// .empty_values(true)
/// # ).get_matches(); /// # ).get_matches();
pub fn empty_values(mut self, ev: bool) -> Self { pub fn empty_values(mut self,
ev: bool)
-> Self {
self.empty_vals = ev; self.empty_vals = ev;
self self
} }
@ -748,10 +788,12 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # Arg::with_name("debug").index(1) /// # Arg::with_name("debug").index(1)
/// .possible_values(&mode_vals) /// .possible_values(&mode_vals)
/// # ).get_matches(); /// # ).get_matches();
pub fn possible_values<T, I>(mut self, names: I) pub fn possible_values<T, I>(mut self,
names: I)
-> Self -> Self
where T: AsRef<str> + 'p, where T: AsRef<str> + 'p,
I: IntoIterator<Item=&'p T> { I: IntoIterator<Item = &'p T>
{
if let Some(ref mut vec) = self.possible_vals { if let Some(ref mut vec) = self.possible_vals {
names.into_iter().map(|s| vec.push(s.as_ref())).collect::<Vec<_>>(); names.into_iter().map(|s| vec.push(s.as_ref())).collect::<Vec<_>>();
} else { } else {
@ -776,7 +818,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// .possible_value("fast") /// .possible_value("fast")
/// .possible_value("slow") /// .possible_value("slow")
/// # ).get_matches(); /// # ).get_matches();
pub fn possible_value(mut self, name: &'p str) -> Self { pub fn possible_value(mut self,
name: &'p str)
-> Self {
if let Some(ref mut vec) = self.possible_vals { if let Some(ref mut vec) = self.possible_vals {
vec.push(name); vec.push(name);
} else { } else {
@ -797,7 +841,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # Arg::with_name("debug").index(1) /// # Arg::with_name("debug").index(1)
/// .group("mode") /// .group("mode")
/// # ).get_matches(); /// # ).get_matches();
pub fn group(mut self, name: &'g str) -> Self { pub fn group(mut self,
name: &'g str)
-> Self {
self.group = Some(name); self.group = Some(name);
self self
} }
@ -820,7 +866,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # Arg::with_name("debug").index(1) /// # Arg::with_name("debug").index(1)
/// .number_of_values(3) /// .number_of_values(3)
/// # ).get_matches(); /// # ).get_matches();
pub fn number_of_values(mut self, qty: u8) -> Self { pub fn number_of_values(mut self,
qty: u8)
-> Self {
self.num_vals = Some(qty); self.num_vals = Some(qty);
self self
} }
@ -851,7 +899,11 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// } /// }
/// }) /// })
/// # ).get_matches(); /// # ).get_matches();
pub fn validator<F>(mut self, f: F) -> Self where F: Fn(String) -> Result<(), String> + 'static { pub fn validator<F>(mut self,
f: F)
-> Self
where F: Fn(String) -> Result<(), String> + 'static
{
self.validator = Some(Rc::new(f)); self.validator = Some(Rc::new(f));
self self
} }
@ -874,7 +926,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # Arg::with_name("debug").index(1) /// # Arg::with_name("debug").index(1)
/// .max_values(3) /// .max_values(3)
/// # ).get_matches(); /// # ).get_matches();
pub fn max_values(mut self, qty: u8) -> Self { pub fn max_values(mut self,
qty: u8)
-> Self {
if qty < 2 { if qty < 2 {
panic!("Arguments with max_values(qty) qty must be > 1. Prefer \ panic!("Arguments with max_values(qty) qty must be > 1. Prefer \
takes_value(true) for arguments with only one value, or flags for arguments \ takes_value(true) for arguments with only one value, or flags for arguments \
@ -906,7 +960,9 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// # Arg::with_name("debug").index(1) /// # Arg::with_name("debug").index(1)
/// .min_values(2) /// .min_values(2)
/// # ).get_matches(); /// # ).get_matches();
pub fn min_values(mut self, qty: u8) -> Self { pub fn min_values(mut self,
qty: u8)
-> Self {
if qty < 1 { if qty < 1 {
panic!("Arguments with min_values(qty) qty must be > 0. Prefer flags for arguments \ panic!("Arguments with min_values(qty) qty must be > 0. Prefer flags for arguments \
with 0 values."); with 0 values.");
@ -940,10 +996,12 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// // ... /// // ...
/// .value_names(&val_names) /// .value_names(&val_names)
/// # ).get_matches(); /// # ).get_matches();
pub fn value_names<T, I>(mut self, names: I) pub fn value_names<T, I>(mut self,
names: I)
-> Self -> Self
where T: AsRef<str> + 'n, where T: AsRef<str> + 'n,
I: IntoIterator<Item=&'n T> { I: IntoIterator<Item = &'n T>
{
if let Some(ref mut vec) = self.val_names { if let Some(ref mut vec) = self.val_names {
names.into_iter().map(|s| vec.insert(s.as_ref())).collect::<Vec<_>>(); names.into_iter().map(|s| vec.insert(s.as_ref())).collect::<Vec<_>>();
} else { } else {
@ -965,7 +1023,8 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
/// .index(1) /// .index(1)
/// .value_name("file") /// .value_name("file")
/// # ).get_matches(); /// # ).get_matches();
pub fn value_name(mut self, name: &'n str) pub fn value_name(mut self,
name: &'n str)
-> Self { -> Self {
if let Some(ref mut vec) = self.val_names { if let Some(ref mut vec) = self.val_names {
vec.insert(name); vec.insert(name);
@ -978,7 +1037,8 @@ impl<'n, 'l, 'h, 'g, 'p, 'r> Arg<'n, 'l, 'h, 'g, 'p, 'r> {
} }
} }
impl<'n, 'l, 'h, 'g, 'p, 'r, 'z> From<&'z Arg<'n, 'l, 'h, 'g, 'p, 'r>> for Arg<'n, 'l, 'h, 'g, 'p, 'r> { impl<'n, 'l, 'h, 'g, 'p, 'r, 'z> From<&'z Arg<'n, 'l, 'h, 'g, 'p, 'r>>
for Arg<'n, 'l, 'h, 'g, 'p, 'r> {
fn from(a: &'z Arg<'n, 'l, 'h, 'g, 'p, 'r>) -> Self { fn from(a: &'z Arg<'n, 'l, 'h, 'g, 'p, 'r>) -> Self {
Arg { Arg {
name: a.name, name: a.name,
@ -1000,7 +1060,7 @@ impl<'n, 'l, 'h, 'g, 'p, 'r, 'z> From<&'z Arg<'n, 'l, 'h, 'g, 'p, 'r>> for Arg<'
global: a.global, global: a.global,
empty_vals: a.empty_vals, empty_vals: a.empty_vals,
validator: a.validator.clone(), validator: a.validator.clone(),
overrides: a.overrides.clone() overrides: a.overrides.clone(),
} }
} }
} }

View file

@ -26,11 +26,13 @@ pub struct FlagBuilder<'n> {
pub short: Option<char>, pub short: Option<char>,
pub global: bool, pub global: bool,
/// A list of names for other arguments that *mutually override* this flag /// A list of names for other arguments that *mutually override* this flag
pub overrides: Option<Vec<&'n str>> pub overrides: Option<Vec<&'n str>>,
} }
impl<'n> Display for FlagBuilder<'n> { impl<'n> Display for FlagBuilder<'n> {
fn fmt(&self, f: &mut Formatter) -> Result { fn fmt(&self,
f: &mut Formatter)
-> Result {
if let Some(l) = self.long { if let Some(l) = self.long {
write!(f, "--{}", l) write!(f, "--{}", l)
} else { } else {
@ -53,7 +55,7 @@ mod test {
blacklist: None, blacklist: None,
requires: None, requires: None,
global: false, global: false,
overrides: None overrides: None,
}; };
assert_eq!(&*format!("{}", f), "--flag"); assert_eq!(&*format!("{}", f), "--flag");
@ -67,7 +69,7 @@ mod test {
blacklist: None, blacklist: None,
requires: None, requires: None,
global: false, global: false,
overrides: None overrides: None,
}; };
assert_eq!(&*format!("{}", f2), "-f"); assert_eq!(&*format!("{}", f2), "-f");

View file

@ -34,11 +34,13 @@ pub struct OptBuilder<'n> {
pub global: bool, pub global: bool,
pub validator: Option<Rc<Fn(String) -> StdResult<(), String>>>, pub validator: Option<Rc<Fn(String) -> StdResult<(), String>>>,
/// A list of names for other arguments that *mutually override* this flag /// A list of names for other arguments that *mutually override* this flag
pub overrides: Option<Vec<&'n str>> pub overrides: Option<Vec<&'n str>>,
} }
impl<'n> Display for OptBuilder<'n> { impl<'n> Display for OptBuilder<'n> {
fn fmt(&self, f: &mut Formatter) -> Result { fn fmt(&self,
f: &mut Formatter)
-> Result {
// Write the name such --long or -l // Write the name such --long or -l
if let Some(l) = self.long { if let Some(l) = self.long {
try!(write!(f, "--{}", l)); try!(write!(f, "--{}", l));
@ -89,7 +91,7 @@ mod test {
empty_vals: true, empty_vals: true,
global: false, global: false,
validator: None, validator: None,
overrides: None overrides: None,
}; };
assert_eq!(&*format!("{}", o), "--option <opt>..."); assert_eq!(&*format!("{}", o), "--option <opt>...");
@ -115,7 +117,7 @@ mod test {
empty_vals: true, empty_vals: true,
global: false, global: false,
validator: None, validator: None,
overrides: None overrides: None,
}; };
assert_eq!(&*format!("{}", o2), "-o <file> <name>"); assert_eq!(&*format!("{}", o2), "-o <file> <name>");

View file

@ -34,7 +34,9 @@ pub struct PosBuilder<'n> {
} }
impl<'n> Display for PosBuilder<'n> { impl<'n> Display for PosBuilder<'n> {
fn fmt(&self, f: &mut Formatter) -> Result { fn fmt(&self,
f: &mut Formatter)
-> Result {
if self.required { if self.required {
try!(write!(f, "<{}>", self.name)); try!(write!(f, "<{}>", self.name));
} else { } else {
@ -68,7 +70,7 @@ mod test {
empty_vals: true, empty_vals: true,
global: false, global: false,
validator: None, validator: None,
overrides: None overrides: None,
}; };
assert_eq!(&*format!("{}", p), "[pos]..."); assert_eq!(&*format!("{}", p), "[pos]...");
@ -88,7 +90,7 @@ mod test {
empty_vals: true, empty_vals: true,
global: false, global: false,
validator: None, validator: None,
overrides: None overrides: None,
}; };
assert_eq!(&*format!("{}", p2), "<pos>"); assert_eq!(&*format!("{}", p2), "<pos>");

View file

@ -58,7 +58,7 @@ pub struct ArgMatches<'n, 'a> {
#[doc(hidden)] #[doc(hidden)]
pub subcommand: Option<Box<SubCommand<'n, 'a>>>, pub subcommand: Option<Box<SubCommand<'n, 'a>>>,
#[doc(hidden)] #[doc(hidden)]
pub usage: Option<String> pub usage: Option<String>,
} }
impl<'n, 'a> ArgMatches<'n, 'a> { impl<'n, 'a> ArgMatches<'n, 'a> {
@ -91,12 +91,17 @@ impl<'n, 'a> ArgMatches<'n, 'a> {
/// ///
/// ```no_run /// ```no_run
/// # use clap::{App, Arg}; /// # use clap::{App, Arg};
/// # let matches = App::new("myapp").arg(Arg::with_name("output").takes_value(true)).get_matches(); /// # let matches = App::new("myapp")
/// # .arg(Arg::with_name("output")
/// # .takes_value(true))
/// # .get_matches();
/// if let Some(o) = matches.value_of("output") { /// if let Some(o) = matches.value_of("output") {
/// println!("Value for output: {}", o); /// println!("Value for output: {}", o);
/// } /// }
/// ``` /// ```
pub fn value_of(&self, name: &str) -> Option<&str> { pub fn value_of(&self,
name: &str)
-> Option<&str> {
if let Some(ref arg) = self.args.get(name) { if let Some(ref arg) = self.args.get(name) {
if let Some(ref vals) = arg.values { if let Some(ref vals) = arg.values {
if let Some(ref val) = vals.values().nth(0) { if let Some(ref val) = vals.values().nth(0) {
@ -115,7 +120,8 @@ impl<'n, 'a> ArgMatches<'n, 'a> {
/// ///
/// ```no_run /// ```no_run
/// # use clap::{App, Arg}; /// # use clap::{App, Arg};
/// # let matches = App::new("myapp").arg(Arg::with_name("output").takes_value(true)).get_matches(); /// # let matches = App::new("myapp")
/// # .arg(Arg::with_name("output").takes_value(true)).get_matches();
/// // If the program had option "-c" that took a value and was run /// // If the program had option "-c" that took a value and was run
/// // via "myapp -o some -o other -o file" /// // via "myapp -o some -o other -o file"
/// // values_of() would return a [&str; 3] ("some", "other", "file") /// // values_of() would return a [&str; 3] ("some", "other", "file")
@ -125,7 +131,9 @@ impl<'n, 'a> ArgMatches<'n, 'a> {
/// } /// }
/// } /// }
/// ``` /// ```
pub fn values_of(&'a self, name: &str) -> Option<Vec<&'a str>> { pub fn values_of(&'a self,
name: &str)
-> Option<Vec<&'a str>> {
if let Some(ref arg) = self.args.get(name) { if let Some(ref arg) = self.args.get(name) {
if let Some(ref vals) = arg.values { if let Some(ref vals) = arg.values {
return Some(vals.values().map(|s| &s[..]).collect::<Vec<_>>()); return Some(vals.values().map(|s| &s[..]).collect::<Vec<_>>());
@ -141,16 +149,23 @@ impl<'n, 'a> ArgMatches<'n, 'a> {
/// ///
/// ```no_run /// ```no_run
/// # use clap::{App, Arg}; /// # use clap::{App, Arg};
/// # let matches = App::new("myapp").arg(Arg::with_name("output").takes_value(true)).get_matches(); /// # let matches = App::new("myapp")
/// # .arg(Arg::with_name("output").takes_value(true)).get_matches();
/// if matches.is_present("output") { /// if matches.is_present("output") {
/// println!("The output argument was used!"); /// println!("The output argument was used!");
/// } /// }
/// ``` /// ```
pub fn is_present(&self, name: &str) -> bool { pub fn is_present(&self,
name: &str)
-> bool {
if let Some(ref sc) = self.subcommand { if let Some(ref sc) = self.subcommand {
if sc.name == name { return true; } if sc.name == name {
return true;
}
}
if self.args.contains_key(name) {
return true;
} }
if self.args.contains_key(name) {return true;}
false false
} }
@ -163,14 +178,17 @@ impl<'n, 'a> ArgMatches<'n, 'a> {
/// ///
/// ```no_run /// ```no_run
/// # use clap::{App, Arg}; /// # use clap::{App, Arg};
/// # let matches = App::new("myapp").arg(Arg::with_name("output").takes_value(true)).get_matches(); /// # let matches = App::new("myapp")
/// # .arg(Arg::with_name("output").takes_value(true)).get_matches();
/// if matches.occurrences_of("debug") > 1 { /// if matches.occurrences_of("debug") > 1 {
/// println!("Debug mode is REALLY on"); /// println!("Debug mode is REALLY on");
/// } else { /// } else {
/// println!("Debug mode kind of on"); /// println!("Debug mode kind of on");
/// } /// }
/// ``` /// ```
pub fn occurrences_of(&self, name: &str) -> u8 { pub fn occurrences_of(&self,
name: &str)
-> u8 {
if let Some(ref arg) = self.args.get(name) { if let Some(ref arg) = self.args.get(name) {
return arg.occurrences; return arg.occurrences;
} }
@ -185,14 +203,19 @@ impl<'n, 'a> ArgMatches<'n, 'a> {
/// ///
/// ```no_run /// ```no_run
/// # use clap::{App, Arg, SubCommand}; /// # use clap::{App, Arg, SubCommand};
/// # let app_matches = App::new("myapp").subcommand(SubCommand::with_name("test")).get_matches(); /// # let app_matches = App::new("myapp")
/// # .subcommand(SubCommand::with_name("test")).get_matches();
/// if let Some(matches) = app_matches.subcommand_matches("test") { /// if let Some(matches) = app_matches.subcommand_matches("test") {
/// // Use matches as normal /// // Use matches as normal
/// } /// }
/// ``` /// ```
pub fn subcommand_matches<'na>(&self, name: &'na str) -> Option<&ArgMatches> { pub fn subcommand_matches<'na>(&self,
name: &'na str)
-> Option<&ArgMatches> {
if let Some( ref sc) = self.subcommand { if let Some( ref sc) = self.subcommand {
if sc.name != name { return None; } if sc.name != name {
return None;
}
return Some(&sc.matches); return Some(&sc.matches);
} }
None None
@ -208,7 +231,8 @@ impl<'n, 'a> ArgMatches<'n, 'a> {
/// ///
/// ```no_run /// ```no_run
/// # use clap::{App, Arg, SubCommand}; /// # use clap::{App, Arg, SubCommand};
/// # let app_matches = App::new("myapp").subcommand(SubCommand::with_name("test")).get_matches(); /// # let app_matches = App::new("myapp")
/// # .subcommand(SubCommand::with_name("test")).get_matches();
/// match app_matches.subcommand_name() { /// match app_matches.subcommand_name() {
/// Some("test") => {}, // test was used /// Some("test") => {}, // test was used
/// Some("config") => {}, // config was used /// Some("config") => {}, // config was used
@ -230,7 +254,8 @@ impl<'n, 'a> ArgMatches<'n, 'a> {
/// ///
/// ```no_run /// ```no_run
/// # use clap::{App, Arg, SubCommand}; /// # use clap::{App, Arg, SubCommand};
/// # let app_matches = App::new("myapp").subcommand(SubCommand::with_name("test")).get_matches(); /// # let app_matches = App::new("myapp")
/// # .subcommand(SubCommand::with_name("test")).get_matches();
/// match app_matches.subcommand() { /// match app_matches.subcommand() {
/// ("test", Some(matches)) => {}, // test was used /// ("test", Some(matches)) => {}, // test was used
/// ("config", Some(matches)) => {}, // config was used /// ("config", Some(matches)) => {}, // config was used
@ -251,7 +276,8 @@ impl<'n, 'a> ArgMatches<'n, 'a> {
/// ///
/// ```no_run /// ```no_run
/// # use clap::{App, Arg, SubCommand}; /// # use clap::{App, Arg, SubCommand};
/// # let app_matches = App::new("myapp").subcommand(SubCommand::with_name("test")).get_matches(); /// # let app_matches = App::new("myapp")
/// # .subcommand(SubCommand::with_name("test")).get_matches();
/// println!("{}",app_matches.usage()); /// println!("{}",app_matches.usage());
/// ``` /// ```
pub fn usage(&self) -> &str { pub fn usage(&self) -> &str {

View file

@ -51,7 +51,7 @@ pub struct ArgGroup<'n, 'ar> {
#[doc(hidden)] #[doc(hidden)]
pub requires: Option<Vec<&'ar str>>, pub requires: Option<Vec<&'ar str>>,
#[doc(hidden)] #[doc(hidden)]
pub conflicts: Option<Vec<&'ar str>> pub conflicts: Option<Vec<&'ar str>>,
} }
impl<'n, 'ar> ArgGroup<'n, 'ar> { impl<'n, 'ar> ArgGroup<'n, 'ar> {
@ -103,7 +103,7 @@ impl<'n, 'ar> ArgGroup<'n, 'ar> {
} }
} }
a a
}, }
"requires" => { "requires" => {
for ys in v.as_vec().unwrap() { for ys in v.as_vec().unwrap() {
if let Some(s) = ys.as_str() { if let Some(s) = ys.as_str() {
@ -111,7 +111,7 @@ impl<'n, 'ar> ArgGroup<'n, 'ar> {
} }
} }
a a
}, }
"conflicts_with" => { "conflicts_with" => {
for ys in v.as_vec().unwrap() { for ys in v.as_vec().unwrap() {
if let Some(s) = ys.as_str() { if let Some(s) = ys.as_str() {
@ -119,8 +119,9 @@ impl<'n, 'ar> ArgGroup<'n, 'ar> {
} }
} }
a a
}, }
s => panic!("Unknown ArgGroup setting '{}' in YAML file for ArgGroup '{}'", s, name_str) s => panic!("Unknown ArgGroup setting '{}' in YAML file for \
ArgGroup '{}'", s, name_str),
} }
} }
@ -139,7 +140,9 @@ impl<'n, 'ar> ArgGroup<'n, 'ar> {
/// # ArgGroup::with_name("conifg") /// # ArgGroup::with_name("conifg")
/// .add("config") /// .add("config")
/// # ).get_matches(); /// # ).get_matches();
pub fn add(mut self, n: &'ar str) -> Self { pub fn add(mut self,
n: &'ar str)
-> Self {
self.args.push(n); self.args.push(n);
self self
} }
@ -156,7 +159,9 @@ impl<'n, 'ar> ArgGroup<'n, 'ar> {
/// # ArgGroup::with_name("conifg") /// # ArgGroup::with_name("conifg")
/// .add_all(&["config", "input", "output"]) /// .add_all(&["config", "input", "output"])
/// # ).get_matches(); /// # ).get_matches();
pub fn add_all(mut self, ns: &[&'ar str]) -> Self { pub fn add_all(mut self,
ns: &[&'ar str])
-> Self {
for n in ns { for n in ns {
self = self.add(n); self = self.add(n);
} }
@ -178,7 +183,9 @@ impl<'n, 'ar> ArgGroup<'n, 'ar> {
/// # ArgGroup::with_name("conifg") /// # ArgGroup::with_name("conifg")
/// .required(true) /// .required(true)
/// # ).get_matches(); /// # ).get_matches();
pub fn required(mut self, r: bool) -> Self { pub fn required(mut self,
r: bool)
-> Self {
self.required = r; self.required = r;
self self
} }
@ -199,7 +206,9 @@ impl<'n, 'ar> ArgGroup<'n, 'ar> {
/// # ArgGroup::with_name("conifg") /// # ArgGroup::with_name("conifg")
/// .requires("config") /// .requires("config")
/// # ).get_matches(); /// # ).get_matches();
pub fn requires(mut self, n: &'ar str) -> Self { pub fn requires(mut self,
n: &'ar str)
-> Self {
if let Some(ref mut reqs) = self.requires { if let Some(ref mut reqs) = self.requires {
reqs.push(n); reqs.push(n);
} else { } else {
@ -224,7 +233,9 @@ impl<'n, 'ar> ArgGroup<'n, 'ar> {
/// # ArgGroup::with_name("conifg") /// # ArgGroup::with_name("conifg")
/// .requires_all(&["config", "input"]) /// .requires_all(&["config", "input"])
/// # ).get_matches(); /// # ).get_matches();
pub fn requires_all(mut self, ns: &[&'ar str]) -> Self { pub fn requires_all(mut self,
ns: &[&'ar str])
-> Self {
for n in ns { for n in ns {
self = self.requires(n); self = self.requires(n);
} }
@ -247,7 +258,9 @@ impl<'n, 'ar> ArgGroup<'n, 'ar> {
/// # ArgGroup::with_name("conifg") /// # ArgGroup::with_name("conifg")
/// .conflicts_with("config") /// .conflicts_with("config")
/// # ).get_matches(); /// # ).get_matches();
pub fn conflicts_with(mut self, n: &'ar str) -> Self { pub fn conflicts_with(mut self,
n: &'ar str)
-> Self {
if let Some(ref mut confs) = self.conflicts { if let Some(ref mut confs) = self.conflicts {
confs.push(n); confs.push(n);
} else { } else {
@ -272,7 +285,9 @@ impl<'n, 'ar> ArgGroup<'n, 'ar> {
/// # ArgGroup::with_name("conifg") /// # ArgGroup::with_name("conifg")
/// .conflicts_with_all(&["config", "input"]) /// .conflicts_with_all(&["config", "input"])
/// # ).get_matches(); /// # ).get_matches();
pub fn conflicts_with_all(mut self, ns: &[&'ar str]) -> Self { pub fn conflicts_with_all(mut self,
ns: &[&'ar str])
-> Self {
for n in ns { for n in ns {
self = self.conflicts_with(n); self = self.conflicts_with(n);
} }
@ -281,7 +296,9 @@ impl<'n, 'ar> ArgGroup<'n, 'ar> {
} }
impl<'n, 'ar> Debug for ArgGroup<'n, 'ar> { impl<'n, 'ar> Debug for ArgGroup<'n, 'ar> {
fn fmt(&self, f: &mut Formatter) -> Result { fn fmt(&self,
f: &mut Formatter)
-> Result {
write!(f, "{{ write!(f, "{{
name:{:?}, name:{:?},
args: {:?}, args: {:?},

View file

@ -7,5 +7,6 @@ pub struct MatchedArg {
#[doc(hidden)] #[doc(hidden)]
pub occurrences: u8, pub occurrences: u8,
#[doc(hidden)] #[doc(hidden)]
pub values: Option<BTreeMap<u8, String>> // Consider VecMap<String> once stablized
pub values: Option<BTreeMap<u8, String>>,
} }

View file

@ -27,7 +27,7 @@ pub struct SubCommand<'n, 'a> {
#[doc(hidden)] #[doc(hidden)]
pub name: &'n str, pub name: &'n str,
#[doc(hidden)] #[doc(hidden)]
pub matches: ArgMatches<'n, 'a> pub matches: ArgMatches<'n, 'a>,
} }
impl<'n, 'a> SubCommand<'n, 'a> { impl<'n, 'a> SubCommand<'n, 'a> {

View file

@ -26,7 +26,8 @@ impl<T: AsRef<str>> Format<T> {
#[cfg(all(feature = "color", not(target_os = "windows")))] #[cfg(all(feature = "color", not(target_os = "windows")))]
impl<T: AsRef<str>> fmt::Display for Format<T> { impl<T: AsRef<str>> fmt::Display for Format<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self,
f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.format()) write!(f, "{}", &self.format())
} }
} }
@ -44,7 +45,8 @@ impl<T: fmt::Display> Format<T> {
#[cfg(any(not(feature = "color"), target_os = "windows"))] #[cfg(any(not(feature = "color"), target_os = "windows"))]
impl<T: fmt::Display> fmt::Display for Format<T> { impl<T: fmt::Display> fmt::Display for Format<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self,
f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.format()) write!(f, "{}", &self.format())
} }
} }

View file

@ -80,7 +80,8 @@ fn test_enums() {
#[test] #[test]
fn create_app() { fn create_app() {
let _ = App::new("test").version("1.0").author("kevin").about("does awesome things").get_matches(); let _ =
App::new("test").version("1.0").author("kevin").about("does awesome things").get_matches();
} }
#[test] #[test]
@ -908,5 +909,3 @@ fn create_multiple_subcommands() {
.arg(Arg::with_name("other").long("other")) .arg(Arg::with_name("other").long("other"))
.get_matches(); .get_matches();
} }

View file

@ -43,26 +43,32 @@ impl<'u> Iterator for UsageParser<'u> {
let closing = match c { let closing = match c {
'[' => ']', '[' => ']',
'<' => '>', '<' => '>',
_ => unreachable!() _ => unreachable!(),
}; };
while let Some(c) = self.chars.next() { while let Some(c) = self.chars.next() {
self.e += 1; self.e += 1;
if c == closing { break } if c == closing {
break
}
}
if self.e > self.usage.len() {
return None
} }
if self.e > self.usage.len() { return None }
let name = &self.usage[self.s..self.e]; let name = &self.usage[self.s..self.e];
return Some(UsageToken::Name(name, if c == '<' { Some(true) } else { None })); return Some(UsageToken::Name(name, if c == '<' { Some(true) } else { None }));
}, }
Some('\'') => { Some('\'') => {
self.s = self.e + 2; self.s = self.e + 2;
self.e = self.usage.len() - 1; self.e = self.usage.len() - 1;
while let Some(_) = self.chars.next() { continue } while let Some(_) = self.chars.next() {
continue
}
return Some(UsageToken::Help(&self.usage[self.s..self.e])); return Some(UsageToken::Help(&self.usage[self.s..self.e]));
}, }
Some('-') => { Some('-') => {
self.e += 1; self.e += 1;
match self.chars.next() { match self.chars.next() {
@ -75,15 +81,19 @@ impl<'u> Iterator for UsageParser<'u> {
while let Some(c) = self.chars.next() { while let Some(c) = self.chars.next() {
self.e += 1; self.e += 1;
if c == ' ' || c == '=' || c == '.' { break } if c == ' ' || c == '=' || c == '.' {
break
}
}
if self.e > self.usage.len() {
return None
} }
if self.e > self.usage.len() { return None }
if self.e == self.usage.len() - 1 { if self.e == self.usage.len() - 1 {
return Some(UsageToken::Long(&self.usage[self.s..])) return Some(UsageToken::Long(&self.usage[self.s..]))
} }
return Some(UsageToken::Long(&self.usage[self.s..self.e])) return Some(UsageToken::Long(&self.usage[self.s..self.e]))
}, }
Some(c) => { Some(c) => {
// When short is first don't increment e // When short is first don't increment e
if self.e != 1 { if self.e != 1 {
@ -94,12 +104,12 @@ impl<'u> Iterator for UsageParser<'u> {
return None return None
} }
return Some(UsageToken::Short(c)) return Some(UsageToken::Short(c))
}, }
_ => { _ => {
return None return None
} }
} }
}, }
Some('.') => { Some('.') => {
self.e += 1; self.e += 1;
let mut mult = false; let mut mult = false;
@ -108,7 +118,9 @@ impl<'u> Iterator for UsageParser<'u> {
match self.chars.next() { match self.chars.next() {
// longs consume one '.' so they match '.. ' whereas shorts can // longs consume one '.' so they match '.. ' whereas shorts can
// match '...' // match '...'
Some('.') | Some(' ') => { mult = true; }, Some('.') | Some(' ') => {
mult = true;
}
_ => { _ => {
// if there is no help or following space all we can match is '..' // if there is no help or following space all we can match is '..'
if self.e == self.usage.len() - 1 { if self.e == self.usage.len() - 1 {
@ -118,18 +130,19 @@ impl<'u> Iterator for UsageParser<'u> {
} }
} }
} }
if mult { return Some(UsageToken::Multiple) } if mult {
}, return Some(UsageToken::Multiple)
}
}
Some(' ') | Some('=') | Some(']') | Some('>') | Some('\t') | Some(',') => { Some(' ') | Some('=') | Some(']') | Some('>') | Some('\t') | Some(',') => {
self.e += 1; self.e += 1;
continue continue
}, }
None => { None => {
return None return None
}, }
Some(c) => { Some(c) => panic!("Usage parser error, unexpected \
panic!("Usage parser error, unexpected \"{}\" at \"{}\", check from_usage call", c, self.usage); \"{}\" at \"{}\", check from_usage call", c, self.usage),
}
} }
} }
} }