Crate getopts [stability]
[-] [+]
[src]
Simple getopt alternative.
Construct a vector of options, either by using reqopt
, optopt
, and optflag
or by building them from components yourself, and pass them to getopts
,
along with a vector of actual arguments (not including argv[0]
). You'll
either get a failure code back, or a match. You'll have to verify whether
the amount of 'free' arguments in the match is what you expect. Use opt_*
accessors to get argument values out of the matches object.
Single-character options are expected to appear on the command line with a single preceding dash; multiple-character options are expected to be proceeded by two dashes. Options that expect an argument accept their argument following either a space or an equals sign. Single-character options don't require the space.
Example
The following example shows simple command line parsing for an application
that requires an input file to be specified, accepts an optional output
file name following -o
, and accepts both -h
and --help
as optional flags.
extern crate getopts; use getopts::Options; use std::os; fn do_work(inp: &str, out: Option<String>) { println!("{}", inp); match out { Some(x) => println!("{}", x), None => println!("No Output"), } } fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options]", program); print!("{}", opts.usage(brief.as_slice())); } fn main() { let args: Vec<String> = os::args(); let program = args[0].clone(); let mut opts = Options::new(); opts.optopt("o", "", "set output file name", "NAME"); opts.optflag("h", "help", "print this help menu"); let matches = match opts.parse(args.tail()) { Ok(m) => { m } Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("h") { print_usage(program.as_slice(), opts); return; } let output = matches.opt_str("o"); let input = if !matches.free.is_empty() { matches.free[0].clone() } else { print_usage(program.as_slice(), opts); return; }; do_work(input.as_slice(), output); }
Structs
Matches | The result of checking command line arguments. Contains a vector of matches and a vector of free strings. |
Options | A description of the options that a program can handle |
Enums
Fail | The type returned when the command line does not conform to the
expected format. Use the |
FailType | The type of failure that occurred. |
HasArg | Describes whether an option has an argument. |
Occur | Describes how often an option may occur. |
ParsingStyle | What parsing style to use when parsing arguments |
Type Definitions
Result | The result of parsing a command line with a set of options. |