Enum lexopt::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§

Convert an unexpected argument into an error.

Examples found in repository?
examples/posixly_correct.rs (line 29)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
fn main() -> Result<(), lexopt::Error> {
    use lexopt::prelude::*;

    let mut parser = lexopt::Parser::from_env();
    let mut free = Vec::new();
    while let Some(arg) = parser.next()? {
        match arg {
            Short('n') | Long("number") => {
                let num: u16 = parser.value()?.parse()?;
                println!("Got number {}", num);
            }
            Long("shout") => {
                println!("Got --shout");
            }
            Value(val) => {
                free.push(val);
                free.extend(parser.raw_args()?);
            }
            _ => return Err(arg.unexpected()),
        }
    }
    println!("Got free args {:?}", free);
    Ok(())
}
More examples
Hide additional examples
examples/hello.rs (line 29)
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
fn parse_args() -> Result<Args, lexopt::Error> {
    use lexopt::prelude::*;

    let mut thing = None;
    let mut number = 1;
    let mut shout = false;
    let mut parser = lexopt::Parser::from_env();
    while let Some(arg) = parser.next()? {
        match arg {
            Short('n') | Long("number") => {
                number = parser.value()?.parse()?;
            }
            Long("shout") => {
                shout = true;
            }
            Value(val) if thing.is_none() => {
                thing = Some(val.string()?);
            }
            Long("help") => {
                println!("Usage: hello [-n|--number=NUM] [--shout] THING");
                std::process::exit(0);
            }
            _ => return Err(arg.unexpected()),
        }
    }

    Ok(Args {
        thing: thing.ok_or("missing argument THING")?,
        number,
        shout,
    })
}
examples/nonstandard.rs (line 40)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
fn main() -> Result<(), lexopt::Error> {
    use lexopt::prelude::*;

    let mut parser = lexopt::Parser::from_env();
    loop {
        if let Some(num) = parse_dashnum(&mut parser) {
            println!("Got number {}", num);
        } else if let Some(arg) = parser.next()? {
            match arg {
                Short('f') | Long("follow") => {
                    println!("Got --follow");
                }
                Short('n') | Long("number") => {
                    let num: u64 = parser.value()?.parse()?;
                    println!("Got number {}", num);
                }
                Value(path) => {
                    let path = PathBuf::from(path);
                    println!("Got file {}", path.display());
                }
                _ => return Err(arg.unexpected()),
            }
        } else {
            break;
        }
    }

    Ok(())
}
examples/pico_test_app.rs (line 68)
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
fn parse_args() -> Result<AppArgs, lexopt::Error> {
    use lexopt::prelude::*;

    let mut number = None;
    let mut opt_number = None;
    let mut width = 10;
    let mut input = None;

    let mut parser = lexopt::Parser::from_env();
    while let Some(arg) = parser.next()? {
        match arg {
            Short('h') | Long("help") => {
                print!("{}", HELP);
                std::process::exit(0);
            }
            Long("number") => number = Some(parser.value()?.parse()?),
            Long("opt-number") => opt_number = Some(parser.value()?.parse()?),
            Long("width") => width = parser.value()?.parse_with(parse_width)?,
            Value(path) if input.is_none() => input = Some(path.into()),
            _ => return Err(arg.unexpected()),
        }
    }
    Ok(AppArgs {
        number: number.ok_or("missing required option --number")?,
        opt_number,
        width,
        input: input.ok_or("missing required argument INPUT")?,
    })
}
examples/cargo.rs (line 55)
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
fn main() -> Result<(), lexopt::Error> {
    use lexopt::prelude::*;

    let mut settings = GlobalSettings {
        toolchain: "stable".to_owned(),
        color: Color::Auto,
        offline: false,
        quiet: false,
        verbose: false,
    };

    let mut parser = lexopt::Parser::from_env();
    while let Some(arg) = parser.next()? {
        match arg {
            Long("color") => {
                settings.color = parser.value()?.parse()?;
            }
            Long("offline") => {
                settings.offline = true;
            }
            Long("quiet") => {
                settings.quiet = true;
                settings.verbose = false;
            }
            Long("verbose") => {
                settings.verbose = true;
                settings.quiet = false;
            }
            Long("help") => {
                println!("{}", HELP);
                std::process::exit(0);
            }
            Value(value) => {
                let value = value.string()?;
                match value.as_str() {
                    value if value.starts_with('+') => {
                        settings.toolchain = value[1..].to_owned();
                    }
                    "install" => {
                        return install(settings, parser);
                    }
                    value => {
                        return Err(format!("unknown subcommand '{}'", value).into());
                    }
                }
            }
            _ => return Err(arg.unexpected()),
        }
    }

    println!("{}", HELP);
    Ok(())
}

#[derive(Debug)]
struct GlobalSettings {
    toolchain: String,
    color: Color,
    offline: bool,
    quiet: bool,
    verbose: bool,
}

fn install(settings: GlobalSettings, mut parser: lexopt::Parser) -> Result<(), lexopt::Error> {
    use lexopt::prelude::*;

    let mut package: Option<String> = None;
    let mut root: Option<PathBuf> = None;
    let mut jobs: u16 = get_no_of_cpus();

    while let Some(arg) = parser.next()? {
        match arg {
            Value(value) if package.is_none() => {
                package = Some(value.string()?);
            }
            Long("root") => {
                root = Some(parser.value()?.into());
            }
            Short('j') | Long("jobs") => {
                jobs = parser.value()?.parse()?;
            }
            Long("help") => {
                println!("cargo install [OPTIONS] CRATE");
                std::process::exit(0);
            }
            _ => return Err(arg.unexpected()),
        }
    }

    println!("Settings: {:#?}", settings);
    println!(
        "Installing {} into {:?} with {} jobs",
        package.ok_or("missing CRATE argument")?,
        root,
        jobs
    );

    Ok(())
}

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.