Parser

Struct Parser 

Source
pub struct Parser<'a> { /* private fields */ }
Expand description

A parser for command line arguments.

Implementations§

Source§

impl<'a> Parser<'a>

Source

pub fn new(raw: &'a dyn RawArgs) -> Parser<'a>

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 args = ["myapp", "-n", "10", "./foo.bar"];
let mut parser = lexarg_parser::Parser::new(&&args[1..]);
Examples found in repository?
examples/hello.rs (line 17)
10fn parse_args() -> Result<Args> {
11    use lexarg::prelude::*;
12
13    let mut thing = None;
14    let mut number = 1;
15    let mut shout = false;
16    let raw = std::env::args_os().collect::<Vec<_>>();
17    let mut parser = lexarg::Parser::new(&raw);
18    let bin_name = parser
19        .next_raw()
20        .expect("nothing parsed yet so no attached lingering")
21        .expect("always at least one");
22    let mut prev_arg = Value(bin_name);
23    while let Some(arg) = parser.next_arg() {
24        match arg {
25            Short("n") | Long("number") => {
26                number = parser
27                    .next_flag_value()
28                    .ok_or_missing(Value(std::ffi::OsStr::new("NUM")))
29                    .parse()
30                    .within(arg)?;
31            }
32            Long("shout") => {
33                shout = true;
34            }
35            Value(val) if thing.is_none() => {
36                thing = Some(val.string("THING")?);
37            }
38            Short("h") | Long("help") => {
39                println!("Usage: hello [-n|--number=NUM] [--shout] THING");
40                std::process::exit(0);
41            }
42            Unexpected(_) => {
43                return Err(LexError::msg("unexpected value")
44                    .unexpected(arg)
45                    .within(prev_arg)
46                    .into());
47            }
48            _ => {
49                return Err(LexError::msg("unexpected argument").unexpected(arg).into());
50            }
51        }
52        prev_arg = arg;
53    }
54
55    Ok(Args {
56        thing: thing
57            .ok_or_missing(Value(std::ffi::OsStr::new("THING")))
58            .within(Value(bin_name))?
59            .to_owned(),
60        number,
61        shout,
62    })
63}
Source

pub fn next_arg(&mut self) -> Option<Arg<'a>>

Get the next option or positional Arg.

Returns None if the command line has been exhausted.

Returns Arg::Unexpected on failure

Notes:

  • = is always accepted as a [Arg::Short("=")]. If that isn’t the case in your application, you may want to special case the error for that.
Examples found in repository?
examples/hello.rs (line 23)
10fn parse_args() -> Result<Args> {
11    use lexarg::prelude::*;
12
13    let mut thing = None;
14    let mut number = 1;
15    let mut shout = false;
16    let raw = std::env::args_os().collect::<Vec<_>>();
17    let mut parser = lexarg::Parser::new(&raw);
18    let bin_name = parser
19        .next_raw()
20        .expect("nothing parsed yet so no attached lingering")
21        .expect("always at least one");
22    let mut prev_arg = Value(bin_name);
23    while let Some(arg) = parser.next_arg() {
24        match arg {
25            Short("n") | Long("number") => {
26                number = parser
27                    .next_flag_value()
28                    .ok_or_missing(Value(std::ffi::OsStr::new("NUM")))
29                    .parse()
30                    .within(arg)?;
31            }
32            Long("shout") => {
33                shout = true;
34            }
35            Value(val) if thing.is_none() => {
36                thing = Some(val.string("THING")?);
37            }
38            Short("h") | Long("help") => {
39                println!("Usage: hello [-n|--number=NUM] [--shout] THING");
40                std::process::exit(0);
41            }
42            Unexpected(_) => {
43                return Err(LexError::msg("unexpected value")
44                    .unexpected(arg)
45                    .within(prev_arg)
46                    .into());
47            }
48            _ => {
49                return Err(LexError::msg("unexpected argument").unexpected(arg).into());
50            }
51        }
52        prev_arg = arg;
53    }
54
55    Ok(Args {
56        thing: thing
57            .ok_or_missing(Value(std::ffi::OsStr::new("THING")))
58            .within(Value(bin_name))?
59            .to_owned(),
60        number,
61        shout,
62    })
63}
Source

pub fn next_flag_value(&mut self) -> Option<&'a OsStr>

Get a flag’s value

This function should normally be called right after seeing a flag that expects a value; positional arguments should be collected with Parser::next_arg().

A value is collected even if it looks like an option (i.e., starts with -).

None is returned if there is not another applicable flag value, including:

  • No more arguments are present
  • -- was encountered, meaning all remaining arguments are positional
  • Being called again when the first value was attached (--flag=value, -Fvalue, -F=value)
Examples found in repository?
examples/hello.rs (line 27)
10fn parse_args() -> Result<Args> {
11    use lexarg::prelude::*;
12
13    let mut thing = None;
14    let mut number = 1;
15    let mut shout = false;
16    let raw = std::env::args_os().collect::<Vec<_>>();
17    let mut parser = lexarg::Parser::new(&raw);
18    let bin_name = parser
19        .next_raw()
20        .expect("nothing parsed yet so no attached lingering")
21        .expect("always at least one");
22    let mut prev_arg = Value(bin_name);
23    while let Some(arg) = parser.next_arg() {
24        match arg {
25            Short("n") | Long("number") => {
26                number = parser
27                    .next_flag_value()
28                    .ok_or_missing(Value(std::ffi::OsStr::new("NUM")))
29                    .parse()
30                    .within(arg)?;
31            }
32            Long("shout") => {
33                shout = true;
34            }
35            Value(val) if thing.is_none() => {
36                thing = Some(val.string("THING")?);
37            }
38            Short("h") | Long("help") => {
39                println!("Usage: hello [-n|--number=NUM] [--shout] THING");
40                std::process::exit(0);
41            }
42            Unexpected(_) => {
43                return Err(LexError::msg("unexpected value")
44                    .unexpected(arg)
45                    .within(prev_arg)
46                    .into());
47            }
48            _ => {
49                return Err(LexError::msg("unexpected argument").unexpected(arg).into());
50            }
51        }
52        prev_arg = arg;
53    }
54
55    Ok(Args {
56        thing: thing
57            .ok_or_missing(Value(std::ffi::OsStr::new("THING")))
58            .within(Value(bin_name))?
59            .to_owned(),
60        number,
61        shout,
62    })
63}
Source

pub fn next_attached_value(&mut self) -> Option<&'a OsStr>

Get a flag’s attached value (--flag=value, -Fvalue, -F=value)

This is a more specialized variant of Parser::next_flag_value for when only attached values are allowed, e.g. --color[=<when>].

Source

pub fn next_raw(&mut self) -> Result<Option<&'a OsStr>, ()>

Get the next argument, independent of what it looks like

Returns Err(()) if an attached value is present

Examples found in repository?
examples/hello.rs (line 19)
10fn parse_args() -> Result<Args> {
11    use lexarg::prelude::*;
12
13    let mut thing = None;
14    let mut number = 1;
15    let mut shout = false;
16    let raw = std::env::args_os().collect::<Vec<_>>();
17    let mut parser = lexarg::Parser::new(&raw);
18    let bin_name = parser
19        .next_raw()
20        .expect("nothing parsed yet so no attached lingering")
21        .expect("always at least one");
22    let mut prev_arg = Value(bin_name);
23    while let Some(arg) = parser.next_arg() {
24        match arg {
25            Short("n") | Long("number") => {
26                number = parser
27                    .next_flag_value()
28                    .ok_or_missing(Value(std::ffi::OsStr::new("NUM")))
29                    .parse()
30                    .within(arg)?;
31            }
32            Long("shout") => {
33                shout = true;
34            }
35            Value(val) if thing.is_none() => {
36                thing = Some(val.string("THING")?);
37            }
38            Short("h") | Long("help") => {
39                println!("Usage: hello [-n|--number=NUM] [--shout] THING");
40                std::process::exit(0);
41            }
42            Unexpected(_) => {
43                return Err(LexError::msg("unexpected value")
44                    .unexpected(arg)
45                    .within(prev_arg)
46                    .into());
47            }
48            _ => {
49                return Err(LexError::msg("unexpected argument").unexpected(arg).into());
50            }
51        }
52        prev_arg = arg;
53    }
54
55    Ok(Args {
56        thing: thing
57            .ok_or_missing(Value(std::ffi::OsStr::new("THING")))
58            .within(Value(bin_name))?
59            .to_owned(),
60        number,
61        shout,
62    })
63}
Source

pub fn remaining_raw(&mut self) -> Result<impl Iterator<Item = &'a OsStr>, ()>

Collect all remaining arguments, independent of what they look like

Returns Err(()) if an attached value is present

Source

pub fn peek_raw(&self) -> Result<Option<&'a OsStr>, ()>

Get the next argument, independent of what it looks like

Returns Err(()) if an attached value is present

Trait Implementations§

Source§

impl<'a> Clone for Parser<'a>

Source§

fn clone(&self) -> Parser<'a>

Returns a duplicate 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<'a> Debug for Parser<'a>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for Parser<'a>

§

impl<'a> !RefUnwindSafe for Parser<'a>

§

impl<'a> !Send for Parser<'a>

§

impl<'a> !Sync for Parser<'a>

§

impl<'a> Unpin for Parser<'a>

§

impl<'a> !UnwindSafe for Parser<'a>

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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,

Source§

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>,

Source§

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>,

Source§

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.