Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 87e60a0

Browse files
authoredNov 26, 2018
Merge pull request #77 from Maxgy/master
add #[derive(Debug)] to Matches struct; run cargo fmt; fix with clippy
2 parents f558c3c + ea84643 commit 87e60a0

File tree

3 files changed

+579
-453
lines changed

3 files changed

+579
-453
lines changed
 

‎.gitignore‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,6 @@
1+
# Cargo
12
/target
23
/Cargo.lock
4+
5+
#IDE
6+
.vscode

‎src/lib.rs‎

Lines changed: 241 additions & 192 deletions
Original file line numberDiff line numberDiff line change
@@ -92,24 +92,32 @@
9292
//! }
9393
//! ```
9494
95-
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
96-
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
97-
html_root_url = "https://docs.rs/getopts/0.2.18")]
95+
#![doc(
96+
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
97+
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
98+
html_root_url = "https://docs.rs/getopts/0.2.18"
99+
)]
98100
#![deny(missing_docs)]
99101
#![cfg_attr(test, deny(warnings))]
100102
#![cfg_attr(rust_build, feature(staged_api))]
101103
#![cfg_attr(rust_build, staged_api)]
102-
#![cfg_attr(rust_build,
103-
unstable(feature = "rustc_private",
104-
reason = "use the crates.io `getopts` library instead"))]
104+
#![cfg_attr(
105+
rust_build,
106+
unstable(
107+
feature = "rustc_private",
108+
reason = "use the crates.io `getopts` library instead"
109+
)
110+
)]
105111

106-
#[cfg(test)] #[macro_use] extern crate log;
112+
#[cfg(test)]
113+
#[macro_use]
114+
extern crate log;
107115
extern crate unicode_width;
108116

109-
use self::Name::*;
117+
use self::Fail::*;
110118
use self::HasArg::*;
119+
use self::Name::*;
111120
use self::Occur::*;
112-
use self::Fail::*;
113121
use self::Optval::*;
114122

115123
use std::error::Error;
@@ -127,8 +135,14 @@ mod tests;
127135
/// A description of the options that a program can handle.
128136
pub struct Options {
129137
grps: Vec<OptGroup>,
130-
parsing_style : ParsingStyle,
131-
long_only: bool
138+
parsing_style: ParsingStyle,
139+
long_only: bool,
140+
}
141+
142+
impl Default for Options {
143+
fn default() -> Self {
144+
Self::new()
145+
}
132146
}
133147

