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

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-parser.rs (line 15)
7fn parse_args() -> Result<Args, &'static str> {
8    #![allow(clippy::enum_glob_use)]
9    use lexarg_parser::Arg::*;
10
11    let mut thing = None;
12    let mut number = 1;
13    let mut shout = false;
14    let raw = std::env::args_os().collect::<Vec<_>>();
15    let mut parser = lexarg_parser::Parser::new(&raw);
16    let _bin_name = parser.next_raw();
17    while let Some(arg) = parser.next_arg() {
18        match arg {
19            Short("n") | Long("number") => {
20                number = parser
21                    .next_flag_value()
22                    .ok_or("`--number` requires a value")?
23                    .to_str()
24                    .ok_or("invalid number")?
25                    .parse()
26                    .map_err(|_e| "invalid number")?;
27            }
28            Long("shout") => {
29                shout = true;
30            }
31            Value(val) if thing.is_none() => {
32                thing = Some(val.to_str().ok_or("invalid string")?);
33            }
34            Short("h") | Long("help") => {
35                println!("Usage: hello [-n|--number=NUM] [--shout] THING");
36                std::process::exit(0);
37            }
38            _ => {
39                return Err("unexpected argument");
40            }
41        }
42    }
43
44    Ok(Args {
45        thing: thing.ok_or("missing argument THING")?.to_owned(),
46        number,
47        shout,
48    })
49}
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-parser.rs (line 17)
7fn parse_args() -> Result<Args, &'static str> {
8    #![allow(clippy::enum_glob_use)]
9    use lexarg_parser::Arg::*;
10
11    let mut thing = None;
12    let mut number = 1;
13    let mut shout = false;
14    let raw = std::env::args_os().collect::<Vec<_>>();
15    let mut parser = lexarg_parser::Parser::new(&raw);
16    let _bin_name = parser.next_raw();
17    while let Some(arg) = parser.next_arg() {
18        match arg {
19            Short("n") | Long("number") => {
20                number = parser
21                    .next_flag_value()
22                    .ok_or("`--number` requires a value")?
23                    .to_str()
24                    .ok_or("invalid number")?
25                    .parse()
26                    .map_err(|_e| "invalid number")?;
27            }
28            Long("shout") => {
29                shout = true;
30            }
31            Value(val) if thing.is_none() => {
32                thing = Some(val.to_str().ok_or("invalid string")?);
33            }
34            Short("h") | Long("help") => {
35                println!("Usage: hello [-n|--number=NUM] [--shout] THING");
36                std::process::exit(0);
37            }
38            _ => {
39                return Err("unexpected argument");
40            }
41        }
42    }
43
44    Ok(Args {
45        thing: thing.ok_or("missing argument THING")?.to_owned(),
46        number,
47        shout,
48    })
49}
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-parser.rs (line 21)
7fn parse_args() -> Result<Args, &'static str> {
8    #![allow(clippy::enum_glob_use)]
9    use lexarg_parser::Arg::*;
10
11    let mut thing = None;
12    let mut number = 1;
13    let mut shout = false;
14    let raw = std::env::args_os().collect::<Vec<_>>();
15    let mut parser = lexarg_parser::Parser::new(&raw);
16    let _bin_name = parser.next_raw();
17    while let Some(arg) = parser.next_arg() {
18        match arg {
19            Short("n") | Long("number") => {
20                number = parser
21                    .next_flag_value()
22                    .ok_or("`--number` requires a value")?
23                    .to_str()
24                    .ok_or("invalid number")?
25                    .parse()
26                    .map_err(|_e| "invalid number")?;
27            }
28            Long("shout") => {
29                shout = true;
30            }
31            Value(val) if thing.is_none() => {
32                thing = Some(val.to_str().ok_or("invalid string")?);
33            }
34            Short("h") | Long("help") => {
35                println!("Usage: hello [-n|--number=NUM] [--shout] THING");
36                std::process::exit(0);
37            }
38            _ => {
39                return Err("unexpected argument");
40            }
41        }
42    }
43
44    Ok(Args {
45        thing: thing.ok_or("missing argument THING")?.to_owned(),
46        number,
47        shout,
48    })
49}
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-parser.rs (line 16)
7fn parse_args() -> Result<Args, &'static str> {
8    #![allow(clippy::enum_glob_use)]
9    use lexarg_parser::Arg::*;
10
11    let mut thing = None;
12    let mut number = 1;
13    let mut shout = false;
14    let raw = std::env::args_os().collect::<Vec<_>>();
15    let mut parser = lexarg_parser::Parser::new(&raw);
16    let _bin_name = parser.next_raw();
17    while let Some(arg) = parser.next_arg() {
18        match arg {
19            Short("n") | Long("number") => {
20                number = parser
21                    .next_flag_value()
22                    .ok_or("`--number` requires a value")?
23                    .to_str()
24                    .ok_or("invalid number")?
25                    .parse()
26                    .map_err(|_e| "invalid number")?;
27            }
28            Long("shout") => {
29                shout = true;
30            }
31            Value(val) if thing.is_none() => {
32                thing = Some(val.to_str().ok_or("invalid string")?);
33            }
34            Short("h") | Long("help") => {
35                println!("Usage: hello [-n|--number=NUM] [--shout] THING");
36                std::process::exit(0);
37            }
38            _ => {
39                return Err("unexpected argument");
40            }
41        }
42    }
43
44    Ok(Args {
45        thing: thing.ok_or("missing argument THING")?.to_owned(),
46        number,
47        shout,
48    })
49}
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

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.