diff --git a/.gitignore b/.gitignore index 4fffb2f8..f0d90b95 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,6 @@ +# Cargo /target /Cargo.lock + +#IDE +.vscode \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index d083b878..99a24622 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -92,24 +92,32 @@ //! } //! ``` -#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", - html_favicon_url = "https://www.rust-lang.org/favicon.ico", - html_root_url = "https://docs.rs/getopts/0.2.18")] +#![doc( + html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://docs.rs/getopts/0.2.18" +)] #![deny(missing_docs)] #![cfg_attr(test, deny(warnings))] #![cfg_attr(rust_build, feature(staged_api))] #![cfg_attr(rust_build, staged_api)] -#![cfg_attr(rust_build, - unstable(feature = "rustc_private", - reason = "use the crates.io `getopts` library instead"))] +#![cfg_attr( + rust_build, + unstable( + feature = "rustc_private", + reason = "use the crates.io `getopts` library instead" + ) +)] -#[cfg(test)] #[macro_use] extern crate log; +#[cfg(test)] +#[macro_use] +extern crate log; extern crate unicode_width; -use self::Name::*; +use self::Fail::*; use self::HasArg::*; +use self::Name::*; use self::Occur::*; -use self::Fail::*; use self::Optval::*; use std::error::Error; @@ -127,8 +135,14 @@ mod tests; /// A description of the options that a program can handle. pub struct Options { grps: Vec, - parsing_style : ParsingStyle, - long_only: bool + parsing_style: ParsingStyle, + long_only: bool, +} + +impl Default for Options { + fn default() -> Self { + Self::new() + } } impl Options { @@ -137,7 +151,7 @@ impl Options { Options { grps: Vec::new(), parsing_style: ParsingStyle::FloatingFrees, - long_only: false + long_only: false, } } @@ -161,16 +175,23 @@ impl Options { } /// Create a generic option group, stating all parameters explicitly. - pub fn opt(&mut self, short_name: &str, long_name: &str, desc: &str, - hint: &str, hasarg: HasArg, occur: Occur) -> &mut Options { + pub fn opt( + &mut self, + short_name: &str, + long_name: &str, + desc: &str, + hint: &str, + hasarg: HasArg, + occur: Occur, + ) -> &mut Options { validate_names(short_name, long_name); self.grps.push(OptGroup { short_name: short_name.to_string(), long_name: long_name.to_string(), hint: hint.to_string(), desc: desc.to_string(), - hasarg: hasarg, - occur: occur + hasarg, + occur, }); self } @@ -180,8 +201,7 @@ impl Options { /// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none /// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none /// * `desc` - Description for usage help - pub fn optflag(&mut self, short_name: &str, long_name: &str, desc: &str) - -> &mut Options { + pub fn optflag(&mut self, short_name: &str, long_name: &str, desc: &str) -> &mut Options { validate_names(short_name, long_name); self.grps.push(OptGroup { short_name: short_name.to_string(), @@ -189,7 +209,7 @@ impl Options { hint: "".to_string(), desc: desc.to_string(), hasarg: No, - occur: Optional + occur: Optional, }); self } @@ -200,8 +220,7 @@ impl Options { /// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none /// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none /// * `desc` - Description for usage help - pub fn optflagmulti(&mut self, short_name: &str, long_name: &str, desc: &str) - -> &mut Options { + pub fn optflagmulti(&mut self, short_name: &str, long_name: &str, desc: &str) -> &mut Options { validate_names(short_name, long_name); self.grps.push(OptGroup { short_name: short_name.to_string(), @@ -209,7 +228,7 @@ impl Options { hint: "".to_string(), desc: desc.to_string(), hasarg: No, - occur: Multi + occur: Multi, }); self } @@ -221,8 +240,13 @@ impl Options { /// * `desc` - Description for usage help /// * `hint` - Hint that is used in place of the argument in the usage help, /// e.g. `"FILE"` for a `-o FILE` option - pub fn optflagopt(&mut self, short_name: &str, long_name: &str, desc: &str, - hint: &str) -> &mut Options { + pub fn optflagopt( + &mut self, + short_name: &str, + long_name: &str, + desc: &str, + hint: &str, + ) -> &mut Options { validate_names(short_name, long_name); self.grps.push(OptGroup { short_name: short_name.to_string(), @@ -230,7 +254,7 @@ impl Options { hint: hint.to_string(), desc: desc.to_string(), hasarg: Maybe, - occur: Optional + occur: Optional, }); self } @@ -243,8 +267,13 @@ impl Options { /// * `desc` - Description for usage help /// * `hint` - Hint that is used in place of the argument in the usage help, /// e.g. `"FILE"` for a `-o FILE` option - pub fn optmulti(&mut self, short_name: &str, long_name: &str, desc: &str, hint: &str) - -> &mut Options { + pub fn optmulti( + &mut self, + short_name: &str, + long_name: &str, + desc: &str, + hint: &str, + ) -> &mut Options { validate_names(short_name, long_name); self.grps.push(OptGroup { short_name: short_name.to_string(), @@ -252,7 +281,7 @@ impl Options { hint: hint.to_string(), desc: desc.to_string(), hasarg: Yes, - occur: Multi + occur: Multi, }); self } @@ -264,8 +293,13 @@ impl Options { /// * `desc` - Description for usage help /// * `hint` - Hint that is used in place of the argument in the usage help, /// e.g. `"FILE"` for a `-o FILE` option - pub fn optopt(&mut self, short_name: &str, long_name: &str, desc: &str, hint: &str) - -> &mut Options { + pub fn optopt( + &mut self, + short_name: &str, + long_name: &str, + desc: &str, + hint: &str, + ) -> &mut Options { validate_names(short_name, long_name); self.grps.push(OptGroup { short_name: short_name.to_string(), @@ -273,7 +307,7 @@ impl Options { hint: hint.to_string(), desc: desc.to_string(), hasarg: Yes, - occur: Optional + occur: Optional, }); self } @@ -285,8 +319,13 @@ impl Options { /// * `desc` - Description for usage help /// * `hint` - Hint that is used in place of the argument in the usage help, /// e.g. `"FILE"` for a `-o FILE` option - pub fn reqopt(&mut self, short_name: &str, long_name: &str, desc: &str, hint: &str) - -> &mut Options { + pub fn reqopt( + &mut self, + short_name: &str, + long_name: &str, + desc: &str, + hint: &str, + ) -> &mut Options { validate_names(short_name, long_name); self.grps.push(OptGroup { short_name: short_name.to_string(), @@ -294,7 +333,7 @@ impl Options { hint: hint.to_string(), desc: desc.to_string(), hasarg: Yes, - occur: Req + occur: Req, }); self } @@ -308,23 +347,29 @@ impl Options { /// Returns `Err(Fail)` on failure: use the `Debug` implementation of `Fail` /// to display information about it. pub fn parse(&self, args: C) -> Result - where C::Item: AsRef + where + C::Item: AsRef, { let opts: Vec = self.grps.iter().map(|x| x.long_to_short()).collect(); - let mut vals = (0 .. opts.len()).map(|_| Vec::new()).collect::>>(); + let mut vals = (0..opts.len()) + .map(|_| Vec::new()) + .collect::>>(); let mut free: Vec = Vec::new(); - let args = args.into_iter().map(|i| { - i.as_ref().to_str().ok_or_else(|| { - Fail::UnrecognizedOption(format!("{:?}", i.as_ref())) - }).map(|s| s.to_owned()) - }).collect::<::std::result::Result,_>>()?; + let args = args + .into_iter() + .map(|i| { + i.as_ref() + .to_str() + .ok_or_else(|| Fail::UnrecognizedOption(format!("{:?}", i.as_ref()))) + .map(|s| s.to_owned()) + }).collect::<::std::result::Result, _>>()?; let mut args = args.into_iter().peekable(); while let Some(cur) = args.next() { if !is_arg(&cur) { free.push(cur); match self.parsing_style { - ParsingStyle::FloatingFrees => {}, + ParsingStyle::FloatingFrees => {} ParsingStyle::StopAtFirstFree => { free.extend(args); break; @@ -363,15 +408,15 @@ impl Options { */ let opt_id = match find_opt(&opts, &opt) { - Some(id) => id, - None => return Err(UnrecognizedOption(opt.to_string())) + Some(id) => id, + None => return Err(UnrecognizedOption(opt.to_string())), }; names.push(opt); let arg_follows = match opts[opt_id].hasarg { Yes | Maybe => true, - No => false + No => false, }; if arg_follows { @@ -387,40 +432,43 @@ impl Options { for nm in names.iter() { name_pos += 1; let optid = match find_opt(&opts, &nm) { - Some(id) => id, - None => return Err(UnrecognizedOption(nm.to_string())) + Some(id) => id, + None => return Err(UnrecognizedOption(nm.to_string())), }; match opts[optid].hasarg { - No => { - if name_pos == names.len() && !i_arg.is_none() { - return Err(UnexpectedArgument(nm.to_string())); - } - vals[optid].push(Given); - } - Maybe => { - // Note that here we do not handle `--arg value`. - // This matches GNU getopt behavior; but also - // makes sense, because if this were accepted, - // then users could only write a "Maybe" long - // option at the end of the arguments when - // FloatingFrees is in use. - if let Some(i_arg) = i_arg.take() { - vals[optid].push(Val(i_arg)); - } else if was_long || name_pos < names.len() || args.peek().map_or(true, |n| is_arg(&n)) { + No => { + if name_pos == names.len() && i_arg.is_some() { + return Err(UnexpectedArgument(nm.to_string())); + } vals[optid].push(Given); - } else { - vals[optid].push(Val(args.next().unwrap())); } - } - Yes => { - if let Some(i_arg) = i_arg.take() { - vals[optid].push(Val(i_arg)); - } else if let Some(n) = args.next() { - vals[optid].push(Val(n)); - } else { - return Err(ArgumentMissing(nm.to_string())); + Maybe => { + // Note that here we do not handle `--arg value`. + // This matches GNU getopt behavior; but also + // makes sense, because if this were accepted, + // then users could only write a "Maybe" long + // option at the end of the arguments when + // FloatingFrees is in use. + if let Some(i_arg) = i_arg.take() { + vals[optid].push(Val(i_arg)); + } else if was_long + || name_pos < names.len() + || args.peek().map_or(true, |n| is_arg(&n)) + { + vals[optid].push(Given); + } else { + vals[optid].push(Val(args.next().unwrap())); + } + } + Yes => { + if let Some(i_arg) = i_arg.take() { + vals[optid].push(Val(i_arg)); + } else if let Some(n) = args.next() { + vals[optid].push(Val(n)); + } else { + return Err(ArgumentMissing(nm.to_string())); + } } - } } } } @@ -434,51 +482,58 @@ impl Options { return Err(OptionDuplicated(opt.name.to_string())); } } - Ok(Matches { - opts: opts, - vals: vals, - free: free - }) + Ok(Matches { opts, vals, free }) } /// Derive a short one-line usage summary from a set of long options. pub fn short_usage(&self, program_name: &str) -> String { let mut line = format!("Usage: {} ", program_name); - line.push_str(&self.grps.iter() - .map(format_option) - .collect::>() - .join(" ")); + line.push_str( + &self + .grps + .iter() + .map(format_option) + .collect::>() + .join(" "), + ); line } - /// Derive a formatted message from a set of options. pub fn usage(&self, brief: &str) -> String { - self.usage_with_format(|opts| - format!("{}\n\nOptions:\n{}\n", brief, opts.collect::>().join("\n"))) + self.usage_with_format(|opts| { + format!( + "{}\n\nOptions:\n{}\n", + brief, + opts.collect::>().join("\n") + ) + }) } /// Derive a custom formatted message from a set of options. The formatted options provided to /// a closure as an iterator. - pub fn usage_with_format) -> String>(&self, mut formatter: F) -> String { + pub fn usage_with_format) -> String>( + &self, + mut formatter: F, + ) -> String { formatter(&mut self.usage_items()) } /// Derive usage items from a set of options. - fn usage_items<'a>(&'a self) -> Box + 'a> { + fn usage_items<'a>(&'a self) -> Box + 'a> { let desc_sep = format!("\n{}", repeat(" ").take(24).collect::()); - let any_short = self.grps.iter().any(|optref| { - optref.short_name.len() > 0 - }); + let any_short = self.grps.iter().any(|optref| !optref.short_name.is_empty()); let rows = self.grps.iter().map(move |optref| { - let OptGroup{short_name, - long_name, - hint, - desc, - hasarg, - ..} = (*optref).clone(); + let OptGroup { + short_name, + long_name, + hint, + desc, + hasarg, + .. + } = (*optref).clone(); let mut row = " ".to_string(); @@ -527,7 +582,7 @@ impl Options { let rowlen = row.width(); if rowlen < 24 { - for _ in 0 .. 24 - rowlen { + for _ in 0..24 - rowlen { row.push(' '); } } else { @@ -540,19 +595,23 @@ impl Options { row }); - Box::new(rows) + Box::new(rows) } } fn validate_names(short_name: &str, long_name: &str) { let len = short_name.len(); - assert!(len == 1 || len == 0, - "the short_name (first argument) should be a single character, \ - or an empty string for none"); + assert!( + len == 1 || len == 0, + "the short_name (first argument) should be a single character, \ + or an empty string for none" + ); let len = long_name.len(); - assert!(len == 0 || len > 1, - "the long_name (second argument) should be longer than a single \ - character, or an empty string for none"); + assert!( + len == 0 || len > 1, + "the long_name (second argument) should be longer than a single \ + character, or an empty string for none" + ); } /// What parsing style to use when parsing arguments. @@ -562,11 +621,11 @@ pub enum ParsingStyle { FloatingFrees, /// As soon as a "free" argument (i.e. non-flag) is encountered, stop /// considering any remaining arguments as flags. - StopAtFirstFree + StopAtFirstFree, } /// Name of an option. Either a string or a single char. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] enum Name { /// A string representing the long name of an option. /// For example: "help" @@ -577,7 +636,7 @@ enum Name { } /// Describes whether an option has an argument. -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Clone, Debug, Copy, PartialEq, Eq)] pub enum HasArg { /// The option requires an argument. Yes, @@ -588,7 +647,7 @@ pub enum HasArg { } /// Describes how often an option may occur. -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Clone, Debug, Copy, PartialEq, Eq)] pub enum Occur { /// The option occurs once. Req, @@ -599,7 +658,7 @@ pub enum Occur { } /// A description of a possible option. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] struct Opt { /// Name of the option name: Name, @@ -626,11 +685,11 @@ struct OptGroup { /// Whether option has an argument hasarg: HasArg, /// How often it can occur - occur: Occur + occur: Occur, } /// Describes whether an option is given at all or has a value. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] enum Optval { Val(String), Given, @@ -638,7 +697,7 @@ enum Optval { /// The result of checking command line arguments. Contains a vector /// of matches and a vector of free strings. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct Matches { /// Options that matched opts: Vec, @@ -692,7 +751,7 @@ impl Name { fn to_string(&self) -> String { match *self { Short(ch) => ch.to_string(), - Long(ref s) => s.to_string() + Long(ref s) => s.to_string(), } } } @@ -710,33 +769,31 @@ impl OptGroup { } = (*self).clone(); match (short_name.len(), long_name.len()) { - (0,0) => panic!("this long-format option was given no name"), - (0,_) => Opt { + (0, 0) => panic!("this long-format option was given no name"), + (0, _) => Opt { name: Long(long_name), - hasarg: hasarg, - occur: occur, - aliases: Vec::new() + hasarg, + occur, + aliases: Vec::new(), }, - (1,0) => Opt { + (1, 0) => Opt { name: Short(short_name.as_bytes()[0] as char), - hasarg: hasarg, - occur: occur, - aliases: Vec::new() + hasarg, + occur, + aliases: Vec::new(), }, - (1,_) => Opt { + (1, _) => Opt { name: Long(long_name), - hasarg: hasarg, - occur: occur, - aliases: vec!( - Opt { - name: Short(short_name.as_bytes()[0] as char), - hasarg: hasarg, - occur: occur, - aliases: Vec::new() - } - ) + hasarg, + occur, + aliases: vec![Opt { + name: Short(short_name.as_bytes()[0] as char), + hasarg: hasarg, + occur: occur, + aliases: Vec::new(), + }], }, - (_,_) => panic!("something is wrong with the long-form opt") + (_, _) => panic!("something is wrong with the long-form opt"), } } } @@ -745,7 +802,7 @@ impl Matches { fn opt_vals(&self, nm: &str) -> Vec { match find_opt(&self.opts, &Name::from_str(nm)) { Some(id) => self.vals[id].clone(), - None => panic!("No option '{}' defined", nm) + None => panic!("No option '{}' defined", nm), } } @@ -769,22 +826,22 @@ impl Matches { /// Returns true if any of several options were matched. pub fn opts_present(&self, names: &[String]) -> bool { - names.iter().any(|nm| { - match find_opt(&self.opts, &Name::from_str(&nm)) { + names + .iter() + .any(|nm| match find_opt(&self.opts, &Name::from_str(&nm)) { Some(id) if !self.vals[id].is_empty() => true, _ => false, - } - }) + }) } /// Returns the string argument supplied to one of several matching options or `None`. pub fn opts_str(&self, names: &[String]) -> Option { - names.iter().filter_map(|nm| { - match self.opt_val(&nm) { + names + .iter() + .filter_map(|nm| match self.opt_val(&nm) { Some(Val(s)) => Some(s), _ => None, - } - }).next() + }).next() } /// Returns a vector of the arguments provided to all matches of the given @@ -792,12 +849,12 @@ impl Matches { /// /// Used when an option accepts multiple values. pub fn opt_strs(&self, nm: &str) -> Vec { - self.opt_vals(nm).into_iter().filter_map(|v| { - match v { + self.opt_vals(nm) + .into_iter() + .filter_map(|v| match v { Val(s) => Some(s), _ => None, - } - }).collect() + }).collect() } /// Returns the string argument supplied to a matching option or `None`. @@ -808,7 +865,6 @@ impl Matches { } } - /// Returns the matching string, a default, or `None`. /// /// Returns `None` if the option was not present, `def` if the option was @@ -826,7 +882,8 @@ impl Matches { /// /// Similar to opt_str, also converts matching argument using FromStr. pub fn opt_get(&self, nm: &str) -> result::Result, T::Err> - where T: FromStr + where + T: FromStr, { match self.opt_val(nm) { Some(Val(s)) => Ok(Some(s.parse()?)), @@ -840,8 +897,9 @@ impl Matches { /// Similar to opt_default, except the two differences. /// Instead of returning None when argument was not present, return `def`. /// Instead of returning &str return type T, parsed using str::parse(). - pub fn opt_get_default(&self, nm: &str, def: T) - -> result::Result where T: FromStr + pub fn opt_get_default(&self, nm: &str, def: T) -> result::Result + where + T: FromStr, { match self.opt_val(nm) { Some(Val(s)) => s.parse(), @@ -859,12 +917,12 @@ fn find_opt(opts: &[Opt], nm: &Name) -> Option { // Search main options. let pos = opts.iter().position(|opt| &opt.name == nm); if pos.is_some() { - return pos + return pos; } // Search in aliases. for candidate in opts.iter() { - if candidate.aliases.iter().position(|opt| &opt.name == nm).is_some() { + if candidate.aliases.iter().any(|opt| &opt.name == nm) { return opts.iter().position(|opt| opt.name == candidate.name); } } @@ -875,21 +933,11 @@ fn find_opt(opts: &[Opt], nm: &Name) -> Option { impl fmt::Display for Fail { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - ArgumentMissing(ref nm) => { - write!(f, "Argument to option '{}' missing", *nm) - } - UnrecognizedOption(ref nm) => { - write!(f, "Unrecognized option: '{}'", *nm) - } - OptionMissing(ref nm) => { - write!(f, "Required option '{}' missing", *nm) - } - OptionDuplicated(ref nm) => { - write!(f, "Option '{}' given more than once", *nm) - } - UnexpectedArgument(ref nm) => { - write!(f, "Option '{}' does not take an argument", *nm) - } + ArgumentMissing(ref nm) => write!(f, "Argument to option '{}' missing", *nm), + UnrecognizedOption(ref nm) => write!(f, "Unrecognized option: '{}'", *nm), + OptionMissing(ref nm) => write!(f, "Required option '{}' missing", *nm), + OptionDuplicated(ref nm) => write!(f, "Option '{}' given more than once", *nm), + UnexpectedArgument(ref nm) => write!(f, "Option '{}' does not take an argument", *nm), } } } @@ -902,7 +950,7 @@ fn format_option(opt: &OptGroup) -> String { } // Use short_name if possible, but fall back to long_name. - if opt.short_name.len() > 0 { + if !opt.short_name.is_empty() { line.push('-'); line.push_str(&opt.short_name); } else { @@ -939,41 +987,42 @@ fn each_split_within(desc: &str, lim: usize) -> Vec { let mut rows = Vec::new(); for line in desc.trim().lines() { let line_chars = line.chars().chain(Some(' ')); - let words = line_chars.fold( (Vec::new(), 0, 0), |(mut words, a, z), c | { - let idx = z + c.len_utf8(); // Get the current byte offset - - // If the char is whitespace, advance the word start and maybe push a word - if c.is_whitespace() { - if a != z { - words.push(&line[a..z]); + let words = line_chars + .fold((Vec::new(), 0, 0), |(mut words, a, z), c| { + let idx = z + c.len_utf8(); // Get the current byte offset + + // If the char is whitespace, advance the word start and maybe push a word + if c.is_whitespace() { + if a != z { + words.push(&line[a..z]); + } + (words, idx, idx) } - (words, idx, idx) - } - // If the char is not whitespace, continue, retaining the current - else { - (words, a, idx) - } - }).0; + // If the char is not whitespace, continue, retaining the current + else { + (words, a, idx) + } + }).0; let mut row = String::new(); for word in words.iter() { - let sep = if row.len() > 0 { Some(" ") } else { None }; - let width = row.width() - + word.width() - + sep.map(UnicodeWidthStr::width).unwrap_or(0); + let sep = if !row.is_empty() { Some(" ") } else { None }; + let width = row.width() + word.width() + sep.map(UnicodeWidthStr::width).unwrap_or(0); if width <= lim { - if let Some(sep) = sep { row.push_str(sep) } + if let Some(sep) = sep { + row.push_str(sep) + } row.push_str(word); - continue + continue; } - if row.len() > 0 { + if !row.is_empty() { rows.push(row.clone()); row.clear(); } row.push_str(word); } - if row.len() > 0 { + if !row.is_empty() { rows.push(row); } } diff --git a/src/tests/mod.rs b/src/tests/mod.rs index 470b6299..f0774f3f 100644 --- a/src/tests/mod.rs +++ b/src/tests/mod.rs @@ -1,31 +1,39 @@ -use super::{HasArg, Name, Occur, Opt, Options, ParsingStyle}; -use super::Fail::*; use super::each_split_within; +use super::Fail::*; +use super::{HasArg, Name, Occur, Opt, Options, ParsingStyle}; #[test] fn test_split_within() { fn t(s: &str, i: usize, u: &[String]) { let v = each_split_within(&(s.to_string()), i); - assert!(v.iter().zip(u.iter()).all(|(a,b)| a == b)); + assert!(v.iter().zip(u.iter()).all(|(a, b)| a == b)); } t("", 0, &[]); t("", 15, &[]); t("hello", 15, &["hello".to_string()]); - t("\nMary had a little lamb\nLittle lamb\n", 15, &[ - "Mary had a".to_string(), - "little lamb".to_string(), - "Little lamb".to_string() - ]); - t("\nMary had a little lamb\nLittle lamb\n", ::std::usize::MAX, - &["Mary had a little lamb".to_string(), - "Little lamb".to_string() - ]); + t( + "\nMary had a little lamb\nLittle lamb\n", + 15, + &[ + "Mary had a".to_string(), + "little lamb".to_string(), + "Little lamb".to_string(), + ], + ); + t( + "\nMary had a little lamb\nLittle lamb\n", + ::std::usize::MAX, + &[ + "Mary had a little lamb".to_string(), + "Little lamb".to_string(), + ], + ); } // Tests for reqopt #[test] fn test_reqopt() { - let long_args = vec!("--test=20".to_string()); + let long_args = vec!["--test=20".to_string()]; let mut opts = Options::new(); opts.reqopt("t", "test", "testing", "TEST"); match opts.parse(&long_args) { @@ -35,9 +43,11 @@ fn test_reqopt() { assert!(m.opt_present("t")); assert_eq!(m.opt_str("t").unwrap(), "20"); } - _ => { panic!("test_reqopt failed (long arg)"); } + _ => { + panic!("test_reqopt failed (long arg)"); + } } - let short_args = vec!("-t".to_string(), "20".to_string()); + let short_args = vec!["-t".to_string(), "20".to_string()]; match opts.parse(&short_args) { Ok(ref m) => { assert!((m.opt_present("test"))); @@ -45,52 +55,56 @@ fn test_reqopt() { assert!((m.opt_present("t"))); assert_eq!(m.opt_str("t").unwrap(), "20"); } - _ => { panic!("test_reqopt failed (short arg)"); } + _ => { + panic!("test_reqopt failed (short arg)"); + } } } #[test] fn test_reqopt_missing() { - let args = vec!("blah".to_string()); + let args = vec!["blah".to_string()]; match Options::new() .reqopt("t", "test", "testing", "TEST") - .parse(&args) { - Err(OptionMissing(_)) => {}, - _ => panic!() + .parse(&args) + { + Err(OptionMissing(_)) => {} + _ => panic!(), } } #[test] fn test_reqopt_no_arg() { - let long_args = vec!("--test".to_string()); + let long_args = vec!["--test".to_string()]; let mut opts = Options::new(); opts.reqopt("t", "test", "testing", "TEST"); match opts.parse(&long_args) { - Err(ArgumentMissing(_)) => {}, - _ => panic!() + Err(ArgumentMissing(_)) => {} + _ => panic!(), } - let short_args = vec!("-t".to_string()); + let short_args = vec!["-t".to_string()]; match opts.parse(&short_args) { - Err(ArgumentMissing(_)) => {}, - _ => panic!() + Err(ArgumentMissing(_)) => {} + _ => panic!(), } } #[test] fn test_reqopt_multi() { - let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string()); + let args = vec!["--test=20".to_string(), "-t".to_string(), "30".to_string()]; match Options::new() .reqopt("t", "test", "testing", "TEST") - .parse(&args) { - Err(OptionDuplicated(_)) => {}, - _ => panic!() + .parse(&args) + { + Err(OptionDuplicated(_)) => {} + _ => panic!(), } } // Tests for optopt #[test] fn test_optopt() { - let long_args = vec!("--test=20".to_string()); + let long_args = vec!["--test=20".to_string()]; let mut opts = Options::new(); opts.optopt("t", "test", "testing", "TEST"); match opts.parse(&long_args) { @@ -100,9 +114,9 @@ fn test_optopt() { assert!((m.opt_present("t"))); assert_eq!(m.opt_str("t").unwrap(), "20"); } - _ => panic!() + _ => panic!(), } - let short_args = vec!("-t".to_string(), "20".to_string()); + let short_args = vec!["-t".to_string(), "20".to_string()]; match opts.parse(&short_args) { Ok(ref m) => { assert!((m.opt_present("test"))); @@ -110,55 +124,57 @@ fn test_optopt() { assert!((m.opt_present("t"))); assert_eq!(m.opt_str("t").unwrap(), "20"); } - _ => panic!() + _ => panic!(), } } #[test] fn test_optopt_missing() { - let args = vec!("blah".to_string()); + let args = vec!["blah".to_string()]; match Options::new() .optopt("t", "test", "testing", "TEST") - .parse(&args) { + .parse(&args) + { Ok(ref m) => { assert!(!m.opt_present("test")); assert!(!m.opt_present("t")); } - _ => panic!() + _ => panic!(), } } #[test] fn test_optopt_no_arg() { - let long_args = vec!("--test".to_string()); + let long_args = vec!["--test".to_string()]; let mut opts = Options::new(); opts.optopt("t", "test", "testing", "TEST"); match opts.parse(&long_args) { - Err(ArgumentMissing(_)) => {}, - _ => panic!() + Err(ArgumentMissing(_)) => {} + _ => panic!(), } - let short_args = vec!("-t".to_string()); + let short_args = vec!["-t".to_string()]; match opts.parse(&short_args) { - Err(ArgumentMissing(_)) => {}, - _ => panic!() + Err(ArgumentMissing(_)) => {} + _ => panic!(), } } #[test] fn test_optopt_multi() { - let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string()); + let args = vec!["--test=20".to_string(), "-t".to_string(), "30".to_string()]; match Options::new() .optopt("t", "test", "testing", "TEST") - .parse(&args) { - Err(OptionDuplicated(_)) => {}, - _ => panic!() + .parse(&args) + { + Err(OptionDuplicated(_)) => {} + _ => panic!(), } } // Tests for optflag #[test] fn test_optflag() { - let long_args = vec!("--test".to_string()); + let long_args = vec!["--test".to_string()]; let mut opts = Options::new(); opts.optflag("t", "test", "testing"); match opts.parse(&long_args) { @@ -166,185 +182,183 @@ fn test_optflag() { assert!(m.opt_present("test")); assert!(m.opt_present("t")); } - _ => panic!() + _ => panic!(), } - let short_args = vec!("-t".to_string()); + let short_args = vec!["-t".to_string()]; match opts.parse(&short_args) { Ok(ref m) => { assert!(m.opt_present("test")); assert!(m.opt_present("t")); } - _ => panic!() + _ => panic!(), } } #[test] fn test_optflag_missing() { - let args = vec!("blah".to_string()); - match Options::new() - .optflag("t", "test", "testing") - .parse(&args) { + let args = vec!["blah".to_string()]; + match Options::new().optflag("t", "test", "testing").parse(&args) { Ok(ref m) => { assert!(!m.opt_present("test")); assert!(!m.opt_present("t")); } - _ => panic!() + _ => panic!(), } } #[test] fn test_opt_end() { let args = vec!["--".to_owned(), "-t".to_owned()]; - match Options::new() - .optflag("t", "test", "testing") - .parse(&args) { + match Options::new().optflag("t", "test", "testing").parse(&args) { Ok(ref m) => { assert!(!m.opt_present("test")); assert!(!m.opt_present("t")); assert_eq!(m.free.len(), 1); assert_eq!(m.free[0], "-t"); } - _ => panic!() + _ => panic!(), } } #[test] fn test_opt_only_end() { let args = vec!["--".to_owned()]; - match Options::new() - .optflag("t", "test", "testing") - .parse(&args) { + match Options::new().optflag("t", "test", "testing").parse(&args) { Ok(ref m) => { assert!(!m.opt_present("test")); assert!(!m.opt_present("t")); assert_eq!(m.free.len(), 0); } - _ => panic!() + _ => panic!(), } } #[test] fn test_optflag_long_arg() { - let args = vec!("--test=20".to_string()); - match Options::new() - .optflag("t", "test", "testing") - .parse(&args) { - Err(UnexpectedArgument(_)) => {}, - _ => panic!() + let args = vec!["--test=20".to_string()]; + match Options::new().optflag("t", "test", "testing").parse(&args) { + Err(UnexpectedArgument(_)) => {} + _ => panic!(), } } #[test] fn test_optflag_multi() { - let args = vec!("--test".to_string(), "-t".to_string()); - match Options::new() - .optflag("t", "test", "testing") - .parse(&args) { - Err(OptionDuplicated(_)) => {}, - _ => panic!() + let args = vec!["--test".to_string(), "-t".to_string()]; + match Options::new().optflag("t", "test", "testing").parse(&args) { + Err(OptionDuplicated(_)) => {} + _ => panic!(), } } #[test] fn test_optflag_short_arg() { - let args = vec!("-t".to_string(), "20".to_string()); - match Options::new() - .optflag("t", "test", "testing") - .parse(&args) { + let args = vec!["-t".to_string(), "20".to_string()]; + match Options::new().optflag("t", "test", "testing").parse(&args) { Ok(ref m) => { // The next variable after the flag is just a free argument assert!(m.free[0] == "20"); } - _ => panic!() + _ => panic!(), } } // Tests for optflagmulti #[test] fn test_optflagmulti_short1() { - let args = vec!("-v".to_string()); + let args = vec!["-v".to_string()]; match Options::new() .optflagmulti("v", "verbose", "verbosity") - .parse(&args) { + .parse(&args) + { Ok(ref m) => { assert_eq!(m.opt_count("v"), 1); } - _ => panic!() + _ => panic!(), } } #[test] fn test_optflagmulti_short2a() { - let args = vec!("-v".to_string(), "-v".to_string()); + let args = vec!["-v".to_string(), "-v".to_string()]; match Options::new() .optflagmulti("v", "verbose", "verbosity") - .parse(&args) { + .parse(&args) + { Ok(ref m) => { assert_eq!(m.opt_count("v"), 2); } - _ => panic!() + _ => panic!(), } } #[test] fn test_optflagmulti_short2b() { - let args = vec!("-vv".to_string()); + let args = vec!["-vv".to_string()]; match Options::new() .optflagmulti("v", "verbose", "verbosity") - .parse(&args) { + .parse(&args) + { Ok(ref m) => { assert_eq!(m.opt_count("v"), 2); } - _ => panic!() + _ => panic!(), } } #[test] fn test_optflagmulti_long1() { - let args = vec!("--verbose".to_string()); + let args = vec!["--verbose".to_string()]; match Options::new() .optflagmulti("v", "verbose", "verbosity") - .parse(&args) { + .parse(&args) + { Ok(ref m) => { assert_eq!(m.opt_count("verbose"), 1); } - _ => panic!() + _ => panic!(), } } #[test] fn test_optflagmulti_long2() { - let args = vec!("--verbose".to_string(), "--verbose".to_string()); + let args = vec!["--verbose".to_string(), "--verbose".to_string()]; match Options::new() .optflagmulti("v", "verbose", "verbosity") - .parse(&args) { + .parse(&args) + { Ok(ref m) => { assert_eq!(m.opt_count("verbose"), 2); } - _ => panic!() + _ => panic!(), } } #[test] fn test_optflagmulti_mix() { - let args = vec!("--verbose".to_string(), "-v".to_string(), - "-vv".to_string(), "verbose".to_string()); + let args = vec![ + "--verbose".to_string(), + "-v".to_string(), + "-vv".to_string(), + "verbose".to_string(), + ]; match Options::new() .optflagmulti("v", "verbose", "verbosity") - .parse(&args) { + .parse(&args) + { Ok(ref m) => { assert_eq!(m.opt_count("verbose"), 4); assert_eq!(m.opt_count("v"), 4); } - _ => panic!() + _ => panic!(), } } // Tests for optflagopt #[test] fn test_optflagopt() { - let long_args = vec!("--test".to_string()); + let long_args = vec!["--test".to_string()]; let mut opts = Options::new(); opts.optflagopt("t", "test", "testing", "ARG"); match opts.parse(&long_args) { @@ -352,54 +366,54 @@ fn test_optflagopt() { assert!(m.opt_present("test")); assert!(m.opt_present("t")); } - _ => panic!() + _ => panic!(), } - let short_args = vec!("-t".to_string()); + let short_args = vec!["-t".to_string()]; match opts.parse(&short_args) { Ok(ref m) => { assert!(m.opt_present("test")); assert!(m.opt_present("t")); } - _ => panic!() + _ => panic!(), } - let short_args = vec!("-t".to_string(), "x".to_string()); + let short_args = vec!["-t".to_string(), "x".to_string()]; match opts.parse(&short_args) { Ok(ref m) => { assert_eq!(m.opt_str("t").unwrap(), "x"); assert_eq!(m.opt_str("test").unwrap(), "x"); } - _ => panic!() + _ => panic!(), } - let long_args = vec!("--test=x".to_string()); + let long_args = vec!["--test=x".to_string()]; match opts.parse(&long_args) { Ok(ref m) => { assert_eq!(m.opt_str("t").unwrap(), "x"); assert_eq!(m.opt_str("test").unwrap(), "x"); } - _ => panic!() + _ => panic!(), } - let long_args = vec!("--test".to_string(), "x".to_string()); + let long_args = vec!["--test".to_string(), "x".to_string()]; match opts.parse(&long_args) { Ok(ref m) => { assert_eq!(m.opt_str("t"), None); assert_eq!(m.opt_str("test"), None); } - _ => panic!() + _ => panic!(), } - let no_args: Vec = vec!(); + let no_args: Vec = vec![]; match opts.parse(&no_args) { Ok(ref m) => { assert!(!m.opt_present("test")); assert!(!m.opt_present("t")); } - _ => panic!() + _ => panic!(), } } // Tests for optmulti #[test] fn test_optmulti() { - let long_args = vec!("--test=20".to_string()); + let long_args = vec!["--test=20".to_string()]; let mut opts = Options::new(); opts.optmulti("t", "test", "testing", "TEST"); match opts.parse(&long_args) { @@ -409,9 +423,9 @@ fn test_optmulti() { assert!((m.opt_present("t"))); assert_eq!(m.opt_str("t").unwrap(), "20"); } - _ => panic!() + _ => panic!(), } - let short_args = vec!("-t".to_string(), "20".to_string()); + let short_args = vec!["-t".to_string(), "20".to_string()]; match opts.parse(&short_args) { Ok(ref m) => { assert!((m.opt_present("test"))); @@ -419,46 +433,48 @@ fn test_optmulti() { assert!((m.opt_present("t"))); assert_eq!(m.opt_str("t").unwrap(), "20"); } - _ => panic!() + _ => panic!(), } } #[test] fn test_optmulti_missing() { - let args = vec!("blah".to_string()); + let args = vec!["blah".to_string()]; match Options::new() .optmulti("t", "test", "testing", "TEST") - .parse(&args) { + .parse(&args) + { Ok(ref m) => { assert!(!m.opt_present("test")); assert!(!m.opt_present("t")); } - _ => panic!() + _ => panic!(), } } #[test] fn test_optmulti_no_arg() { - let long_args = vec!("--test".to_string()); + let long_args = vec!["--test".to_string()]; let mut opts = Options::new(); opts.optmulti("t", "test", "testing", "TEST"); match opts.parse(&long_args) { - Err(ArgumentMissing(_)) => {}, - _ => panic!() + Err(ArgumentMissing(_)) => {} + _ => panic!(), } - let short_args = vec!("-t".to_string()); + let short_args = vec!["-t".to_string()]; match opts.parse(&short_args) { - Err(ArgumentMissing(_)) => {}, - _ => panic!() + Err(ArgumentMissing(_)) => {} + _ => panic!(), } } #[test] fn test_optmulti_multi() { - let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string()); + let args = vec!["--test=20".to_string(), "-t".to_string(), "30".to_string()]; match Options::new() .optmulti("t", "test", "testing", "TEST") - .parse(&args) { + .parse(&args) + { Ok(ref m) => { assert!(m.opt_present("test")); assert_eq!(m.opt_str("test").unwrap(), "20"); @@ -468,57 +484,58 @@ fn test_optmulti_multi() { assert!(pair[0] == "20"); assert!(pair[1] == "30"); } - _ => panic!() + _ => panic!(), } } #[test] fn test_free_argument_is_hyphen() { - let args = vec!("-".to_string()); + let args = vec!["-".to_string()]; match Options::new().parse(&args) { Ok(ref m) => { assert_eq!(m.free.len(), 1); assert_eq!(m.free[0], "-"); } - _ => panic!() + _ => panic!(), } } #[test] fn test_unrecognized_option() { - let long_args = vec!("--untest".to_string()); + let long_args = vec!["--untest".to_string()]; let mut opts = Options::new(); opts.optmulti("t", "test", "testing", "TEST"); match opts.parse(&long_args) { - Err(UnrecognizedOption(_)) => {}, - _ => panic!() + Err(UnrecognizedOption(_)) => {} + _ => panic!(), } - let short_args = vec!("-u".to_string()); + let short_args = vec!["-u".to_string()]; match opts.parse(&short_args) { - Err(UnrecognizedOption(_)) => {}, - _ => panic!() + Err(UnrecognizedOption(_)) => {} + _ => panic!(), } } #[test] fn test_combined() { - let args = - vec!("prog".to_string(), - "free1".to_string(), - "-s".to_string(), - "20".to_string(), - "free2".to_string(), - "--flag".to_string(), - "--long=30".to_string(), - "-f".to_string(), - "-m".to_string(), - "40".to_string(), - "-m".to_string(), - "50".to_string(), - "-n".to_string(), - "-A B".to_string(), - "-n".to_string(), - "-60 70".to_string()); + let args = vec![ + "prog".to_string(), + "free1".to_string(), + "-s".to_string(), + "20".to_string(), + "free2".to_string(), + "--flag".to_string(), + "--long=30".to_string(), + "-f".to_string(), + "-m".to_string(), + "40".to_string(), + "-m".to_string(), + "50".to_string(), + "-n".to_string(), + "-A B".to_string(), + "-n".to_string(), + "-60 70".to_string(), + ]; match Options::new() .optopt("s", "something", "something", "SOMETHING") .optflag("", "flag", "a flag") @@ -527,7 +544,8 @@ fn test_combined() { .optmulti("m", "", "mmmmmm", "YUM") .optmulti("n", "", "nothing", "NOTHING") .optopt("", "notpresent", "nothing to see here", "NOPE") - .parse(&args) { + .parse(&args) + { Ok(ref m) => { assert!(m.free[0] == "prog"); assert!(m.free[1] == "free1"); @@ -544,22 +562,24 @@ fn test_combined() { assert!(pair[1] == "-60 70"); assert!((!m.opt_present("notpresent"))); } - _ => panic!() + _ => panic!(), } } #[test] fn test_mixed_stop() { - let args = - vec!("-a".to_string(), - "b".to_string(), - "-c".to_string(), - "d".to_string()); + let args = vec![ + "-a".to_string(), + "b".to_string(), + "-c".to_string(), + "d".to_string(), + ]; match Options::new() .parsing_style(ParsingStyle::StopAtFirstFree) .optflag("a", "", "") .optopt("c", "", "", "") - .parse(&args) { + .parse(&args) + { Ok(ref m) => { println!("{}", m.opt_present("c")); assert!(m.opt_present("a")); @@ -569,22 +589,24 @@ fn test_mixed_stop() { assert_eq!(m.free[1], "-c"); assert_eq!(m.free[2], "d"); } - _ => panic!() + _ => panic!(), } } #[test] fn test_mixed_stop_hyphen() { - let args = - vec!("-a".to_string(), - "-".to_string(), - "-c".to_string(), - "d".to_string()); + let args = vec![ + "-a".to_string(), + "-".to_string(), + "-c".to_string(), + "d".to_string(), + ]; match Options::new() .parsing_style(ParsingStyle::StopAtFirstFree) .optflag("a", "", "") .optopt("c", "", "", "") - .parse(&args) { + .parse(&args) + { Ok(ref m) => { println!("{}", m.opt_present("c")); assert!(m.opt_present("a")); @@ -594,7 +616,7 @@ fn test_mixed_stop_hyphen() { assert_eq!(m.free[1], "-c"); assert_eq!(m.free[2], "d"); } - _ => panic!() + _ => panic!(), } } @@ -605,10 +627,10 @@ fn test_multi() { opts.optopt("", "encrypt", "encrypt", "ENCRYPT"); opts.optopt("f", "", "flag", "FLAG"); - let args_single = vec!("-e".to_string(), "foo".to_string()); + let args_single = vec!["-e".to_string(), "foo".to_string()]; let matches_single = &match opts.parse(&args_single) { Ok(m) => m, - Err(_) => panic!() + _ => panic!(), }; assert!(matches_single.opts_present(&["e".to_string()])); assert!(matches_single.opts_present(&["encrypt".to_string(), "e".to_string()])); @@ -618,16 +640,28 @@ fn test_multi() { assert!(!matches_single.opts_present(&[])); assert_eq!(matches_single.opts_str(&["e".to_string()]).unwrap(), "foo"); - assert_eq!(matches_single.opts_str(&["e".to_string(), "encrypt".to_string()]).unwrap(), - "foo"); - assert_eq!(matches_single.opts_str(&["encrypt".to_string(), "e".to_string()]).unwrap(), - "foo"); + assert_eq!( + matches_single + .opts_str(&["e".to_string(), "encrypt".to_string()]) + .unwrap(), + "foo" + ); + assert_eq!( + matches_single + .opts_str(&["encrypt".to_string(), "e".to_string()]) + .unwrap(), + "foo" + ); - let args_both = vec!("-e".to_string(), "foo".to_string(), "--encrypt".to_string(), - "foo".to_string()); + let args_both = vec![ + "-e".to_string(), + "foo".to_string(), + "--encrypt".to_string(), + "foo".to_string(), + ]; let matches_both = &match opts.parse(&args_both) { Ok(m) => m, - Err(_) => panic!() + _ => panic!(), }; assert!(matches_both.opts_present(&["e".to_string()])); assert!(matches_both.opts_present(&["encrypt".to_string()])); @@ -638,39 +672,51 @@ fn test_multi() { assert!(!matches_both.opts_present(&[])); assert_eq!(matches_both.opts_str(&["e".to_string()]).unwrap(), "foo"); - assert_eq!(matches_both.opts_str(&["encrypt".to_string()]).unwrap(), "foo"); - assert_eq!(matches_both.opts_str(&["e".to_string(), "encrypt".to_string()]).unwrap(), - "foo"); - assert_eq!(matches_both.opts_str(&["encrypt".to_string(), "e".to_string()]).unwrap(), - "foo"); + assert_eq!( + matches_both.opts_str(&["encrypt".to_string()]).unwrap(), + "foo" + ); + assert_eq!( + matches_both + .opts_str(&["e".to_string(), "encrypt".to_string()]) + .unwrap(), + "foo" + ); + assert_eq!( + matches_both + .opts_str(&["encrypt".to_string(), "e".to_string()]) + .unwrap(), + "foo" + ); } #[test] fn test_nospace() { - let args = vec!("-Lfoo".to_string(), "-M.".to_string()); + let args = vec!["-Lfoo".to_string(), "-M.".to_string()]; let matches = &match Options::new() .optmulti("L", "", "library directory", "LIB") .optmulti("M", "", "something", "MMMM") - .parse(&args) { + .parse(&args) + { Ok(m) => m, - Err(_) => panic!() + _ => panic!(), }; assert!(matches.opts_present(&["L".to_string()])); assert_eq!(matches.opts_str(&["L".to_string()]).unwrap(), "foo"); assert!(matches.opts_present(&["M".to_string()])); assert_eq!(matches.opts_str(&["M".to_string()]).unwrap(), "."); - } #[test] fn test_nospace_conflict() { - let args = vec!("-vvLverbose".to_string(), "-v".to_string() ); + let args = vec!["-vvLverbose".to_string(), "-v".to_string()]; let matches = &match Options::new() .optmulti("L", "", "library directory", "LIB") .optflagmulti("v", "verbose", "Verbose") - .parse(&args) { + .parse(&args) + { Ok(m) => m, - Err(e) => panic!( "{}", e ) + Err(e) => panic!("{}", e), }; assert!(matches.opts_present(&["L".to_string()])); assert_eq!(matches.opts_str(&["L".to_string()]).unwrap(), "verbose"); @@ -686,19 +732,21 @@ fn test_long_to_short() { occur: Occur::Req, aliases: Vec::new(), }; - short.aliases = vec!(Opt { name: Name::Short('b'), + short.aliases = vec![Opt { + name: Name::Short('b'), hasarg: HasArg::Yes, occur: Occur::Req, - aliases: Vec::new() }); + aliases: Vec::new(), + }]; let mut opts = Options::new(); opts.reqopt("b", "banana", "some bananas", "VAL"); - let ref verbose = opts.grps[0]; + let verbose = &opts.grps[0]; assert!(verbose.long_to_short() == short); } #[test] fn test_aliases_long_and_short() { - let args = vec!("-a".to_string(), "--apple".to_string(), "-a".to_string()); + let args = vec!["-a".to_string(), "--apple".to_string(), "-a".to_string()]; let matches = Options::new() .optflagmulti("a", "apple", "Desc") @@ -712,15 +760,13 @@ fn test_aliases_long_and_short() { fn test_usage() { let mut opts = Options::new(); opts.reqopt("b", "banana", "Desc", "VAL"); - opts.optopt("a", "012345678901234567890123456789", - "Desc", "VAL"); + opts.optopt("a", "012345678901234567890123456789", "Desc", "VAL"); opts.optflag("k", "kiwi", "Desc"); opts.optflagopt("p", "", "Desc", "VAL"); opts.optmulti("l", "", "Desc", "VAL"); opts.optflag("", "starfruit", "Starfruit"); - let expected = -"Usage: fruits + let expected = "Usage: fruits Options: -b, --banana VAL Desc @@ -745,15 +791,23 @@ fn test_usage_description_wrapping() { // lines wrap after 78: or rather descriptions wrap after 54 let mut opts = Options::new(); - opts.optflag("k", "kiwi", - "This is a long description which won't be wrapped..+.."); // 54 - opts.optflag("a", "apple", - "This is a long description which _will_ be wrapped..+.."); - opts.optflag("b", "banana", - "HereWeNeedOneSingleWordThatIsLongerThanTheWrappingLengthAndThisIsIt"); + opts.optflag( + "k", + "kiwi", + "This is a long description which won't be wrapped..+..", + ); // 54 + opts.optflag( + "a", + "apple", + "This is a long description which _will_ be wrapped..+..", + ); + opts.optflag( + "b", + "banana", + "HereWeNeedOneSingleWordThatIsLongerThanTheWrappingLengthAndThisIsIt", + ); - let expected = -"Usage: fruits + let expected = "Usage: fruits Options: -k, --kiwi This is a long description which won't be wrapped..+.. @@ -772,14 +826,19 @@ Options: #[test] fn test_usage_description_multibyte_handling() { let mut opts = Options::new(); - opts.optflag("k", "k\u{2013}w\u{2013}", - "The word kiwi is normally spelled with two i's"); - opts.optflag("a", "apple", - "This \u{201C}description\u{201D} has some characters that could \ -confuse the line wrapping; an apple costs 0.51€ in some parts of Europe."); + opts.optflag( + "k", + "k\u{2013}w\u{2013}", + "The word kiwi is normally spelled with two i's", + ); + opts.optflag( + "a", + "apple", + "This \u{201C}description\u{201D} has some characters that could \ + confuse the line wrapping; an apple costs 0.51€ in some parts of Europe.", + ); - let expected = -"Usage: fruits + let expected = "Usage: fruits Options: -k, --k–w– The word kiwi is normally spelled with two i's @@ -798,14 +857,19 @@ Options: #[test] fn test_usage_description_newline_handling() { let mut opts = Options::new(); - opts.optflag("k", "k\u{2013}w\u{2013}", - "The word kiwi is normally spelled with two i's"); - opts.optflag("a", "apple", - "This description forces a new line.\n Here is a premature\n\ - newline"); + opts.optflag( + "k", + "k\u{2013}w\u{2013}", + "The word kiwi is normally spelled with two i's", + ); + opts.optflag( + "a", + "apple", + "This description forces a new line.\n Here is a premature\n\ + newline", + ); - let expected = -"Usage: fruits + let expected = "Usage: fruits Options: -k, --k–w– The word kiwi is normally spelled with two i's @@ -824,19 +888,20 @@ Options: #[test] fn test_usage_multiwidth() { let mut opts = Options::new(); - opts.optflag("a", "apple", "apple description"); + opts.optflag("a", "apple", "apple description"); opts.optflag("b", "banana\u{00AB}", "banana description"); opts.optflag("c", "brûlée", "brûlée quite long description"); - opts.optflag("k", "kiwi\u{20AC}", "kiwi description"); + opts.optflag("k", "kiwi\u{20AC}", "kiwi description"); opts.optflag("o", "orange\u{2039}", "orange description"); - opts.optflag("r", "raspberry-but-making-this-option-way-too-long", - "raspberry description is also quite long indeed longer than \ - every other piece of text we might encounter here and thus will \ - be automatically broken up" + opts.optflag( + "r", + "raspberry-but-making-this-option-way-too-long", + "raspberry description is also quite long indeed longer than \ + every other piece of text we might encounter here and thus will \ + be automatically broken up", ); - let expected = -"Usage: fruits + let expected = "Usage: fruits Options: -a, --apple apple description @@ -857,7 +922,6 @@ Options: assert!(usage == expected) } - #[test] fn test_usage_short_only() { let mut opts = Options::new(); @@ -865,8 +929,7 @@ fn test_usage_short_only() { opts.optflag("s", "", "Starfruit"); opts.optflagopt("a", "", "Apple", "TYPE"); - let expected = -"Usage: fruits + let expected = "Usage: fruits Options: -k VAL Kiwi @@ -887,8 +950,7 @@ fn test_usage_long_only() { opts.optflag("", "starfruit", "Starfruit"); opts.optflagopt("", "apple", "Apple", "TYPE"); - let expected = -"Usage: fruits + let expected = "Usage: fruits Options: --kiwi VAL Kiwi @@ -906,8 +968,7 @@ Options: fn test_short_usage() { let mut opts = Options::new(); opts.reqopt("b", "banana", "Desc", "VAL"); - opts.optopt("a", "012345678901234567890123456789", - "Desc", "VAL"); + opts.optopt("a", "012345678901234567890123456789", "Desc", "VAL"); opts.optflag("k", "kiwi", "Desc"); opts.optflagopt("p", "", "Desc", "VAL"); opts.optmulti("l", "", "Desc", "VAL"); @@ -934,11 +995,14 @@ fn test_args_with_equals() { opts.optopt("o", "one", "One", "INFO"); opts.optopt("t", "two", "Two", "INFO"); - let args = vec!("--one".to_string(), "A=B".to_string(), - "--two=C=D".to_string()); + let args = vec![ + "--one".to_string(), + "A=B".to_string(), + "--two=C=D".to_string(), + ]; let matches = &match opts.parse(&args) { Ok(m) => m, - Err(e) => panic!("{}", e) + Err(e) => panic!("{}", e), }; assert_eq!(matches.opts_str(&["o".to_string()]).unwrap(), "A=B"); assert_eq!(matches.opts_str(&["t".to_string()]).unwrap(), "C=D"); @@ -951,8 +1015,7 @@ fn test_long_only_usage() { opts.optflag("k", "kiwi", "Description"); opts.optflag("a", "apple", "Description"); - let expected = -"Usage: fruits + let expected = "Usage: fruits Options: -k, -kiwi Description @@ -977,11 +1040,20 @@ fn test_long_only_mode() { opts.optopt("e", "", "Description", "X"); opts.optopt("", "fruit", "Description", "X"); - let args = vec!("-a", "A", "-b=B", "--c=C", "-durian", "D", "--e", "E", - "-fruit=any"); + let args = vec![ + "-a", + "A", + "-b=B", + "--c=C", + "-durian", + "D", + "--e", + "E", + "-fruit=any", + ]; let matches = &match opts.parse(&args) { Ok(m) => m, - Err(e) => panic!("{}", e) + Err(e) => panic!("{}", e), }; assert_eq!(matches.opts_str(&["a".to_string()]).unwrap(), "A"); assert_eq!(matches.opts_str(&["b".to_string()]).unwrap(), "B"); @@ -999,10 +1071,10 @@ fn test_long_only_mode_no_short_parse() { opts.optflag("i", "ignore", "Description"); opts.optflag("", "hi", "Description"); - let args = vec!("-hi"); + let args = vec!["-hi"]; let matches = &match opts.parse(&args) { Ok(m) => m, - Err(e) => panic!("{}", e) + Err(e) => panic!("{}", e), }; assert!(matches.opt_present("hi")); assert!(!matches.opt_present("h")); @@ -1021,10 +1093,10 @@ fn test_normal_mode_no_long_parse() { opts.optflag("", "hi", "Description"); opts.long_only(false); - let args = vec!("-hi"); + let args = vec!["-hi"]; let matches = &match opts.parse(&args) { Ok(m) => m, - Err(e) => panic!("{}", e) + Err(e) => panic!("{}", e), }; assert!(!matches.opt_present("hi")); assert!(matches.opt_present("h")); @@ -1046,7 +1118,7 @@ fn test_undefined_opt_present() { let args = vec!["-h"]; match opts.parse(args) { Ok(matches) => assert!(!matches.opt_present("undefined")), - Err(e) => panic!("{}", e) + Err(e) => panic!("{}", e), } } @@ -1058,11 +1130,10 @@ fn test_opt_default() { opts.optflag("r", "run", "Description"); opts.long_only(false); - let args: Vec = ["-i", "-r", "10"] - .iter().map(|x| x.to_string()).collect(); + let args: Vec = ["-i", "-r", "10"].iter().map(|x| x.to_string()).collect(); let matches = &match opts.parse(&args) { Ok(m) => m, - Err(e) => panic!("{}", e) + Err(e) => panic!("{}", e), }; assert_eq!(matches.opt_default("help", ""), None); assert_eq!(matches.opt_default("i", "def"), Some("def".to_string())); @@ -1077,12 +1148,13 @@ fn test_opt_get() { opts.optflagopt("p", "percent", "Description", "0.0 .. 10.0"); opts.long_only(false); - let args: Vec = [ - "-i", "true", "-p", "1.1" - ].iter().map(|x| x.to_string()).collect(); + let args: Vec = ["-i", "true", "-p", "1.1"] + .iter() + .map(|x| x.to_string()) + .collect(); let matches = &match opts.parse(&args) { Ok(m) => m, - Err(e) => panic!("{}", e) + Err(e) => panic!("{}", e), }; let h_arg = matches.opt_get::("help"); assert_eq!(h_arg, Ok(None)); @@ -1101,17 +1173,18 @@ fn test_opt_get_default() { opts.optflagopt("p", "percent", "Description", "0.0 .. 10.0"); opts.long_only(false); - let args: Vec = [ - "-i", "true", "-p", "1.1" - ].iter().map(|x| x.to_string()).collect(); + let args: Vec = ["-i", "true", "-p", "1.1"] + .iter() + .map(|x| x.to_string()) + .collect(); let matches = &match opts.parse(&args) { Ok(m) => m, - Err(e) => panic!("{}", e) + Err(e) => panic!("{}", e), }; - let h_arg =matches.opt_get_default("help", 10); + let h_arg = matches.opt_get_default("help", 10); assert_eq!(h_arg, Ok(10)); let i_arg = matches.opt_get_default("i", false); assert_eq!(i_arg, Ok(true)); let p_arg = matches.opt_get_default("p", 10.2); assert_eq!(p_arg, Ok(1.1)); -} \ No newline at end of file +}