Enum Arg

Source
pub enum Arg<'a> {
    Short(char),
    Long(&'a str),
    Value(OsString),
}
Expand description

A command line argument found by Parser, either an option or a positional argument.

Variants§

§

Short(char)

A short option, e.g. Short('q') for -q.

§

Long(&'a str)

A long option, e.g. Long("verbose") for --verbose. (The dashes are not included.)

§

Value(OsString)

A positional argument, e.g. /dev/null.

Implementations§

Source§

impl Arg<'_>

Source

pub fn unexpected(self) -> Error

Convert an unexpected argument into an error.

Examples found in repository?
examples/posixly_correct.rs (line 32)
14fn main() -> Result<(), lexopt::Error> {
15    use lexopt::prelude::*;
16
17    let mut parser = lexopt::Parser::from_env();
18    let mut free = Vec::new();
19    while let Some(arg) = parser.next()? {
20        match arg {
21            Short('n') | Long("number") => {
22                let num: u16 = parser.value()?.parse()?;
23                println!("Got number {}", num);
24            }
25            Long("shout") => {
26                println!("Got --shout");
27            }
28            Value(val) => {
29                free.push(val);
30                free.extend(parser.raw_args()?);
31            }
32            _ => return Err(arg.unexpected()),
33        }
34    }
35    println!("Got free args {:?}", free);
36    Ok(())
37}
More examples
Hide additional examples
examples/hello.rs (line 29)
7fn parse_args() -> Result<Args, lexopt::Error> {
8    use lexopt::prelude::*;
9
10    let mut thing = None;
11    let mut number = 1;
12    let mut shout = false;
13    let mut parser = lexopt::Parser::from_env();
14    while let Some(arg) = parser.next()? {
15        match arg {
16            Short('n') | Long("number") => {
17                number = parser.value()?.parse()?;
18            }
19            Long("shout") => {
20                shout = true;
21            }
22            Value(val) if thing.is_none() => {
23                thing = Some(val.string()?);
24            }
25            Long("help") => {
26                println!("Usage: hello [-n|--number=NUM] [--shout] THING");
27                std::process::exit(0);
28            }
29            _ => return Err(arg.unexpected()),
30        }
31    }
32
33    Ok(Args {
34        thing: thing.ok_or("missing argument THING")?,
35        number,
36        shout,
37    })
38}
examples/nonstandard.rs (line 40)
20fn main() -> Result<(), lexopt::Error> {
21    use lexopt::prelude::*;
22
23    let mut parser = lexopt::Parser::from_env();
24    loop {
25        if let Some(num) = parse_dashnum(&mut parser) {
26            println!("Got number {}", num);
27        } else if let Some(arg) = parser.next()? {
28            match arg {
29                Short('f') | Long("follow") => {
30                    println!("Got --follow");
31                }
32                Short('n') | Long("number") => {
33                    let num: u64 = parser.value()?.parse()?;
34                    println!("Got number {}", num);
35                }
36                Value(path) => {
37                    let path = PathBuf::from(path);
38                    println!("Got file {}", path.display());
39                }
40                _ => return Err(arg.unexpected()),
41            }
42        } else {
43            break;
44        }
45    }
46
47    Ok(())
48}
examples/pico_test_app.rs (line 68)
49fn parse_args() -> Result<AppArgs, lexopt::Error> {
50    use lexopt::prelude::*;
51
52    let mut number = None;
53    let mut opt_number = None;
54    let mut width = 10;
55    let mut input = None;
56
57    let mut parser = lexopt::Parser::from_env();
58    while let Some(arg) = parser.next()? {
59        match arg {
60            Short('h') | Long("help") => {
61                print!("{}", HELP);
62                std::process::exit(0);
63            }
64            Long("number") => number = Some(parser.value()?.parse()?),
65            Long("opt-number") => opt_number = Some(parser.value()?.parse()?),
66            Long("width") => width = parser.value()?.parse_with(parse_width)?,
67            Value(path) if input.is_none() => input = Some(path.into()),
68            _ => return Err(arg.unexpected()),
69        }
70    }
71    Ok(AppArgs {
72        number: number.ok_or("missing required option --number")?,
73        opt_number,
74        width,
75        input: input.ok_or("missing required argument INPUT")?,
76    })
77}
examples/cargo.rs (line 55)
9fn main() -> Result<(), lexopt::Error> {
10    use lexopt::prelude::*;
11
12    let mut settings = GlobalSettings {
13        toolchain: "stable".to_owned(),
14        color: Color::Auto,
15        offline: false,
16        quiet: false,
17        verbose: false,
18    };
19
20    let mut parser = lexopt::Parser::from_env();
21    while let Some(arg) = parser.next()? {
22        match arg {
23            Long("color") => {
24                settings.color = parser.value()?.parse()?;
25            }
26            Long("offline") => {
27                settings.offline = true;
28            }
29            Long("quiet") => {
30                settings.quiet = true;
31                settings.verbose = false;
32            }
33            Long("verbose") => {
34                settings.verbose = true;
35                settings.quiet = false;
36            }
37            Long("help") => {
38                println!("{}", HELP);
39                std::process::exit(0);
40            }
41            Value(value) => {
42                let value = value.string()?;
43                match value.as_str() {
44                    value if value.starts_with('+') => {
45                        settings.toolchain = value[1..].to_owned();
46                    }
47                    "install" => {
48                        return install(settings, parser);
49                    }
50                    value => {
51                        return Err(format!("unknown subcommand '{}'", value).into());
52                    }
53                }
54            }
55            _ => return Err(arg.unexpected()),
56        }
57    }
58
59    println!("{}", HELP);
60    Ok(())
61}
62
63#[derive(Debug)]
64struct GlobalSettings {
65    toolchain: String,
66    color: Color,
67    offline: bool,
68    quiet: bool,
69    verbose: bool,
70}
71
72fn install(settings: GlobalSettings, mut parser: lexopt::Parser) -> Result<(), lexopt::Error> {
73    use lexopt::prelude::*;
74
75    let mut package: Option<String> = None;
76    let mut root: Option<PathBuf> = None;
77    let mut jobs: u16 = get_no_of_cpus();
78
79    while let Some(arg) = parser.next()? {
80        match arg {
81            Value(value) if package.is_none() => {
82                package = Some(value.string()?);
83            }
84            Long("root") => {
85                root = Some(parser.value()?.into());
86            }
87            Short('j') | Long("jobs") => {
88                jobs = parser.value()?.parse()?;
89            }
90            Long("help") => {
91                println!("cargo install [OPTIONS] CRATE");
92                std::process::exit(0);
93            }
94            _ => return Err(arg.unexpected()),
95        }
96    }
97
98    println!("Settings: {:#?}", settings);
99    println!(
100        "Installing {} into {:?} with {} jobs",
101        package.ok_or("missing CRATE argument")?,
102        root,
103        jobs
104    );
105
106    Ok(())
107}

Trait Implementations§

Source§

impl<'a> Clone for Arg<'a>

Source§

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

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<'a> Debug for Arg<'a>

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<'a> PartialEq for Arg<'a>

Source§

fn eq(&self, other: &Arg<'a>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a> Eq for Arg<'a>

Source§

impl<'a> StructuralPartialEq for Arg<'a>

Auto Trait Implementations§

§

impl<'a> Freeze for Arg<'a>

§

impl<'a> RefUnwindSafe for Arg<'a>

§

impl<'a> Send for Arg<'a>

§

impl<'a> Sync for Arg<'a>

§

impl<'a> Unpin for Arg<'a>

§

impl<'a> UnwindSafe for Arg<'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.