134148
impl Options {
@@ -137,7 +151,7 @@ impl Options {
137151
Options {
138152
grps: Vec::new(),
139153
parsing_style: ParsingStyle::FloatingFrees,
140-
long_only: false
154+
long_only: false,
141155
}
142156
}
143157

@@ -161,16 +175,23 @@ impl Options {
161175
}
162176

163177
/// Create a generic option group, stating all parameters explicitly.
164-
pub fn opt(&mut self, short_name: &str, long_name: &str, desc: &str,
165-
hint: &str, hasarg: HasArg, occur: Occur) -> &mut Options {
178+
pub fn opt(
179+
&mut self,
180+
short_name: &str,
181+
long_name: &str,
182+
desc: &str,
183+
hint: &str,
184+
hasarg: HasArg,
185+
occur: Occur,
186+
) -> &mut Options {
166187
validate_names(short_name, long_name);
167188
self.grps.push(OptGroup {
168189
short_name: short_name.to_string(),
169190
long_name: long_name.to_string(),
170191
hint: hint.to_string(),
171192
desc: desc.to_string(),
172-
hasarg: hasarg,
173-
occur: occur
193+
hasarg,
194+
occur,
174195
});
175196
self
176197
}
@@ -180,16 +201,15 @@ impl Options {
180201
/// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none
181202
/// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none
182203
/// * `desc` - Description for usage help
183-
pub fn optflag(&mut self, short_name: &str, long_name: &str, desc: &str)
184-
-> &mut Options {
204+
pub fn optflag(&mut self, short_name: &str, long_name: &str, desc: &str) -> &mut Options {
185205
validate_names(short_name, long_name);
186206
self.grps.push(OptGroup {
187207
short_name: short_name.to_string(),
188208
long_name: long_name.to_string(),
189209
hint: "".to_string(),
190210
desc: desc.to_string(),
191211
hasarg: No,
192-
occur: Optional
212+
occur: Optional,
193213
});
194214
self
195215
}
@@ -200,16 +220,15 @@ impl Options {
200220
/// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none
201221
/// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none
202222
/// * `desc` - Description for usage help
203-
pub fn optflagmulti(&mut self, short_name: &str, long_name: &str, desc: &str)
204-
-> &mut Options {
223+
pub fn optflagmulti(&mut self, short_name: &str, long_name: &str, desc: &str) -> &mut Options {
205224
validate_names(short_name, long_name);
206225
self.grps.push(OptGroup {
207226
short_name: short_name.to_string(),
208227
long_name: long_name.to_string(),
209228
hint: "".to_string(),
210229
desc: desc.to_string(),
211230
hasarg: No,
212-
occur: Multi
231+
occur: Multi,
213232
});
214233
self
215234
}
@@ -221,16 +240,21 @@ impl Options {
221240
/// * `desc` - Description for usage help
222241
/// * `hint` - Hint that is used in place of the argument in the usage help,
223242
/// e.g. `"FILE"` for a `-o FILE` option
224-
pub fn optflagopt(&mut self, short_name: &str, long_name: &str, desc: &str,
225-
hint: &str) -> &mut Options {
243+
pub fn optflagopt(
244+
&mut self,
245+
short_name: &str,
246+
long_name: &str,
247+
desc: &str,
248+
hint: &str,
249+
) -> &mut Options {
226250
validate_names(short_name, long_name);
227251
self.grps.push(OptGroup {
228252
short_name: short_name.to_string(),
229253
long_name: long_name.to_string(),
230254
hint: hint.to_string(),
231255
desc: desc.to_string(),
232256
hasarg: Maybe,
233-
occur: Optional
257+
occur: Optional,
234258
});
235259
self
236260
}
@@ -243,16 +267,21 @@ impl Options {
243267
/// * `desc` - Description for usage help
244268
/// * `hint` - Hint that is used in place of the argument in the usage help,
245269
/// e.g. `"FILE"` for a `-o FILE` option
246-
pub fn optmulti(&mut self, short_name: &str, long_name: &str, desc: &str, hint: &str)
247-
-> &mut Options {
270+
pub fn optmulti(
271+
&mut self,
272+
short_name: &str,
273+
long_name: &str,
274+
desc: &str,
275+
hint: &str,
276+
) -> &mut Options {
248277
validate_names(short_name, long_name);
249278
self.grps.push(OptGroup {
250279
short_name: short_name.to_string(),
251280
long_name: long_name.to_string(),
252281
hint: hint.to_string(),
253282
desc: desc.to_string(),
254283
hasarg: Yes,
255-
occur: Multi
284+
occur: Multi,
256285
});
257286
self
258287
}
@@ -264,16 +293,21 @@ impl Options {
264293
/// * `desc` - Description for usage help
265294
/// * `hint` - Hint that is used in place of the argument in the usage help,
266295
/// e.g. `"FILE"` for a `-o FILE` option
267-
pub fn optopt(&mut self, short_name: &str, long_name: &str, desc: &str, hint: &str)
268-
-> &mut Options {
296+
pub fn optopt(
297+
&mut self,
298+
short_name: &str,
299+
long_name: &str,
300+
desc: &str,
301+
hint: &str,
302+
) -> &mut Options {
269303
validate_names(short_name, long_name);
270304
self.grps.push(OptGroup {
271305
short_name: short_name.to_string(),
272306
long_name: long_name.to_string(),
273307
hint: hint.to_string(),
274308
desc: desc.to_string(),
275309
hasarg: Yes,
276-
occur: Optional
310+
occur: Optional,
277311
});
278312
self
279313
}
@@ -285,16 +319,21 @@ impl Options {
285319
/// * `desc` - Description for usage help
286320
/// * `hint` - Hint that is used in place of the argument in the usage help,
287321
/// e.g. `"FILE"` for a `-o FILE` option
288-
pub fn reqopt(&mut self, short_name: &str, long_name: &str, desc: &str, hint: &str)
289-
-> &mut Options {
322+
pub fn reqopt(
323+
&mut self,
324+
short_name: &str,
325+
long_name: &str,
326+
desc: &str,
327+
hint: &str,
328+
) -> &mut Options {
290329
validate_names(short_name, long_name);
291330
self.grps.push(OptGroup {
292331
short_name: short_name.to_string(),
293332
long_name: long_name.to_string(),
294333
hint: hint.to_string(),
295334
desc: desc.to_string(),
296335
hasarg: Yes,
297-
occur: Req
336+
occur: Req,
298337
});
299338
self
300339
}
@@ -308,23 +347,29 @@ impl Options {
308347
/// Returns `Err(Fail)` on failure: use the `Debug` implementation of `Fail`
309348
/// to display information about it.
310349
pub fn parse<C: IntoIterator>(&self, args: C) -> Result
311-
where C::Item: AsRef<OsStr>
350+
where
351+
C::Item: AsRef<OsStr>,
312352
{
313353
let opts: Vec<Opt> = self.grps.iter().map(|x| x.long_to_short()).collect();
314354

315-
let mut vals = (0 .. opts.len()).map(|_| Vec::new()).collect::<Vec<Vec<Optval>>>();
355+
let mut vals = (0..opts.len())
356+
.map(|_| Vec::new())
357+
.collect::<Vec<Vec<Optval>>>();
316358
let mut free: Vec<String> = Vec::new();
317-
let args = args.into_iter().map(|i| {
318-
i.as_ref().to_str().ok_or_else(|| {
319-
Fail::UnrecognizedOption(format!("{:?}", i.as_ref()))
320-
}).map(|s| s.to_owned())
321-
}).collect::<::std::result::Result<Vec<_>,_>>()?;
359+
let args = args
360+
.into_iter()
361+
.map(|i| {
362+
i.as_ref()
363+
.to_str()
364+
.ok_or_else(|| Fail::UnrecognizedOption(format!("{:?}", i.as_ref())))
365+
.map(|s| s.to_owned())
366+
}).collect::<::std::result::Result<Vec<_>, _>>()?;
322367
let mut args = args.into_iter().peekable();
323368
while let Some(cur) = args.next() {
324369
if !is_arg(&cur) {
325370
free.push(cur);
326371
match self.parsing_style {
327-
ParsingStyle::FloatingFrees => {},
372+
ParsingStyle::FloatingFrees => {}
328373
ParsingStyle::StopAtFirstFree => {
329374
free.extend(args);
330375
break;
@@ -363,15 +408,15 @@ impl Options {
363408
*/
364409

365410
let opt_id = match find_opt(&opts, &opt) {
366-
Some(id) => id,
367-
None => return Err(UnrecognizedOption(opt.to_string()))
411+
Some(id) => id,
412+
None => return Err(UnrecognizedOption(opt.to_string())),
368413
};
369414

370415
names.push(opt);
371416

372417
let arg_follows = match opts[opt_id].hasarg {
373418
Yes | Maybe => true,
374-
No => false
419+
No => false,
375420
};
376421

377422
if arg_follows {
@@ -387,40 +432,43 @@ impl Options {
387432
for nm in names.iter() {
388433
name_pos += 1;
389434
let optid = match find_opt(&opts, &nm) {
390-
Some(id) => id,
391-
None => return Err(UnrecognizedOption(nm.to_string()))
435+
Some(id) => id,
436+
None => return Err(UnrecognizedOption(nm.to_string())),
392437
};
393438
match opts[optid].hasarg {
394-
No => {
395-
if name_pos == names.len() && !i_arg.is_none() {
396-
return Err(UnexpectedArgument(nm.to_string()));
397-
}
398-
vals[optid].push(Given);
399-
}
400-
Maybe => {
401-
// Note that here we do not handle `--arg value`.
402-
// This matches GNU getopt behavior; but also
403-
// makes sense, because if this were accepted,
404-
// then users could only write a "Maybe" long
405-
// option at the end of the arguments when
406-
// FloatingFrees is in use.
407-
if let Some(i_arg) = i_arg.take() {
408-
vals[optid].push(Val(i_arg));
409-
} else if was_long || name_pos < names.len() || args.peek().map_or(true, |n| is_arg(&n)) {
439+
No => {
440+
if name_pos == names.len() && i_arg.is_some() {
441+
return Err(UnexpectedArgument(nm.to_string()));
442+
}
410443
vals[optid].push(Given);
411-
} else {
412-
vals[optid].push(Val(args.next().unwrap()));
413444
}
414-
}
415-
Yes => {
416-
if let Some(i_arg) = i_arg.take() {
417-
vals[optid].push(Val(i_arg));
418-
} else if let Some(n) = args.next() {
419-
vals[optid].push(Val(n));
420-
} else {
421-
return Err(ArgumentMissing(nm.to_string()));
445+
Maybe => {
446+
// Note that here we do not handle `--arg value`.
447+
// This matches GNU getopt behavior; but also
448+
// makes sense, because if this were accepted,
449+
// then users could only write a "Maybe" long
450+
// option at the end of the arguments when
451+
// FloatingFrees is in use.
452+
if let Some(i_arg) = i_arg.take() {
453+
vals[optid].push(Val(i_arg));
454+
} else if was_long
455+
|| name_pos < names.len()
456+
|| args.peek().map_or(true, |n| is_arg(&n))
457+
{
458+
vals[optid].push(Given);
459+
} else {
460+
vals[optid].push(Val(args.next().unwrap()));
461+
}
462+
}
463+
Yes => {
464+
if let Some(i_arg) = i_arg.take() {
465+
vals[optid].push(Val(i_arg));
466+
} else if let Some(n) = args.next() {
467+
vals[optid].push(Val(n));
468+
} else {
469+
return Err(ArgumentMissing(nm.to_string()));
470+
}
422471
}
423-
}
424472
}
425473
}
426474
}
@@ -434,51 +482,58 @@ impl Options {
434482
return Err(OptionDuplicated(opt.name.to_string()));
435483
}
436484
}
437-
Ok(Matches {
438-
opts: opts,
439-
vals: vals,
440-
free: free
441-
})
485+
Ok(Matches { opts, vals, free })
442486
}
443487

444488
/// Derive a short one-line usage summary from a set of long options.
445489
pub fn short_usage(&self, program_name: &str) -> String {
446490
let mut line = format!("Usage: {} ", program_name);
447-
line.push_str(&self.grps.iter()
448-
.map(format_option)
449-
.collect::<Vec<String>>()
450-
.join(" "));
491+
line.push_str(
492+
&self
493+
.grps
494+
.iter()
495+
.map(format_option)
496+
.collect::<Vec<String>>()
497+
.join(" "),
498+
);
451499
line
452500
}
453501

454-
455502
/// Derive a formatted message from a set of options.
456503
pub fn usage(&self, brief: &str) -> String {
457-
self.usage_with_format(|opts|
458-
format!("{}\n\nOptions:\n{}\n", brief, opts.collect::<Vec<String>>().join("\n")))
504+
self.usage_with_format(|opts| {
505+
format!(
506+
"{}\n\nOptions:\n{}\n",
507+
brief,
508+
opts.collect::<Vec<String>>().join("\n")
509+
)
510+
})
459511
}
460512

461513
/// Derive a custom formatted message from a set of options. The formatted options provided to
462514
/// a closure as an iterator.
463-
pub fn usage_with_format<F: FnMut(&mut Iterator<Item=String>) -> String>(&self, mut formatter: F) -> String {
515+
pub fn usage_with_format<F: FnMut(&mut Iterator<Item = String>) -> String>(
516+
&self,
517+
mut formatter: F,
518+
) -> String {
464519
formatter(&mut self.usage_items())
465520
}
466521

467522
/// Derive usage items from a set of options.
468-
fn usage_items<'a>(&'a self) -> Box<Iterator<Item=String> + 'a> {
523+
fn usage_items<'a>(&'a self) -> Box<Iterator<Item = String> + 'a> {
469524
let desc_sep = format!("\n{}", repeat(" ").take(24).collect::<String>());
470525

471-
let any_short = self.grps.iter().any(|optref| {
472-
optref.short_name.len() > 0
473-
});
526+
let any_short = self.grps.iter().any(|optref| !optref.short_name.is_empty());
474527

475528
let rows = self.grps.iter().map(move |optref| {
476-
let OptGroup{short_name,
477-
long_name,
478-
hint,
479-
desc,
480-
hasarg,
481-
..} = (*optref).clone();
529+
let OptGroup {
530+
short_name,
531+
long_name,
532+
hint,
533+
desc,
534+
hasarg,
535+
..
536+
} = (*optref).clone();
482537

483538
let mut row = " ".to_string();
484539

@@ -527,7 +582,7 @@ impl Options {
527582

528583
let rowlen = row.width();
529584
if rowlen < 24 {
530-
for _ in 0 .. 24 - rowlen {
585+
for _ in 0..24 - rowlen {
531586
row.push(' ');
532587
}
533588
} else {
@@ -540,19 +595,23 @@ impl Options {
540595
row
541596
});
542597

543-
Box::new(rows)
598+
Box::new(rows)
544599
}
545600
}
546601

547602
fn validate_names(short_name: &str, long_name: &str) {
548603
let len = short_name.len();
549-
assert!(len == 1 || len == 0,
550-
"the short_name (first argument) should be a single character, \
551-
or an empty string for none");
604+
assert!(
605+
len == 1 || len == 0,
606+
"the short_name (first argument) should be a single character, \
607+
or an empty string for none"
608+
);
552609
let len = long_name.len();
553-
assert!(len == 0 || len > 1,
554-
"the long_name (second argument) should be longer than a single \
555-
character, or an empty string for none");
610+
assert!(
611+
len == 0 || len > 1,
612+
"the long_name (second argument) should be longer than a single \
613+
character, or an empty string for none"
614+
);
556615
}
557616

558617
/// What parsing style to use when parsing arguments.
@@ -562,11 +621,11 @@ pub enum ParsingStyle {
562621
FloatingFrees,
563622
/// As soon as a "free" argument (i.e. non-flag) is encountered, stop
564623
/// considering any remaining arguments as flags.
565-
StopAtFirstFree
624+
StopAtFirstFree,
566625
}
567626

568627
/// Name of an option. Either a string or a single char.
569-
#[derive(Clone, PartialEq, Eq)]
628+
#[derive(Clone, Debug, PartialEq, Eq)]
570629
enum Name {
571630
/// A string representing the long name of an option.
572631
/// For example: "help"
@@ -577,7 +636,7 @@ enum Name {
577636
}
578637

579638
/// Describes whether an option has an argument.
580-
#[derive(Clone, Copy, PartialEq, Eq)]
639+
#[derive(Clone, Debug, Copy, PartialEq, Eq)]
581640
pub enum HasArg {
582641
/// The option requires an argument.
583642
Yes,
@@ -588,7 +647,7 @@ pub enum HasArg {
588647
}
589648

590649
/// Describes how often an option may occur.
591-
#[derive(Clone, Copy, PartialEq, Eq)]
650+
#[derive(Clone, Debug, Copy, PartialEq, Eq)]
592651
pub enum Occur {
593652
/// The option occurs once.
594653
Req,
@@ -599,7 +658,7 @@ pub enum Occur {
599658
}
600659

601660
/// A description of a possible option.
602-
#[derive(Clone, PartialEq, Eq)]
661+
#[derive(Clone, Debug, PartialEq, Eq)]
603662
struct Opt {
604663
/// Name of the option
605664
name: Name,
@@ -626,19 +685,19 @@ struct OptGroup {
626685
/// Whether option has an argument
627686
hasarg: HasArg,
628687
/// How often it can occur
629-
occur: Occur
688+
occur: Occur,
630689
}
631690

632691
/// Describes whether an option is given at all or has a value.
633-
#[derive(Clone, PartialEq, Eq)]
692+
#[derive(Clone, Debug, PartialEq, Eq)]
634693
enum Optval {
635694
Val(String),
636695
Given,
637696
}
638697

639698
/// The result of checking command line arguments. Contains a vector
640699
/// of matches and a vector of free strings.
641-
#[derive(Clone, PartialEq, Eq)]
700+
#[derive(Clone, Debug, PartialEq, Eq)]
642701
pub struct Matches {
643702
/// Options that matched
644703
opts: Vec<Opt>,
@@ -692,7 +751,7 @@ impl Name {
692751
fn to_string(&self) -> String {
693752
match *self {
694753
Short(ch) => ch.to_string(),
695-
Long(ref s) => s.to_string()
754+
Long(ref s) => s.to_string(),
696755
}
697756
}
698757
}
@@ -710,33 +769,31 @@ impl OptGroup {
710769
} = (*self).clone();
711770

712771
match (short_name.len(), long_name.len()) {
713-
(0,0) => panic!("this long-format option was given no name"),
714-
(0,_) => Opt {
772+
(0, 0) => panic!("this long-format option was given no name"),
773+
(0, _) => Opt {
715774
name: Long(long_name),
716-
hasarg: hasarg,
717-
occur: occur,
718-
aliases: Vec::new()
775+
hasarg,
776+
occur,
777+
aliases: Vec::new(),
719778
},
720-
(1,0) => Opt {
779+
(1, 0) => Opt {
721780
name: Short(short_name.as_bytes()[0] as char),
722-
hasarg: hasarg,
723-
occur: occur,
724-
aliases: Vec::new()
781+
hasarg,
782+
occur,
783+
aliases: Vec::new(),
725784
},
726-
(1,_) => Opt {
785+
(1, _) => Opt {
727786
name: Long(long_name),
728-
hasarg: hasarg,
729-
occur: occur,
730-
aliases: vec!(
731-
Opt {
732-
name: Short(short_name.as_bytes()[0] as char),
733-
hasarg: hasarg,
734-
occur: occur,
735-
aliases: Vec::new()
736-
}
737-
)
787+
hasarg,
788+
occur,
789+
aliases: vec![Opt {
790+
name: Short(short_name.as_bytes()[0] as char),
791+
hasarg: hasarg,
792+
occur: occur,
793+
aliases: Vec::new(),
794+
}],
738795
},
739-
(_,_) => panic!("something is wrong with the long-form opt")
796+
(_, _) => panic!("something is wrong with the long-form opt"),
740797
}
741798
}
742799
}
@@ -745,7 +802,7 @@ impl Matches {
745802
fn opt_vals(&self, nm: &str) -> Vec<Optval> {
746803
match find_opt(&self.opts, &Name::from_str(nm)) {
747804
Some(id) => self.vals[id].clone(),
748-
None => panic!("No option '{}' defined", nm)
805+
None => panic!("No option '{}' defined", nm),
749806
}
750807
}
751808

@@ -769,35 +826,35 @@ impl Matches {
769826

770827
/// Returns true if any of several options were matched.
771828
pub fn opts_present(&self, names: &[String]) -> bool {
772-
names.iter().any(|nm| {
773-
match find_opt(&self.opts, &Name::from_str(&nm)) {
829+
names
830+
.iter()
831+
.any(|nm| match find_opt(&self.opts, &Name::from_str(&nm)) {
774832
Some(id) if !self.vals[id].is_empty() => true,
775833
_ => false,
776-
}
777-
})
834+
})
778835
}
779836

780837
/// Returns the string argument supplied to one of several matching options or `None`.
781838
pub fn opts_str(&self, names: &[String]) -> Option<String> {
782-
names.iter().filter_map(|nm| {
783-
match self.opt_val(&nm) {
839+
names
840+
.iter()
841+
.filter_map(|nm| match self.opt_val(&nm) {
784842
Some(Val(s)) => Some(s),
785843
_ => None,
786-
}
787-
}).next()
844+
}).next()
788845
}
789846

790847
/// Returns a vector of the arguments provided to all matches of the given
791848
/// option.
792849
///
793850
/// Used when an option accepts multiple values.
794851
pub fn opt_strs(&self, nm: &str) -> Vec<String> {
795-
self.opt_vals(nm).into_iter().filter_map(|v| {
796-
match v {
852+
self.opt_vals(nm)
853+
.into_iter()
854+
.filter_map(|v| match v {
797855
Val(s) => Some(s),
798856
_ => None,
799-
}
800-
}).collect()
857+
}).collect()
801858
}
802859

803860
/// Returns the string argument supplied to a matching option or `None`.
@@ -808,7 +865,6 @@ impl Matches {
808865
}
809866
}
810867

811-
812868
/// Returns the matching string, a default, or `None`.
813869
///
814870
/// Returns `None` if the option was not present, `def` if the option was
@@ -826,7 +882,8 @@ impl Matches {
826882
///
827883
/// Similar to opt_str, also converts matching argument using FromStr.
828884
pub fn opt_get<T>(&self, nm: &str) -> result::Result<Option<T>, T::Err>
829-
where T: FromStr
885+
where
886+
T: FromStr,
830887
{
831888
match self.opt_val(nm) {
832889
Some(Val(s)) => Ok(Some(s.parse()?)),
@@ -840,8 +897,9 @@ impl Matches {
840897
/// Similar to opt_default, except the two differences.
841898
/// Instead of returning None when argument was not present, return `def`.
842899
/// Instead of returning &str return type T, parsed using str::parse().
843-
pub fn opt_get_default<T>(&self, nm: &str, def: T)
844-
-> result::Result<T, T::Err> where T: FromStr
900+
pub fn opt_get_default<T>(&self, nm: &str, def: T) -> result::Result<T, T::Err>
901+
where
902+
T: FromStr,
845903
{
846904
match self.opt_val(nm) {
847905
Some(Val(s)) => s.parse(),
@@ -859,12 +917,12 @@ fn find_opt(opts: &[Opt], nm: &Name) -> Option<usize> {
859917
// Search main options.
860918
let pos = opts.iter().position(|opt| &opt.name == nm);
861919
if pos.is_some() {
862-
return pos
920+
return pos;
863921
}
864922

865923
// Search in aliases.
866924
for candidate in opts.iter() {
867-
if candidate.aliases.iter().position(|opt| &opt.name == nm).is_some() {
925+
if candidate.aliases.iter().any(|opt| &opt.name == nm) {
868926
return opts.iter().position(|opt| opt.name == candidate.name);
869927
}
870928
}
@@ -875,21 +933,11 @@ fn find_opt(opts: &[Opt], nm: &Name) -> Option<usize> {
875933
impl fmt::Display for Fail {
876934
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
877935
match *self {
878-
ArgumentMissing(ref nm) => {
879-
write!(f, "Argument to option '{}' missing", *nm)
880-
}
881-
UnrecognizedOption(ref nm) => {
882-
write!(f, "Unrecognized option: '{}'", *nm)
883-
}
884-
OptionMissing(ref nm) => {
885-
write!(f, "Required option '{}' missing", *nm)
886-
}
887-
OptionDuplicated(ref nm) => {
888-
write!(f, "Option '{}' given more than once", *nm)
889-
}
890-
UnexpectedArgument(ref nm) => {
891-
write!(f, "Option '{}' does not take an argument", *nm)
892-
}
936+
ArgumentMissing(ref nm) => write!(f, "Argument to option '{}' missing", *nm),
937+
UnrecognizedOption(ref nm) => write!(f, "Unrecognized option: '{}'", *nm),
938+
OptionMissing(ref nm) => write!(f, "Required option '{}' missing", *nm),
939+
OptionDuplicated(ref nm) => write!(f, "Option '{}' given more than once", *nm),
940+
UnexpectedArgument(ref nm) => write!(f, "Option '{}' does not take an argument", *nm),
893941
}
894942
}
895943
}
@@ -902,7 +950,7 @@ fn format_option(opt: &OptGroup) -> String {
902950
}
903951

904952
// Use short_name if possible, but fall back to long_name.
905-
if opt.short_name.len() > 0 {
953+
if !opt.short_name.is_empty() {
906954
line.push('-');
907955
line.push_str(&opt.short_name);
908956
} else {
@@ -939,41 +987,42 @@ fn each_split_within(desc: &str, lim: usize) -> Vec<String> {
939987
let mut rows = Vec::new();
940988
for line in desc.trim().lines() {
941989
let line_chars = line.chars().chain(Some(' '));
942-
let words = line_chars.fold( (Vec::new(), 0, 0), |(mut words, a, z), c | {
943-
let idx = z + c.len_utf8(); // Get the current byte offset
944-
945-
// If the char is whitespace, advance the word start and maybe push a word
946-
if c.is_whitespace() {
947-
if a != z {
948-
words.push(&line[a..z]);
990+
let words = line_chars
991+
.fold((Vec::new(), 0, 0), |(mut words, a, z), c| {
992+
let idx = z + c.len_utf8(); // Get the current byte offset
993+
994+
// If the char is whitespace, advance the word start and maybe push a word
995+
if c.is_whitespace() {
996+
if a != z {
997+
words.push(&line[a..z]);
998+
}
999+
(words, idx, idx)
9491000
}
950-
(words, idx, idx)
951-
}
952-
// If the char is not whitespace, continue, retaining the current
953-
else {
954-
(words, a, idx)
955-
}
956-
}).0;
1001+
// If the char is not whitespace, continue, retaining the current
1002+
else {
1003+
(words, a, idx)
1004+
}
1005+
}).0;
9571006

9581007
let mut row = String::new();
9591008
for word in words.iter() {
960-
let sep = if row.len() > 0 { Some(" ") } else { None };
961-
let width = row.width()
962-
+ word.width()
963-
+ sep.map(UnicodeWidthStr::width).unwrap_or(0);
1009+
let sep = if !row.is_empty() { Some(" ") } else { None };
1010+
let width = row.width() + word.width() + sep.map(UnicodeWidthStr::width).unwrap_or(0);
9641011

9651012
if width <= lim {
966-
if let Some(sep) = sep { row.push_str(sep) }
1013+
if let Some(sep) = sep {
1014+
row.push_str(sep)
1015+
}
9671016
row.push_str(word);
968-
continue
1017+
continue;
9691018
}
970-
if row.len() > 0 {
1019+
if !row.is_empty() {
9711020
rows.push(row.clone());
9721021
row.clear();
9731022
}
9741023
row.push_str(word);
9751024
}
976-
if row.len() > 0 {
1025+
if !row.is_empty() {
9771026
rows.push(row);
9781027
}
9791028
}

‎src/tests/mod.rs‎

Lines changed: 334 additions & 261 deletions
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)
Please sign in to comment.