pub struct Parser { /* private fields */ }
Expand description
A parser for command line arguments.
Implementations§
source§impl Parser
impl Parser
sourcepub fn next(&mut self) -> Result<Option<Arg<'_>>, Error>
pub fn next(&mut self) -> Result<Option<Arg<'_>>, Error>
Get the next option or positional argument.
A return value of Ok(None)
means the command line has been exhausted.
Options that are not valid unicode are transformed with replacement
characters as by String::from_utf8_lossy
.
§Errors
Error::UnexpectedValue
is returned if the last option had a
value that hasn’t been consumed, as in --option=value
or -o=value
.
It’s possible to continue parsing after an error (but this is rarely useful).
sourcepub fn value(&mut self) -> Result<OsString, Error>
pub fn value(&mut self) -> Result<OsString, Error>
Get a value for an option.
This function should normally be called right after seeing an option
that expects a value, with positional arguments being collected
using next()
.
A value is collected even if it looks like an option
(i.e., starts with -
).
§Errors
An Error::MissingValue
is returned if the end of the command
line is reached.
sourcepub fn values(&mut self) -> Result<ValuesIter<'_>, Error>
pub fn values(&mut self) -> Result<ValuesIter<'_>, Error>
Gather multiple values for an option.
This is used for options that take multiple arguments, such as a
--command
flag that’s invoked as app --command echo 'Hello world'
.
It will gather arguments until another option is found, or --
is found, or
the end of the command line is reached. This differs from .value()
, which
takes a value even if it looks like an option.
An equals sign (=
) will limit this to a single value. That means -a=b c
and
--opt=b c
will only yield "b"
while -a b c
, -ab c
and --opt b c
will
yield "b"
, "c"
.
§Errors
If not at least one value is found then Error::MissingValue
is returned.
§Example
let arguments: Vec<OsString> = parser.values()?.collect();
let at_most_three_files: Vec<PathBuf> = parser.values()?.take(3).map(Into::into).collect();
for value in parser.values()? {
// ...
}
sourcepub fn raw_args(&mut self) -> Result<RawArgs<'_>, Error>
pub fn raw_args(&mut self) -> Result<RawArgs<'_>, Error>
Take raw arguments from the original command line.
This returns an iterator of OsString
s. Any arguments that are not
consumed are kept, so you can continue parsing after you’re done with
the iterator.
To inspect an argument without consuming it, use RawArgs::peek
or
RawArgs::as_slice
.
§Errors
Returns an Error::UnexpectedValue
if the last option had a left-over
argument, as in --option=value
, -ovalue
, or if it was midway through
an option chain, as in -abc
. The iterator only yields whole arguments.
To avoid this, use try_raw_args()
.
After this error the method is guaranteed to succeed, as it consumes the rest of the argument.
§Example
As soon as a free-standing argument is found, consume the other arguments as-is, and build them into a command.
Value(prog) => {
let args: Vec<_> = parser.raw_args()?.collect();
let command = std::process::Command::new(prog).args(args);
}
sourcepub fn try_raw_args(&mut self) -> Option<RawArgs<'_>>
pub fn try_raw_args(&mut self) -> Option<RawArgs<'_>>
Take raw arguments from the original command line, if the current argument has finished processing.
Unlike raw_args()
this does not consume any value
in case of a left-over argument. This makes it safe to call at any time.
It returns None
exactly when optional_value()
would return Some
.
Note: If no arguments are left then it returns an empty iterator (not None
).
§Example
Process arguments of the form -123
as numbers. For a complete runnable version of
this example, see
examples/nonstandard.rs
.
fn parse_dashnum(parser: &mut lexopt::Parser) -> Option<u64> {
let mut raw = parser.try_raw_args()?;
let arg = raw.peek()?.to_str()?;
let num = arg.strip_prefix('-')?.parse::<u64>().ok()?;
raw.next(); // Consume the argument we just parsed
Some(num)
}
loop {
if let Some(num) = parse_dashnum(&mut parser) {
println!("Got number {}", num);
} else if let Some(arg) = parser.next()? {
match arg {
// ...
}
} else {
break;
}
}
sourcepub fn bin_name(&self) -> Option<&str>
pub fn bin_name(&self) -> Option<&str>
The name of the command, as in the zeroth argument of the process.
This is intended for use in messages. If the name is not valid unicode
it will be sanitized with replacement characters as by
String::from_utf8_lossy
.
To get the current executable, use std::env::current_exe
.
§Example
let mut parser = lexopt::Parser::from_env();
let bin_name = parser.bin_name().unwrap_or("myapp");
println!("{}: Some message", bin_name);
sourcepub fn optional_value(&mut self) -> Option<OsString>
pub fn optional_value(&mut self) -> Option<OsString>
Get a value only if it’s concatenated to an option, as in -ovalue
or
--option=value
or -o=value
, but not -o value
or --option value
.
sourcepub fn from_env() -> Parser
pub fn from_env() -> Parser
Create a parser from the environment using std::env::args_os
.
This is the usual way to create a Parser
.
sourcepub fn from_iter<I>(args: I) -> Parser
pub fn from_iter<I>(args: I) -> Parser
Create a parser from an iterator. This is useful for testing among other things.
The first item from the iterator must be the binary name, as from std::env::args_os
.
The iterator is consumed immediately.
§Example
let mut parser = lexopt::Parser::from_iter(&["myapp", "-n", "10", "./foo.bar"]);
sourcepub fn from_args<I>(args: I) -> Parser
pub fn from_args<I>(args: I) -> Parser
Create a parser from an iterator that does not include the binary name.
The iterator is consumed immediately.
bin_name()
will return None
. Consider using
Parser::from_iter
instead.