pub struct Parser<'a> { /* private fields */ }
Expand description
A parser for command line arguments.
Implementations§
Source§impl<'a> Parser<'a>
impl<'a> Parser<'a>
Sourcepub fn new(raw: &'a dyn RawArgs) -> Self
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?
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}
Sourcepub fn next_arg(&mut self) -> Option<Arg<'a>>
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?
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}
Sourcepub fn next_flag_value(&mut self) -> Option<&'a OsStr>
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?
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}
Sourcepub fn next_attached_value(&mut self) -> Option<&'a OsStr>
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>]
.
Sourcepub fn next_raw(&mut self) -> Result<Option<&'a OsStr>, ()>
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?
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}
Sourcepub fn remaining_raw(
&mut self,
) -> Result<impl Iterator<Item = &'a OsStr> + '_, ()>
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