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.
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 mod extra;
use extra::getopts::*;
use std::os;
fn do_work(in: &str, out: Option<~str>) {
println(in);
println(match out {
Some(x) => x,
None => ~"No Output"
});
}
fn print_usage(program: &str, _opts: &[Opt]) {
println(fmt!("Usage: %s [options]", program));
println("-o\\t\\tOutput");
println("-h --help\\tUsage");
}
fn main() {
let args = os::args();
let program = copy args[0];
let opts = ~[
optopt("o"),
optflag("h"),
optflag("help")
];
let matches = match getopts(args.tail(), opts) {
Ok(m) => { m }
Err(f) => { fail!(fail_str(f)) }
};
if opt_present(&matches, "h") || opt_present(&matches, "help") {
print_usage(program, opts);
return;
}
let output = opt_maybe_str(&matches, "o");
let input: &str = if !matches.free.is_empty() {
copy matches.free[0]
} else {
print_usage(program, opts);
return;
};
do_work(input, output);
}
Result
- The result of parsing a command line with a set of options (result::tFailType
Fail_
- The type returned when the command line does not conform to the expected formatHasArg
Name
Occur
Matches
- The result of checking command line argumentsOpt
- A description of a possible optionof ::std::cmp::Eq for Name
- Automatically derived.of ::std::cmp::Eq for HasArg
- Automatically derived.of ::std::cmp::Eq for Occur
- Automatically derived.of ::std::cmp::Eq for Opt
- Automatically derived.of ::std::cmp::Eq for Optval
- Automatically derived.of ::std::cmp::Eq for Matches
- Automatically derived.of ::std::cmp::Eq for Fail_
- Automatically derived.of ::std::cmp::Eq for FailType
- Automatically derived.fail_str
- Convert a fail_
enum into an error stringgetopts
- Parse command line arguments according to the provided optionsopt_count
- Returns the number of times an option was matchedopt_default
- Returns the matching string, a default, or noneopt_maybe_str
- Returns the string argument supplied to a matching option or noneopt_present
- Returns true if an option was matchedopt_str
- Returns the string argument supplied to a matching optionopt_strs
- Returns a vector of the arguments provided to all matches of the given option.optflag
- Create an option that is optional and does not take an argumentoptflagmulti
- Create an option that is optional and does not take an argumentoptflagopt
- Create an option that is optional and takes an optional argumentoptmulti
- Create an option that is optional, takes an argument, and may occur multiple timesoptopt
- Create an option that is optional and takes an argumentopts_present
- Returns true if any of several options were matchedopts_str
- Returns the string argument supplied to one of several matching optionsreqopt
- Create an option that is required and takes an argumentgetopts::groups
- A module which provides a way to specify descriptions and * groups of short and long option names, together.Result
type Result = result::Result<Matches, Fail_>
The result of parsing a command line with a set of options (result::t
FailType
ArgumentMissing_
UnrecognizedOption_
OptionMissing_
OptionDuplicated_
UnexpectedArgument_
Fail_
The type returned when the command line does not conform to the expected format. Pass this value to
ArgumentMissing(~str)
UnrecognizedOption(~str)
OptionMissing(~str)
OptionDuplicated(~str)
UnexpectedArgument(~str)
HasArg
Yes
No
Maybe
Name
Long(~str)
Short(char)
Occur
Req
Optional
Multi
Matches
pub struct Matches {
opts: ~[Opt],
vals: ~[~[Optval]],
free: ~[~str],
}
The result of checking command line arguments. Contains a vector of matches and a vector of free strings.
Opt
pub struct Opt {
name: Name,
hasarg: HasArg,
occur: Occur,
}
A description of a possible option
::std::cmp::Eq
for Name
Automatically derived.
eq
fn eq(&self, __arg_0: &Name) -> ::bool
ne
fn ne(&self, __arg_0: &Name) -> ::bool
::std::cmp::Eq
for HasArg
Automatically derived.
eq
fn eq(&self, __arg_0: &HasArg) -> ::bool
ne
fn ne(&self, __arg_0: &HasArg) -> ::bool
::std::cmp::Eq
for Occur
Automatically derived.
eq
fn eq(&self, __arg_0: &Occur) -> ::bool
ne
fn ne(&self, __arg_0: &Occur) -> ::bool
::std::cmp::Eq
for Opt
Automatically derived.
eq
fn eq(&self, __arg_0: &Opt) -> ::bool
ne
fn ne(&self, __arg_0: &Opt) -> ::bool
::std::cmp::Eq
for Optval
Automatically derived.
eq
fn eq(&self, __arg_0: &Optval) -> ::bool
ne
fn ne(&self, __arg_0: &Optval) -> ::bool
::std::cmp::Eq
for Matches
Automatically derived.
eq
fn eq(&self, __arg_0: &Matches) -> ::bool
ne
fn ne(&self, __arg_0: &Matches) -> ::bool
::std::cmp::Eq
for Fail_
Automatically derived.
eq
fn eq(&self, __arg_0: &Fail_) -> ::bool
ne
fn ne(&self, __arg_0: &Fail_) -> ::bool
::std::cmp::Eq
for FailType
Automatically derived.
eq
fn eq(&self, __arg_0: &FailType) -> ::bool
ne
fn ne(&self, __arg_0: &FailType) -> ::bool
fail_str
fn fail_str(f: Fail_) -> ~str
Convert a fail_
enum into an error string
getopts
fn getopts(args: &[~str], opts: &[Opt]) -> Result
Parse command line arguments according to the provided options
On success returns ok(Opt)
. Use functions such as opt_present
opt_str
, etc. to interrogate results. Returns err(Fail_)
on failure. Use
opt_count
fn opt_count(mm: &Matches, nm: &str) -> uint
Returns the number of times an option was matched
opt_default
fn opt_default(mm: &Matches, nm: &str, def: &str) -> Option<~str>
Returns the matching string, a default, or none
Returns none if the option was not present, def
if the option was present but no argument was provided, and the argument if the option was present and an argument was provided.
opt_maybe_str
fn opt_maybe_str(mm: &Matches, nm: &str) -> Option<~str>
Returns the string argument supplied to a matching option or none
opt_present
fn opt_present(mm: &Matches, nm: &str) -> bool
Returns true if an option was matched
opt_str
fn opt_str(mm: &Matches, nm: &str) -> ~str
Returns the string argument supplied to a matching option
Fails if the option was not matched or if the match did not take an argument
opt_strs
fn opt_strs(mm: &Matches, nm: &str) -> ~[~str]
Returns a vector of the arguments provided to all matches of the given option.
Used when an option accepts multiple values.
optflag
fn optflag(name: &str) -> Opt
Create an option that is optional and does not take an argument
optflagmulti
fn optflagmulti(name: &str) -> Opt
Create an option that is optional and does not take an argument
optflagopt
fn optflagopt(name: &str) -> Opt
Create an option that is optional and takes an optional argument
optmulti
fn optmulti(name: &str) -> Opt
Create an option that is optional, takes an argument, and may occur multiple times
optopt
fn optopt(name: &str) -> Opt
Create an option that is optional and takes an argument
opts_present
fn opts_present(mm: &Matches, names: &[~str]) -> bool
Returns true if any of several options were matched
opts_str
fn opts_str(mm: &Matches, names: &[~str]) -> ~str
Returns the string argument supplied to one of several matching options
Fails if the no option was provided from the given list, or if the no such option took an argument
reqopt
fn reqopt(name: &str) -> Opt
Create an option that is required and takes an argument