1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Simple getopt alternative.
13 //! Construct a vector of options, either by using `reqopt`, `optopt`, and `optflag`
14 //! or by building them from components yourself, and pass them to `getopts`,
15 //! along with a vector of actual arguments (not including `argv[0]`). You'll
16 //! either get a failure code back, or a match. You'll have to verify whether
17 //! the amount of 'free' arguments in the match is what you expect. Use `opt_*`
18 //! accessors to get argument values out of the matches object.
20 //! Single-character options are expected to appear on the command line with a
21 //! single preceding dash; multiple-character options are expected to be
22 //! proceeded by two dashes. Options that expect an argument accept their
23 //! argument following either a space or an equals sign. Single-character
24 //! options don't require the space.
28 //! The following example shows simple command line parsing for an application
29 //! that requires an input file to be specified, accepts an optional output
30 //! file name following `-o`, and accepts both `-h` and `--help` as optional flags.
33 //! extern crate getopts;
34 //! use getopts::{optopt,optflag,getopts,OptGroup,usage};
37 //! fn do_work(inp: &str, out: Option<String>) {
38 //! println!("{}", inp);
40 //! Some(x) => println!("{}", x),
41 //! None => println!("No Output"),
45 //! fn print_usage(program: &str, opts: &[OptGroup]) {
46 //! let brief = format!("Usage: {} [options]", program);
47 //! print!("{}", usage(brief, opts));
51 //! let args: Vec<String> = os::args();
53 //! let program = args[0].clone();
56 //! optopt("o", "", "set output file name", "NAME"),
57 //! optflag("h", "help", "print this help menu")
59 //! let matches = match getopts(args[1..], opts) {
61 //! Err(f) => { panic!(f.to_string()) }
63 //! if matches.opt_present("h") {
64 //! print_usage(program, opts);
67 //! let output = matches.opt_str("o");
68 //! let input = if !matches.free.is_empty() {
69 //! matches.free[0].clone()
71 //! print_usage(program, opts);
74 //! do_work(input, output);
79 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
80 #![cfg_attr(stage0, feature(custom_attribute))]
81 #![crate_name = "getopts"]
82 #![unstable(feature = "rustc_private",
83 reason = "use the crates.io `getopts` library instead")]
85 #![crate_type = "rlib"]
86 #![crate_type = "dylib"]
87 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
88 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
89 html_root_url = "http://doc.rust-lang.org/nightly/",
90 html_playground_url = "http://play.rust-lang.org/")]
92 #![deny(missing_docs)]
93 #![feature(staged_api)]
95 #![cfg_attr(test, feature(rustc_private))]
97 #[cfg(test)] #[macro_use] extern crate log;
104 use self::SplitWithinState::*;
105 use self::Whitespace::*;
106 use self::LengthLimit::*;
109 use std::iter::repeat;
112 /// Name of an option. Either a string or a single char.
113 #[derive(Clone, PartialEq, Eq, Debug)]
115 /// A string representing the long name of an option.
116 /// For example: "help"
118 /// A char representing the short name of an option.
123 /// Describes whether an option has an argument.
124 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
126 /// The option requires an argument.
128 /// The option takes no argument.
130 /// The option argument is optional.
134 /// Describes how often an option may occur.
135 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
137 /// The option occurs once.
139 /// The option occurs at most once.
141 /// The option occurs zero or more times.
145 /// A description of a possible option.
146 #[derive(Clone, PartialEq, Eq, Debug)]
148 /// Name of the option
150 /// Whether it has an argument
152 /// How often it can occur
154 /// Which options it aliases
155 pub aliases: Vec<Opt>,
158 /// One group of options, e.g., both `-h` and `--help`, along with
159 /// their shared description and properties.
160 #[derive(Clone, PartialEq, Eq, Debug)]
161 pub struct OptGroup {
162 /// Short name of the option, e.g. `h` for a `-h` option
163 pub short_name: String,
164 /// Long name of the option, e.g. `help` for a `--help` option
165 pub long_name: String,
166 /// Hint for argument, e.g. `FILE` for a `-o FILE` option
168 /// Description for usage help text
170 /// Whether option has an argument
172 /// How often it can occur
176 /// Describes whether an option is given at all or has a value.
177 #[derive(Clone, PartialEq, Eq, Debug)]
183 /// The result of checking command line arguments. Contains a vector
184 /// of matches and a vector of free strings.
185 #[derive(Clone, PartialEq, Eq, Debug)]
187 /// Options that matched
189 /// Values of the Options that matched
190 vals: Vec<Vec<Optval>>,
191 /// Free string fragments
192 pub free: Vec<String>,
195 /// The type returned when the command line does not conform to the
196 /// expected format. Use the `Debug` implementation to output detailed
198 #[derive(Clone, PartialEq, Eq, Debug)]
200 /// The option requires an argument but none was passed.
201 ArgumentMissing(String),
202 /// The passed option is not declared among the possible options.
203 UnrecognizedOption(String),
204 /// A required option is not present.
205 OptionMissing(String),
206 /// A single occurrence option is being used multiple times.
207 OptionDuplicated(String),
208 /// There's an argument being passed to a non-argument option.
209 UnexpectedArgument(String),
212 /// The type of failure that occurred.
213 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
214 #[allow(missing_docs)]
223 /// The result of parsing a command line with a set of options.
224 pub type Result = result::Result<Matches, Fail>;
227 fn from_str(nm: &str) -> Name {
235 fn to_string(&self) -> String {
237 Short(ch) => ch.to_string(),
238 Long(ref s) => s.to_string()
244 /// Translate OptGroup into Opt.
245 /// (Both short and long names correspond to different Opts).
246 pub fn long_to_short(&self) -> Opt {
255 match (short_name.len(), long_name.len()) {
256 (0,0) => panic!("this long-format option was given no name"),
258 name: Long((long_name)),
264 name: Short(short_name.char_at(0)),
270 name: Long((long_name)),
275 name: Short(short_name.char_at(0)),
282 (_,_) => panic!("something is wrong with the long-form opt")
288 fn opt_vals(&self, nm: &str) -> Vec<Optval> {
289 match find_opt(&self.opts[..], Name::from_str(nm)) {
290 Some(id) => self.vals[id].clone(),
291 None => panic!("No option '{}' defined", nm)
295 fn opt_val(&self, nm: &str) -> Option<Optval> {
296 let vals = self.opt_vals(nm);
300 Some(vals[0].clone())
304 /// Returns true if an option was matched.
305 pub fn opt_present(&self, nm: &str) -> bool {
306 !self.opt_vals(nm).is_empty()
309 /// Returns the number of times an option was matched.
310 pub fn opt_count(&self, nm: &str) -> usize {
311 self.opt_vals(nm).len()
314 /// Returns true if any of several options were matched.
315 pub fn opts_present(&self, names: &[String]) -> bool {
317 match find_opt(&self.opts, Name::from_str(&**nm)) {
318 Some(id) if !self.vals[id].is_empty() => return true,
325 /// Returns the string argument supplied to one of several matching options or `None`.
326 pub fn opts_str(&self, names: &[String]) -> Option<String> {
328 match self.opt_val(&nm[..]) {
329 Some(Val(ref s)) => return Some(s.clone()),
336 /// Returns a vector of the arguments provided to all matches of the given
339 /// Used when an option accepts multiple values.
340 pub fn opt_strs(&self, nm: &str) -> Vec<String> {
341 let mut acc: Vec<String> = Vec::new();
342 let r = self.opt_vals(nm);
345 Val(ref s) => acc.push((*s).clone()),
352 /// Returns the string argument supplied to a matching option or `None`.
353 pub fn opt_str(&self, nm: &str) -> Option<String> {
354 let vals = self.opt_vals(nm);
356 return None::<String>;
359 Val(ref s) => Some((*s).clone()),
365 /// Returns the matching string, a default, or none.
367 /// Returns none if the option was not present, `def` if the option was
368 /// present but no argument was provided, and the argument if the option was
369 /// present and an argument was provided.
370 pub fn opt_default(&self, nm: &str, def: &str) -> Option<String> {
371 let vals = self.opt_vals(nm);
376 Val(ref s) => Some((*s).clone()),
377 _ => Some(def.to_string())
384 fn is_arg(arg: &str) -> bool {
385 arg.len() > 1 && arg.as_bytes()[0] == b'-'
388 fn find_opt(opts: &[Opt], nm: Name) -> Option<usize> {
389 // Search main options.
390 let pos = opts.iter().position(|opt| opt.name == nm);
395 // Search in aliases.
396 for candidate in opts {
397 if candidate.aliases.iter().position(|opt| opt.name == nm).is_some() {
398 return opts.iter().position(|opt| opt.name == candidate.name);
405 /// Create a long option that is required and takes an argument.
407 /// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none
408 /// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none
409 /// * `desc` - Description for usage help
410 /// * `hint` - Hint that is used in place of the argument in the usage help,
411 /// e.g. `"FILE"` for a `-o FILE` option
412 pub fn reqopt(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptGroup {
413 let len = short_name.len();
414 assert!(len == 1 || len == 0);
416 short_name: short_name.to_string(),
417 long_name: long_name.to_string(),
418 hint: hint.to_string(),
419 desc: desc.to_string(),
425 /// Create a long option that is optional and takes an argument.
427 /// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none
428 /// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none
429 /// * `desc` - Description for usage help
430 /// * `hint` - Hint that is used in place of the argument in the usage help,
431 /// e.g. `"FILE"` for a `-o FILE` option
432 pub fn optopt(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptGroup {
433 let len = short_name.len();
434 assert!(len == 1 || len == 0);
436 short_name: short_name.to_string(),
437 long_name: long_name.to_string(),
438 hint: hint.to_string(),
439 desc: desc.to_string(),
445 /// Create a long option that is optional and does not take an argument.
447 /// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none
448 /// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none
449 /// * `desc` - Description for usage help
450 pub fn optflag(short_name: &str, long_name: &str, desc: &str) -> OptGroup {
451 let len = short_name.len();
452 assert!(len == 1 || len == 0);
454 short_name: short_name.to_string(),
455 long_name: long_name.to_string(),
456 hint: "".to_string(),
457 desc: desc.to_string(),
463 /// Create a long option that can occur more than once and does not
464 /// take an argument.
466 /// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none
467 /// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none
468 /// * `desc` - Description for usage help
469 pub fn optflagmulti(short_name: &str, long_name: &str, desc: &str) -> OptGroup {
470 let len = short_name.len();
471 assert!(len == 1 || len == 0);
473 short_name: short_name.to_string(),
474 long_name: long_name.to_string(),
475 hint: "".to_string(),
476 desc: desc.to_string(),
482 /// Create a long option that is optional and takes an optional argument.
484 /// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none
485 /// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none
486 /// * `desc` - Description for usage help
487 /// * `hint` - Hint that is used in place of the argument in the usage help,
488 /// e.g. `"FILE"` for a `-o FILE` option
489 pub fn optflagopt(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptGroup {
490 let len = short_name.len();
491 assert!(len == 1 || len == 0);
493 short_name: short_name.to_string(),
494 long_name: long_name.to_string(),
495 hint: hint.to_string(),
496 desc: desc.to_string(),
502 /// Create a long option that is optional, takes an argument, and may occur
505 /// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none
506 /// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none
507 /// * `desc` - Description for usage help
508 /// * `hint` - Hint that is used in place of the argument in the usage help,
509 /// e.g. `"FILE"` for a `-o FILE` option
510 pub fn optmulti(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptGroup {
511 let len = short_name.len();
512 assert!(len == 1 || len == 0);
514 short_name: short_name.to_string(),
515 long_name: long_name.to_string(),
516 hint: hint.to_string(),
517 desc: desc.to_string(),
523 /// Create a generic option group, stating all parameters explicitly
524 pub fn opt(short_name: &str,
529 occur: Occur) -> OptGroup {
530 let len = short_name.len();
531 assert!(len == 1 || len == 0);
533 short_name: short_name.to_string(),
534 long_name: long_name.to_string(),
535 hint: hint.to_string(),
536 desc: desc.to_string(),
543 /// Convert a `Fail` enum into an error string.
544 #[unstable(feature = "rustc_private")]
545 #[deprecated(since = "1.0.0",
546 reason = "use `fmt::Display` (`{}` format specifier)")]
547 pub fn to_err_msg(self) -> String {
552 impl fmt::Display for Fail {
553 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
555 ArgumentMissing(ref nm) => {
556 write!(f, "Argument to option '{}' missing.", *nm)
558 UnrecognizedOption(ref nm) => {
559 write!(f, "Unrecognized option: '{}'.", *nm)
561 OptionMissing(ref nm) => {
562 write!(f, "Required option '{}' missing.", *nm)
564 OptionDuplicated(ref nm) => {
565 write!(f, "Option '{}' given more than once.", *nm)
567 UnexpectedArgument(ref nm) => {
568 write!(f, "Option '{}' does not take an argument.", *nm)
574 /// Parse command line arguments according to the provided options.
576 /// On success returns `Ok(Matches)`. Use methods such as `opt_present`
577 /// `opt_str`, etc. to interrogate results.
580 /// Returns `Err(Fail)` on failure: use the `Debug` implementation of `Fail` to display
581 /// information about it.
582 pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result {
583 let opts: Vec<Opt> = optgrps.iter().map(|x| x.long_to_short()).collect();
584 let n_opts = opts.len();
586 fn f(_x: usize) -> Vec<Optval> { return Vec::new(); }
588 let mut vals: Vec<_> = (0..n_opts).map(f).collect();
589 let mut free: Vec<String> = Vec::new();
593 let cur = args[i].clone();
594 let curlen = cur.len();
595 if !is_arg(&cur[..]) {
597 } else if cur == "--" {
599 while j < l { free.push(args[j].clone()); j += 1; }
603 let mut i_arg = None;
604 if cur.as_bytes()[1] == b'-' {
605 let tail = &cur[2..curlen];
606 let tail_eq: Vec<&str> = tail.split('=').collect();
607 if tail_eq.len() <= 1 {
608 names = vec!(Long(tail.to_string()));
611 vec!(Long(tail_eq[0].to_string()));
612 i_arg = Some(tail_eq[1].to_string());
618 let ch = cur.char_at(j);
621 /* In a series of potential options (eg. -aheJ), if we
622 see one which takes an argument, we assume all
623 subsequent characters make up the argument. This
624 allows options such as -L/usr/local/lib/foo to be
625 interpreted correctly
628 let opt_id = match find_opt(&opts, opt.clone()) {
630 None => return Err(UnrecognizedOption(opt.to_string()))
635 let arg_follows = match opts[opt_id].hasarg {
640 let next = j + ch.len_utf8();
641 if arg_follows && next < curlen {
642 i_arg = Some((&cur[next..curlen]).to_string());
649 let mut name_pos = 0;
652 let optid = match find_opt(&opts, (*nm).clone()) {
654 None => return Err(UnrecognizedOption(nm.to_string()))
656 match opts[optid].hasarg {
658 if name_pos == names.len() && !i_arg.is_none() {
659 return Err(UnexpectedArgument(nm.to_string()));
661 let v = &mut vals[optid];
665 if !i_arg.is_none() {
666 let v = &mut vals[optid];
667 v.push(Val((i_arg.clone())
669 } else if name_pos < names.len() || i + 1 == l ||
670 is_arg(&args[i + 1][..]) {
671 let v = &mut vals[optid];
675 let v = &mut vals[optid];
676 v.push(Val(args[i].clone()));
680 if !i_arg.is_none() {
681 let v = &mut vals[optid];
682 v.push(Val(i_arg.clone().unwrap()));
683 } else if i + 1 == l {
684 return Err(ArgumentMissing(nm.to_string()));
687 let v = &mut vals[optid];
688 v.push(Val(args[i].clone()));
697 let n = vals[i].len();
698 let occ = opts[i].occur;
699 if occ == Req && n == 0 {
700 return Err(OptionMissing(opts[i].name.to_string()));
702 if occ != Multi && n > 1 {
703 return Err(OptionDuplicated(opts[i].name.to_string()));
713 /// Derive a usage message from a set of long options.
714 pub fn usage(brief: &str, opts: &[OptGroup]) -> String {
716 let desc_sep = format!("\n{}", repeat(" ").take(24).collect::<String>());
718 let rows = opts.iter().map(|optref| {
719 let OptGroup{short_name,
724 ..} = (*optref).clone();
726 let mut row = repeat(" ").take(4).collect::<String>();
729 match short_name.len() {
733 row.push_str(&short_name[..]);
736 _ => panic!("the short name should only be 1 ascii char long"),
740 match long_name.len() {
744 row.push_str(&long_name[..]);
752 Yes => row.push_str(&hint[..]),
755 row.push_str(&hint[..]);
760 // FIXME: #5516 should be graphemes not codepoints
761 // here we just need to indent the start of the description
762 let rowlen = row.chars().count();
764 for _ in 0..24 - rowlen {
768 row.push_str(&desc_sep[..]);
771 // Normalize desc to contain words separated by one space character
772 let mut desc_normalized_whitespace = String::new();
773 for word in desc.split_whitespace() {
774 desc_normalized_whitespace.push_str(word);
775 desc_normalized_whitespace.push(' ');
778 // FIXME: #5516 should be graphemes not codepoints
779 let mut desc_rows = Vec::new();
780 each_split_within(&desc_normalized_whitespace[..], 54, |substr| {
781 desc_rows.push(substr.to_string());
785 // FIXME: #5516 should be graphemes not codepoints
786 // wrapped description
787 row.push_str(&desc_rows.join(&desc_sep[..]));
792 format!("{}\n\nOptions:\n{}\n", brief,
793 rows.collect::<Vec<String>>().join("\n"))
796 fn format_option(opt: &OptGroup) -> String {
797 let mut line = String::new();
799 if opt.occur != Req {
803 // Use short_name is possible, but fallback to long_name.
804 if !opt.short_name.is_empty() {
806 line.push_str(&opt.short_name[..]);
809 line.push_str(&opt.long_name[..]);
812 if opt.hasarg != No {
814 if opt.hasarg == Maybe {
817 line.push_str(&opt.hint[..]);
818 if opt.hasarg == Maybe {
823 if opt.occur != Req {
826 if opt.occur == Multi {
833 /// Derive a short one-line usage summary from a set of long options.
834 pub fn short_usage(program_name: &str, opts: &[OptGroup]) -> String {
835 let mut line = format!("Usage: {} ", program_name);
836 line.push_str(&opts.iter()
838 .collect::<Vec<String>>()
843 #[derive(Copy, Clone)]
844 enum SplitWithinState {
845 A, // leading whitespace, initial state
847 C, // internal and trailing whitespace
849 #[derive(Copy, Clone)]
851 Ws, // current char is whitespace
852 Cr // current char is not whitespace
854 #[derive(Copy, Clone)]
856 UnderLim, // current char makes current substring still fit in limit
857 OverLim // current char makes current substring no longer fit in limit
861 /// Splits a string into substrings with possibly internal whitespace,
862 /// each of them at most `lim` bytes long. The substrings have leading and trailing
863 /// whitespace removed, and are only cut at whitespace boundaries.
865 /// Note: Function was moved here from `std::str` because this module is the only place that
866 /// uses it, and because it was too specific for a general string function.
870 /// Panics during iteration if the string contains a non-whitespace
871 /// sequence longer than the limit.
872 fn each_split_within<F>(ss: &str, lim: usize, mut it: F) -> bool where
873 F: FnMut(&str) -> bool
875 // Just for fun, let's write this as a state machine:
877 let mut slice_start = 0;
878 let mut last_start = 0;
879 let mut last_end = 0;
881 let mut fake_i = ss.len();
886 // if the limit is larger than the string, lower it to save cycles
891 let mut machine = |cont: &mut bool, (i, c): (usize, char)| -> bool {
892 let whitespace = if c.is_whitespace() { Ws } else { Cr };
893 let limit = if (i - slice_start + 1) <= lim { UnderLim } else { OverLim };
895 state = match (state, whitespace, limit) {
897 (A, Cr, _) => { slice_start = i; last_start = i; B }
899 (B, Cr, UnderLim) => { B }
900 (B, Cr, OverLim) if (i - last_start + 1) > lim
901 => panic!("word starting with {} longer than limit!",
902 &ss[last_start..i + 1]),
903 (B, Cr, OverLim) => {
904 *cont = it(&ss[slice_start..last_end]);
905 slice_start = last_start;
908 (B, Ws, UnderLim) => {
912 (B, Ws, OverLim) => {
914 *cont = it(&ss[slice_start..last_end]);
918 (C, Cr, UnderLim) => {
922 (C, Cr, OverLim) => {
923 *cont = it(&ss[slice_start..last_end]);
929 (C, Ws, OverLim) => {
930 *cont = it(&ss[slice_start..last_end]);
933 (C, Ws, UnderLim) => {
941 ss.char_indices().all(|x| machine(&mut cont, x));
943 // Let the automaton 'run out' by supplying trailing whitespace
944 while cont && match state { B | C => true, A => false } {
945 machine(&mut cont, (fake_i, ' '));
952 fn test_split_within() {
953 fn t(s: &str, i: usize, u: &[String]) {
954 let mut v = Vec::new();
955 each_split_within(s, i, |s| { v.push(s.to_string()); true });
956 assert!(v.iter().zip(u).all(|(a,b)| a == b));
960 t("hello", 15, &["hello".to_string()]);
961 t("\nMary had a little lamb\nLittle lamb\n", 15, &[
962 "Mary had a".to_string(),
963 "little lamb".to_string(),
964 "Little lamb".to_string()
966 t("\nMary had a little lamb\nLittle lamb\n", ::std::usize::MAX,
967 &["Mary had a little lamb\nLittle lamb".to_string()]);
975 use std::result::Result::{Err, Ok};
981 let long_args = vec!("--test=20".to_string());
982 let opts = vec!(reqopt("t", "test", "testing", "TEST"));
983 let rs = getopts(&long_args, &opts);
986 assert!(m.opt_present("test"));
987 assert_eq!(m.opt_str("test").unwrap(), "20");
988 assert!(m.opt_present("t"));
989 assert_eq!(m.opt_str("t").unwrap(), "20");
991 _ => { panic!("test_reqopt failed (long arg)"); }
993 let short_args = vec!("-t".to_string(), "20".to_string());
994 match getopts(&short_args, &opts) {
996 assert!((m.opt_present("test")));
997 assert_eq!(m.opt_str("test").unwrap(), "20");
998 assert!((m.opt_present("t")));
999 assert_eq!(m.opt_str("t").unwrap(), "20");
1001 _ => { panic!("test_reqopt failed (short arg)"); }
1006 fn test_reqopt_missing() {
1007 let args = vec!("blah".to_string());
1008 let opts = vec!(reqopt("t", "test", "testing", "TEST"));
1009 let rs = getopts(&args, &opts);
1011 Err(OptionMissing(_)) => {},
1017 fn test_reqopt_no_arg() {
1018 let long_args = vec!("--test".to_string());
1019 let opts = vec!(reqopt("t", "test", "testing", "TEST"));
1020 let rs = getopts(&long_args, &opts);
1022 Err(ArgumentMissing(_)) => {},
1025 let short_args = vec!("-t".to_string());
1026 match getopts(&short_args, &opts) {
1027 Err(ArgumentMissing(_)) => {},
1033 fn test_reqopt_multi() {
1034 let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string());
1035 let opts = vec!(reqopt("t", "test", "testing", "TEST"));
1036 let rs = getopts(&args, &opts);
1038 Err(OptionDuplicated(_)) => {},
1046 let long_args = vec!("--test=20".to_string());
1047 let opts = vec!(optopt("t", "test", "testing", "TEST"));
1048 let rs = getopts(&long_args, &opts);
1051 assert!(m.opt_present("test"));
1052 assert_eq!(m.opt_str("test").unwrap(), "20");
1053 assert!((m.opt_present("t")));
1054 assert_eq!(m.opt_str("t").unwrap(), "20");
1058 let short_args = vec!("-t".to_string(), "20".to_string());
1059 match getopts(&short_args, &opts) {
1061 assert!((m.opt_present("test")));
1062 assert_eq!(m.opt_str("test").unwrap(), "20");
1063 assert!((m.opt_present("t")));
1064 assert_eq!(m.opt_str("t").unwrap(), "20");
1071 fn test_optopt_missing() {
1072 let args = vec!("blah".to_string());
1073 let opts = vec!(optopt("t", "test", "testing", "TEST"));
1074 let rs = getopts(&args, &opts);
1077 assert!(!m.opt_present("test"));
1078 assert!(!m.opt_present("t"));
1085 fn test_optopt_no_arg() {
1086 let long_args = vec!("--test".to_string());
1087 let opts = vec!(optopt("t", "test", "testing", "TEST"));
1088 let rs = getopts(&long_args, &opts);
1090 Err(ArgumentMissing(_)) => {},
1093 let short_args = vec!("-t".to_string());
1094 match getopts(&short_args, &opts) {
1095 Err(ArgumentMissing(_)) => {},
1101 fn test_optopt_multi() {
1102 let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string());
1103 let opts = vec!(optopt("t", "test", "testing", "TEST"));
1104 let rs = getopts(&args, &opts);
1106 Err(OptionDuplicated(_)) => {},
1111 // Tests for optflag
1114 let long_args = vec!("--test".to_string());
1115 let opts = vec!(optflag("t", "test", "testing"));
1116 let rs = getopts(&long_args, &opts);
1119 assert!(m.opt_present("test"));
1120 assert!(m.opt_present("t"));
1124 let short_args = vec!("-t".to_string());
1125 match getopts(&short_args, &opts) {
1127 assert!(m.opt_present("test"));
1128 assert!(m.opt_present("t"));
1135 fn test_optflag_missing() {
1136 let args = vec!("blah".to_string());
1137 let opts = vec!(optflag("t", "test", "testing"));
1138 let rs = getopts(&args, &opts);
1141 assert!(!m.opt_present("test"));
1142 assert!(!m.opt_present("t"));
1149 fn test_optflag_long_arg() {
1150 let args = vec!("--test=20".to_string());
1151 let opts = vec!(optflag("t", "test", "testing"));
1152 let rs = getopts(&args, &opts);
1154 Err(UnexpectedArgument(_)) => {},
1160 fn test_optflag_multi() {
1161 let args = vec!("--test".to_string(), "-t".to_string());
1162 let opts = vec!(optflag("t", "test", "testing"));
1163 let rs = getopts(&args, &opts);
1165 Err(OptionDuplicated(_)) => {},
1171 fn test_optflag_short_arg() {
1172 let args = vec!("-t".to_string(), "20".to_string());
1173 let opts = vec!(optflag("t", "test", "testing"));
1174 let rs = getopts(&args, &opts);
1177 // The next variable after the flag is just a free argument
1179 assert!(m.free[0] == "20");
1185 // Tests for optflagmulti
1187 fn test_optflagmulti_short1() {
1188 let args = vec!("-v".to_string());
1189 let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
1190 let rs = getopts(&args, &opts);
1193 assert_eq!(m.opt_count("v"), 1);
1200 fn test_optflagmulti_short2a() {
1201 let args = vec!("-v".to_string(), "-v".to_string());
1202 let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
1203 let rs = getopts(&args, &opts);
1206 assert_eq!(m.opt_count("v"), 2);
1213 fn test_optflagmulti_short2b() {
1214 let args = vec!("-vv".to_string());
1215 let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
1216 let rs = getopts(&args, &opts);
1219 assert_eq!(m.opt_count("v"), 2);
1226 fn test_optflagmulti_long1() {
1227 let args = vec!("--verbose".to_string());
1228 let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
1229 let rs = getopts(&args, &opts);
1232 assert_eq!(m.opt_count("verbose"), 1);
1239 fn test_optflagmulti_long2() {
1240 let args = vec!("--verbose".to_string(), "--verbose".to_string());
1241 let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
1242 let rs = getopts(&args, &opts);
1245 assert_eq!(m.opt_count("verbose"), 2);
1252 fn test_optflagmulti_mix() {
1253 let args = vec!("--verbose".to_string(), "-v".to_string(),
1254 "-vv".to_string(), "verbose".to_string());
1255 let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
1256 let rs = getopts(&args, &opts);
1259 assert_eq!(m.opt_count("verbose"), 4);
1260 assert_eq!(m.opt_count("v"), 4);
1266 // Tests for optmulti
1268 fn test_optmulti() {
1269 let long_args = vec!("--test=20".to_string());
1270 let opts = vec!(optmulti("t", "test", "testing", "TEST"));
1271 let rs = getopts(&long_args, &opts);
1274 assert!((m.opt_present("test")));
1275 assert_eq!(m.opt_str("test").unwrap(), "20");
1276 assert!((m.opt_present("t")));
1277 assert_eq!(m.opt_str("t").unwrap(), "20");
1281 let short_args = vec!("-t".to_string(), "20".to_string());
1282 match getopts(&short_args, &opts) {
1284 assert!((m.opt_present("test")));
1285 assert_eq!(m.opt_str("test").unwrap(), "20");
1286 assert!((m.opt_present("t")));
1287 assert_eq!(m.opt_str("t").unwrap(), "20");
1294 fn test_optmulti_missing() {
1295 let args = vec!("blah".to_string());
1296 let opts = vec!(optmulti("t", "test", "testing", "TEST"));
1297 let rs = getopts(&args, &opts);
1300 assert!(!m.opt_present("test"));
1301 assert!(!m.opt_present("t"));
1308 fn test_optmulti_no_arg() {
1309 let long_args = vec!("--test".to_string());
1310 let opts = vec!(optmulti("t", "test", "testing", "TEST"));
1311 let rs = getopts(&long_args, &opts);
1313 Err(ArgumentMissing(_)) => {},
1316 let short_args = vec!("-t".to_string());
1317 match getopts(&short_args, &opts) {
1318 Err(ArgumentMissing(_)) => {},
1324 fn test_optmulti_multi() {
1325 let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string());
1326 let opts = vec!(optmulti("t", "test", "testing", "TEST"));
1327 let rs = getopts(&args, &opts);
1330 assert!(m.opt_present("test"));
1331 assert_eq!(m.opt_str("test").unwrap(), "20");
1332 assert!(m.opt_present("t"));
1333 assert_eq!(m.opt_str("t").unwrap(), "20");
1334 let pair = m.opt_strs("test");
1335 assert!(pair[0] == "20");
1336 assert!(pair[1] == "30");
1343 fn test_unrecognized_option() {
1344 let long_args = vec!("--untest".to_string());
1345 let opts = vec!(optmulti("t", "test", "testing", "TEST"));
1346 let rs = getopts(&long_args, &opts);
1348 Err(UnrecognizedOption(_)) => {},
1351 let short_args = vec!("-u".to_string());
1352 match getopts(&short_args, &opts) {
1353 Err(UnrecognizedOption(_)) => {},
1359 fn test_combined() {
1361 vec!("prog".to_string(),
1362 "free1".to_string(),
1365 "free2".to_string(),
1366 "--flag".to_string(),
1367 "--long=30".to_string(),
1376 "-60 70".to_string());
1378 vec!(optopt("s", "something", "something", "SOMETHING"),
1379 optflag("", "flag", "a flag"),
1380 reqopt("", "long", "hi", "LONG"),
1381 optflag("f", "", "another flag"),
1382 optmulti("m", "", "mmmmmm", "YUM"),
1383 optmulti("n", "", "nothing", "NOTHING"),
1384 optopt("", "notpresent", "nothing to see here", "NOPE"));
1385 let rs = getopts(&args, &opts);
1388 assert!(m.free[0] == "prog");
1389 assert!(m.free[1] == "free1");
1390 assert_eq!(m.opt_str("s").unwrap(), "20");
1391 assert!(m.free[2] == "free2");
1392 assert!((m.opt_present("flag")));
1393 assert_eq!(m.opt_str("long").unwrap(), "30");
1394 assert!((m.opt_present("f")));
1395 let pair = m.opt_strs("m");
1396 assert!(pair[0] == "40");
1397 assert!(pair[1] == "50");
1398 let pair = m.opt_strs("n");
1399 assert!(pair[0] == "-A B");
1400 assert!(pair[1] == "-60 70");
1401 assert!((!m.opt_present("notpresent")));
1409 let opts = vec!(optopt("e", "", "encrypt", "ENCRYPT"),
1410 optopt("", "encrypt", "encrypt", "ENCRYPT"),
1411 optopt("f", "", "flag", "FLAG"));
1413 let args_single = vec!("-e".to_string(), "foo".to_string());
1414 let matches_single = &match getopts(&args_single, &opts) {
1415 result::Result::Ok(m) => m,
1416 result::Result::Err(_) => panic!()
1418 assert!(matches_single.opts_present(&["e".to_string()]));
1419 assert!(matches_single.opts_present(&["encrypt".to_string(), "e".to_string()]));
1420 assert!(matches_single.opts_present(&["e".to_string(), "encrypt".to_string()]));
1421 assert!(!matches_single.opts_present(&["encrypt".to_string()]));
1422 assert!(!matches_single.opts_present(&["thing".to_string()]));
1423 assert!(!matches_single.opts_present(&[]));
1425 assert_eq!(matches_single.opts_str(&["e".to_string()]).unwrap(), "foo");
1426 assert_eq!(matches_single.opts_str(&["e".to_string(), "encrypt".to_string()]).unwrap(),
1428 assert_eq!(matches_single.opts_str(&["encrypt".to_string(), "e".to_string()]).unwrap(),
1431 let args_both = vec!("-e".to_string(), "foo".to_string(), "--encrypt".to_string(),
1433 let matches_both = &match getopts(&args_both, &opts) {
1434 result::Result::Ok(m) => m,
1435 result::Result::Err(_) => panic!()
1437 assert!(matches_both.opts_present(&["e".to_string()]));
1438 assert!(matches_both.opts_present(&["encrypt".to_string()]));
1439 assert!(matches_both.opts_present(&["encrypt".to_string(), "e".to_string()]));
1440 assert!(matches_both.opts_present(&["e".to_string(), "encrypt".to_string()]));
1441 assert!(!matches_both.opts_present(&["f".to_string()]));
1442 assert!(!matches_both.opts_present(&["thing".to_string()]));
1443 assert!(!matches_both.opts_present(&[]));
1445 assert_eq!(matches_both.opts_str(&["e".to_string()]).unwrap(), "foo");
1446 assert_eq!(matches_both.opts_str(&["encrypt".to_string()]).unwrap(), "foo");
1447 assert_eq!(matches_both.opts_str(&["e".to_string(), "encrypt".to_string()]).unwrap(),
1449 assert_eq!(matches_both.opts_str(&["encrypt".to_string(), "e".to_string()]).unwrap(),
1455 let args = vec!("-Lfoo".to_string(), "-M.".to_string());
1456 let opts = vec!(optmulti("L", "", "library directory", "LIB"),
1457 optmulti("M", "", "something", "MMMM"));
1458 let matches = &match getopts(&args, &opts) {
1459 result::Result::Ok(m) => m,
1460 result::Result::Err(_) => panic!()
1462 assert!(matches.opts_present(&["L".to_string()]));
1463 assert_eq!(matches.opts_str(&["L".to_string()]).unwrap(), "foo");
1464 assert!(matches.opts_present(&["M".to_string()]));
1465 assert_eq!(matches.opts_str(&["M".to_string()]).unwrap(), ".");
1470 fn test_nospace_conflict() {
1471 let args = vec!("-vvLverbose".to_string(), "-v".to_string() );
1472 let opts = vec!(optmulti("L", "", "library directory", "LIB"),
1473 optflagmulti("v", "verbose", "Verbose"));
1474 let matches = &match getopts(&args, &opts) {
1475 result::Result::Ok(m) => m,
1476 result::Result::Err(e) => panic!( "{}", e )
1478 assert!(matches.opts_present(&["L".to_string()]));
1479 assert_eq!(matches.opts_str(&["L".to_string()]).unwrap(), "verbose");
1480 assert!(matches.opts_present(&["v".to_string()]));
1481 assert_eq!(3, matches.opt_count("v"));
1485 fn test_long_to_short() {
1486 let mut short = Opt {
1487 name: Name::Long("banana".to_string()),
1488 hasarg: HasArg::Yes,
1490 aliases: Vec::new(),
1492 short.aliases = vec!(Opt { name: Name::Short('b'),
1493 hasarg: HasArg::Yes,
1495 aliases: Vec::new() });
1496 let verbose = reqopt("b", "banana", "some bananas", "VAL");
1498 assert!(verbose.long_to_short() == short);
1502 fn test_aliases_long_and_short() {
1504 optflagmulti("a", "apple", "Desc"));
1506 let args = vec!("-a".to_string(), "--apple".to_string(), "-a".to_string());
1508 let matches = getopts(&args, &opts).unwrap();
1509 assert_eq!(3, matches.opt_count("a"));
1510 assert_eq!(3, matches.opt_count("apple"));
1515 let optgroups = vec!(
1516 reqopt("b", "banana", "Desc", "VAL"),
1517 optopt("a", "012345678901234567890123456789",
1519 optflag("k", "kiwi", "Desc"),
1520 optflagopt("p", "", "Desc", "VAL"),
1521 optmulti("l", "", "Desc", "VAL"));
1527 -b --banana VAL Desc
1528 -a --012345678901234567890123456789 VAL
1535 let generated_usage = usage("Usage: fruits", &optgroups);
1537 debug!("expected: <<{}>>", expected);
1538 debug!("generated: <<{}>>", generated_usage);
1539 assert_eq!(generated_usage, expected);
1543 fn test_usage_description_wrapping() {
1544 // indentation should be 24 spaces
1545 // lines wrap after 78: or rather descriptions wrap after 54
1547 let optgroups = vec!(
1548 optflag("k", "kiwi",
1549 "This is a long description which won't be wrapped..+.."), // 54
1550 optflag("a", "apple",
1551 "This is a long description which _will_ be wrapped..+.."));
1557 -k --kiwi This is a long description which won't be wrapped..+..
1558 -a --apple This is a long description which _will_ be
1562 let usage = usage("Usage: fruits", &optgroups);
1564 debug!("expected: <<{}>>", expected);
1565 debug!("generated: <<{}>>", usage);
1566 assert!(usage == expected)
1570 fn test_usage_description_multibyte_handling() {
1571 let optgroups = vec!(
1572 optflag("k", "k\u{2013}w\u{2013}",
1573 "The word kiwi is normally spelled with two i's"),
1574 optflag("a", "apple",
1575 "This \u{201C}description\u{201D} has some characters that could \
1576 confuse the line wrapping; an apple costs 0.51€ in some parts of Europe."));
1582 -k --k–w– The word kiwi is normally spelled with two i's
1583 -a --apple This “description” has some characters that could
1584 confuse the line wrapping; an apple costs 0.51€ in
1585 some parts of Europe.
1588 let usage = usage("Usage: fruits", &optgroups);
1590 debug!("expected: <<{}>>", expected);
1591 debug!("generated: <<{}>>", usage);
1592 assert!(usage == expected)
1596 fn test_short_usage() {
1597 let optgroups = vec!(
1598 reqopt("b", "banana", "Desc", "VAL"),
1599 optopt("a", "012345678901234567890123456789",
1601 optflag("k", "kiwi", "Desc"),
1602 optflagopt("p", "", "Desc", "VAL"),
1603 optmulti("l", "", "Desc", "VAL"));
1605 let expected = "Usage: fruits -b VAL [-a VAL] [-k] [-p [VAL]] [-l VAL]..".to_string();
1606 let generated_usage = short_usage("fruits", &optgroups);
1608 debug!("expected: <<{}>>", expected);
1609 debug!("generated: <<{}>>", generated_usage);
1610 assert_eq!(generated_usage, expected);