Struct lexopt::Parser

source ·
pub struct Parser { /* private fields */ }
Expand description

A parser for command line arguments.

Implementations§

source§

impl Parser

source

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).

source

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.

source

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()? {
    // ...
}
source

pub fn raw_args(&mut self) -> Result<RawArgs<'_>, Error>

Take raw arguments from the original command line.

This returns an iterator of OsStrings. 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);
}
source

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;
    }
}
source

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);
source

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.

source

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.

source

pub fn from_iter<I>(args: I) -> Parser
where I: IntoIterator, I::Item: Into<OsString>,

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"]);
source

pub fn from_args<I>(args: I) -> Parser
where I: IntoIterator, I::Item: Into<OsString>,

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.

Trait Implementations§

source§

impl Clone for Parser

source§

fn clone(&self) -> Parser

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Parser

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Parser

§

impl RefUnwindSafe for Parser

§

impl Send for Parser

§

impl Sync for Parser

§

impl Unpin for Parser

§

impl UnwindSafe for Parser

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.