Expand description
Simple argument parser
The goals of this library are to correctly handle OsString and produce high-quality error messages.
This library is like the traditional getopt
with better error reporting. It converts an
iterator of String
or OsString
to positional arguments and named arguments.
Single and double hyphens are considered equivalent. This means that -help
and --help
are
equivalent. Opinion: Most new projects should parse each argument as a separate flag. So, -abc
should be parsed as one argument named "abc"
, not three arguments named "a"
, "b"
, and
"c"
. Combining multiple flags into one argument is confusing, so it should only be used for
programs that are called interactively very frequently, like ls
.
Options which take values can take values either as one argument, -option=value
, or as two
arguments, -option value
.
§Example
use simpleargs::{Arg, Args, UsageError, OptionError};
use std::ffi::OsString;
use std::str::FromStr;
fn parse_args<T>(mut args: Args<T>) -> Result<(), UsageError<OsString>>
where
T: Iterator<Item = OsString>,
{
// The input file
let mut input: Option<OsString> = None;
// True if -flag was set
let mut flag = false;
// The value of -xvalue, if it was used
let mut xvalue: Option<i32> = None;
loop {
match args.next() {
Arg::Positional(arg) => if input.is_some() {
return Err(UsageError::UnexpectedArgument { arg });
} else {
input = Some(arg)
}
Arg::Named(arg) => arg.parse(|name, value| match name {
"flag" => {
// parse() above will return an error for -flag=value,
// because this function does not use 'value'.
flag = true;
Ok(())
}
"xvalue" => {
// Call as_str() for a str, or as_osstr() for OsStr.
xvalue = Some(i32::from_str(value.as_str()?)?);
Ok(())
}
_ => Err(OptionError::Unknown),
})?,
Arg::End => break,
Arg::Error(err) => return Err(err),
}
}
let input = match input {
Some(path) => path,
None => return Err(UsageError::MissingArgument { name: "input".to_owned() }),
};
Ok(())
}
Modules§
- arg
- Low-level argument parsing.
Structs§
- Args
- A stream of arguments.
- Named
Argument - A named command-line argument which may or may not have an associated value.
- Value
- A handle for getting the value associated with a named flag.UsageError
Enums§
- Arg
- A single argument in a stream of arguments.
- Option
Error - An error for an invalid named argument.
- Usage
Error - A command-line usage error, for when the user has passed incorrect arguments to the program.