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

The base command line parser.

Example

use blarg::{CommandLineParser};

let parser = CommandLineParser::new("program")
    // Configure with CommandLineParser::add and CommandLineParser::branch.
    .build();
parser.parse_tokens(empty::slice()).unwrap();

Implementations§

source§

impl<'a> CommandLineParser<'a>

source

pub fn new(program: impl Into<String>) -> CommandLineParser<'a>

Create a command line parser.

Example
use blarg::CommandLineParser;

let parser = CommandLineParser::new("program")
    .build();

parser.parse_tokens(vec![].as_slice()).unwrap();
Examples found in repository?
examples/empty.rs (line 4)
3
4
5
6
7
8
fn main() {
    let ap = CommandLineParser::new("empty");
    let parser = ap.build();
    parser.parse();
    println!("empty parser");
}
More examples
Hide additional examples
examples/demo_summer_b.rs (line 6)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
    let mut items: Vec<u32> = Vec::default();

    let clp = CommandLineParser::new("summer");
    let parser = clp
        .add(
            Parameter::argument(Collection::new(&mut items, Nargs::AtLeastOne), "item")
                .help("The items to sum."),
        )
        .build();

    parser.parse();
    let sum: u32 = items.iter().sum();
    println!("Sum: {sum}");
}
examples/example.rs (line 5)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fn main() {
    let mut verbose: bool = false;
    let mut value: u32 = 0;
    let ap = CommandLineParser::new("example");
    let parser = ap
        .add(Parameter::option(
            Switch::new(&mut verbose, true),
            "verbose",
            Some('v'),
        ))
        .add(Parameter::argument(Scalar::new(&mut value), "value").meta(vec!["type: u32"]))
        .build();
    parser.parse();
    println!("value: {value}, verbose: {verbose}");
}
examples/demo_organization.rs (line 33)
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
fn parse_tokens(parse_fn: impl FnOnce(GeneralParser) -> Result<(), i32>) -> Params {
    let mut params = Params::init();

    let clp = CommandLineParser::new("organization");
    let parser = clp
        .add(Parameter::option(
            Switch::new(&mut params.verbose, true),
            "verbose",
            Some('v'),
        ))
        .add(Parameter::argument(
            Collection::new(&mut params.items, Nargs::AtLeastOne),
            "item",
        ))
        .build();

    // The parse_fn signature is a `Result`.
    // However, since `GeneralParser::parse` does not return an error (it uses `std::process::exit` under the hood), the `Err` case is only reached via test.
    parse_fn(parser).expect("test-reachable-only");
    params
}
examples/reducer.rs (line 60)
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
fn main() {
    let mut _verbose: bool = false;
    let mut operand: Operand = Operand::Add;
    let mut initial: Option<u32> = None;
    let mut _countries: HashSet<Country> = HashSet::default();
    let mut items: Vec<u32> = Vec::default();

    let ap = CommandLineParser::new("reducer");
    let parser = ap
        .add(
            Parameter::option(Switch::new(&mut _verbose, true), "verbose", Some('v'))
                .help("Do dee doo.  We're really stretching here HAAAAAAAA HAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"),
        )
        .add(
            Parameter::option(Scalar::new(&mut operand), "operand", Some('o'))
                .help("moot")
                .choice(Operand::Add, "+")
                .choice(Operand::Multiply, "*"),
        )
        .add(Parameter::option(Optional::new(&mut initial), "initial", None)
            .meta(vec!["testing a really long meta.. abcdefghijklmnopqrstuvwxyz"])
        )
        .add(Parameter::option(Collection::new(&mut _countries, Nargs::AtLeastOne), "country", None))
        .add(
            Parameter::argument(Collection::new(&mut items, Nargs::AtLeastOne), "item")
                .help("The items."),
        )
        .build();
    parser.parse();
    println!("Items: {items:?}");
    execute(_verbose, operand, initial, _countries, items);
}
examples/foo_bar.rs (line 61)
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
fn main() {
    let mut verbose: bool = false;
    let mut foo_bar = FooBar::Foo;
    let mut initial: Option<u32> = None;
    let mut countries: HashSet<Country> = HashSet::default();
    let mut items: Vec<u32> = Vec::default();

    let ap = CommandLineParser::new("foo_bar");
    let parser = ap
        .add(
            Parameter::option(Switch::new(&mut verbose, true), "verbose", Some('v'))
                .help("Do dee doo."),
        )
        .branch(
            Condition::new(Scalar::new(&mut foo_bar), "foo_bar")
                .choice(FooBar::Foo, "123 abc let's make this one medium long.")
                .choice(FooBar::Bar, "456 def let's make this one multiple sentences.  We're really stretching here HAAAAAAAA HAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!")
                .help("foo'y bar'y stuff")
                .meta(vec!["a", "b", "c"]),
        )
        .command(FooBar::Foo, |sub| {
            sub.add(Parameter::option(
                Optional::new(&mut initial),
                "initial",
                None,
            ))
            .add(
                Parameter::argument(Collection::new(&mut items, Nargs::Any), "item")
                    .help("The items."),
            )
        })
        .command(FooBar::Bar, |sub| {
            sub.add(Parameter::option(
                Collection::new(&mut countries, Nargs::AtLeastOne),
                "country",
                None,
            ))
        })
        .build();
    parser.parse();
    println!("Items: {items:?}");
    execute(verbose, foo_bar, initial, countries, items);
}
source

pub fn about(self, description: impl Into<String>) -> CommandLineParser<'a>

Document the about message for this command line parser. If repeated, only the final help message will apply.

An about message documents the command line parser in full sentence/paragraph format. We recommend allowing blarg to format this field (ex: it is not recommended to use line breaks '\n').

Example
use blarg::CommandLineParser;

let parser = CommandLineParser::new("program")
    .about("--this will get discarded--")
    .about("My program that does awesome stuff.  Check it out!")
    .build();

parser.parse_tokens(vec![].as_slice()).unwrap();
Examples found in repository?
examples/demo_sub_command.rs (line 11)
3
4
5
6
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
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
fn main() {
    let mut sub: u32 = 0;
    let mut arg_0: bool = false;
    let mut opt_0: bool = false;
    let mut arg_1: bool = false;

    let clp = CommandLineParser::new("sub-command");
    let parser = clp
        .about("Describe the base command line parser.  Let's make it a little long for fun.")
        .branch(
            Condition::new(Scalar::new(&mut sub), "sub")
                // "0" is an undocumented sub-command.
                // "1" is a regular sub-command.
                .choice(1, "the one sub-command")
                // "2" is a regular sub-command.
                .choice(2, "the two sub-command")
                // "3" is a false sub-command.
                // It will appear in the documentation, but only those specified via `command(..)` actually affect the program structure.
                .choice(3, "the three sub-command"),
        )
        .command(0, |sub_command| {
            sub_command
                .about("Describe the 0 sub-command parser.  Let's make it a little long for fun.")
                .add(Parameter::argument(Scalar::new(&mut arg_0), "arg"))
                .add(Parameter::option(
                    Switch::new(&mut opt_0, true),
                    "opt",
                    None,
                ))
        })
        .command(1, |sub_command| {
            sub_command
                .about("Describe the 1 sub-command parser.")
                .add(Parameter::argument(Scalar::new(&mut arg_1), "arg"))
        })
        // Specify an argument-less & option-less sub-command by leaving the 'sub' untouched.
        .command(2, |sub_command| sub_command)
        // Since we never add "3", it isn't a true sub-command.
        .build();

    parser.parse();

    println!("Used sub-command '{sub}'.");
    match sub {
        0 => {
            println!("arg_0: {arg_0}");
            println!("opt_0: {opt_0}");
            assert!(!arg_1);
        }
        1 => {
            assert!(!arg_0);
            assert!(!opt_0);
            println!("arg_1: {arg_1}");
        }
        2 => {
            assert!(!arg_0);
            assert!(!opt_0);
            assert!(!arg_1);
            println!("argument-less & option-less");
        }
        _ => {
            panic!(
                "impossible - the parser will reject any variants not specified via `command(..)`."
            )
        }
    }
}
source

pub fn add<T>(self, parameter: Parameter<'a, T>) -> CommandLineParser<'a>

Add an argument/option to the command line parser.

The order of argument parameters corresponds to their positional order during parsing. The order of option parameters does not affect the command parser semantics.

Example
use blarg::{CommandLineParser, Parameter, Scalar};

let mut a: u32 = 0;
let mut b: u32 = 0;
let parser = CommandLineParser::new("program")
    .add(Parameter::argument(Scalar::new(&mut a), "a"))
    .add(Parameter::argument(Scalar::new(&mut b), "b"))
    .build();

parser.parse_tokens(vec!["1", "2"].as_slice()).unwrap();

assert_eq!(a, 1);
assert_eq!(b, 2);
Examples found in repository?
examples/demo_summer_b.rs (lines 8-11)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
    let mut items: Vec<u32> = Vec::default();

    let clp = CommandLineParser::new("summer");
    let parser = clp
        .add(
            Parameter::argument(Collection::new(&mut items, Nargs::AtLeastOne), "item")
                .help("The items to sum."),
        )
        .build();

    parser.parse();
    let sum: u32 = items.iter().sum();
    println!("Sum: {sum}");
}
More examples
Hide additional examples
examples/example.rs (lines 7-11)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fn main() {
    let mut verbose: bool = false;
    let mut value: u32 = 0;
    let ap = CommandLineParser::new("example");
    let parser = ap
        .add(Parameter::option(
            Switch::new(&mut verbose, true),
            "verbose",
            Some('v'),
        ))
        .add(Parameter::argument(Scalar::new(&mut value), "value").meta(vec!["type: u32"]))
        .build();
    parser.parse();
    println!("value: {value}, verbose: {verbose}");
}
examples/demo_organization.rs (lines 35-39)
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
fn parse_tokens(parse_fn: impl FnOnce(GeneralParser) -> Result<(), i32>) -> Params {
    let mut params = Params::init();

    let clp = CommandLineParser::new("organization");
    let parser = clp
        .add(Parameter::option(
            Switch::new(&mut params.verbose, true),
            "verbose",
            Some('v'),
        ))
        .add(Parameter::argument(
            Collection::new(&mut params.items, Nargs::AtLeastOne),
            "item",
        ))
        .build();

    // The parse_fn signature is a `Result`.
    // However, since `GeneralParser::parse` does not return an error (it uses `std::process::exit` under the hood), the `Err` case is only reached via test.
    parse_fn(parser).expect("test-reachable-only");
    params
}
examples/reducer.rs (lines 62-65)
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
fn main() {
    let mut _verbose: bool = false;
    let mut operand: Operand = Operand::Add;
    let mut initial: Option<u32> = None;
    let mut _countries: HashSet<Country> = HashSet::default();
    let mut items: Vec<u32> = Vec::default();

    let ap = CommandLineParser::new("reducer");
    let parser = ap
        .add(
            Parameter::option(Switch::new(&mut _verbose, true), "verbose", Some('v'))
                .help("Do dee doo.  We're really stretching here HAAAAAAAA HAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"),
        )
        .add(
            Parameter::option(Scalar::new(&mut operand), "operand", Some('o'))
                .help("moot")
                .choice(Operand::Add, "+")
                .choice(Operand::Multiply, "*"),
        )
        .add(Parameter::option(Optional::new(&mut initial), "initial", None)
            .meta(vec!["testing a really long meta.. abcdefghijklmnopqrstuvwxyz"])
        )
        .add(Parameter::option(Collection::new(&mut _countries, Nargs::AtLeastOne), "country", None))
        .add(
            Parameter::argument(Collection::new(&mut items, Nargs::AtLeastOne), "item")
                .help("The items."),
        )
        .build();
    parser.parse();
    println!("Items: {items:?}");
    execute(_verbose, operand, initial, _countries, items);
}
examples/foo_bar.rs (lines 63-66)
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
fn main() {
    let mut verbose: bool = false;
    let mut foo_bar = FooBar::Foo;
    let mut initial: Option<u32> = None;
    let mut countries: HashSet<Country> = HashSet::default();
    let mut items: Vec<u32> = Vec::default();

    let ap = CommandLineParser::new("foo_bar");
    let parser = ap
        .add(
            Parameter::option(Switch::new(&mut verbose, true), "verbose", Some('v'))
                .help("Do dee doo."),
        )
        .branch(
            Condition::new(Scalar::new(&mut foo_bar), "foo_bar")
                .choice(FooBar::Foo, "123 abc let's make this one medium long.")
                .choice(FooBar::Bar, "456 def let's make this one multiple sentences.  We're really stretching here HAAAAAAAA HAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!")
                .help("foo'y bar'y stuff")
                .meta(vec!["a", "b", "c"]),
        )
        .command(FooBar::Foo, |sub| {
            sub.add(Parameter::option(
                Optional::new(&mut initial),
                "initial",
                None,
            ))
            .add(
                Parameter::argument(Collection::new(&mut items, Nargs::Any), "item")
                    .help("The items."),
            )
        })
        .command(FooBar::Bar, |sub| {
            sub.add(Parameter::option(
                Collection::new(&mut countries, Nargs::AtLeastOne),
                "country",
                None,
            ))
        })
        .build();
    parser.parse();
    println!("Items: {items:?}");
    execute(verbose, foo_bar, initial, countries, items);
}
source

pub fn branch<T>(self, condition: Condition<'a, T>) -> SubCommandParser<'a, T>
where T: FromStr + Display + PartialEq,

Branch into a sub-command parser.

This changes the command line parser into a sub-command style command line parser. Any parameters added before the branch apply to the root parser.

Branching is always done with a special Scalar argument: Condition.

Example
use blarg::{CommandLineParser, Parameter, Scalar, Condition};

let mut belongs_to_root: u32 = 0;
let mut sub_command: String = "".to_string();
let mut belongs_to_sub_command: u32 = 0;
let parser = CommandLineParser::new("program")
    .add(Parameter::argument(Scalar::new(&mut belongs_to_root), "belongs_to_root"))
    .branch(Condition::new(Scalar::new(&mut sub_command), "sub_command"))
    .command("the-command".to_string(), |sub| {
        sub.add(Parameter::argument(Scalar::new(&mut belongs_to_sub_command), "belongs_to_sub_command"))
    })
    .build();

parser.parse_tokens(vec!["1", "the-command", "2"].as_slice()).unwrap();

assert_eq!(belongs_to_root, 1);
assert_eq!(&sub_command, "the-command");
assert_eq!(belongs_to_sub_command, 2);
Examples found in repository?
examples/foo_bar.rs (lines 67-73)
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
fn main() {
    let mut verbose: bool = false;
    let mut foo_bar = FooBar::Foo;
    let mut initial: Option<u32> = None;
    let mut countries: HashSet<Country> = HashSet::default();
    let mut items: Vec<u32> = Vec::default();

    let ap = CommandLineParser::new("foo_bar");
    let parser = ap
        .add(
            Parameter::option(Switch::new(&mut verbose, true), "verbose", Some('v'))
                .help("Do dee doo."),
        )
        .branch(
            Condition::new(Scalar::new(&mut foo_bar), "foo_bar")
                .choice(FooBar::Foo, "123 abc let's make this one medium long.")
                .choice(FooBar::Bar, "456 def let's make this one multiple sentences.  We're really stretching here HAAAAAAAA HAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!")
                .help("foo'y bar'y stuff")
                .meta(vec!["a", "b", "c"]),
        )
        .command(FooBar::Foo, |sub| {
            sub.add(Parameter::option(
                Optional::new(&mut initial),
                "initial",
                None,
            ))
            .add(
                Parameter::argument(Collection::new(&mut items, Nargs::Any), "item")
                    .help("The items."),
            )
        })
        .command(FooBar::Bar, |sub| {
            sub.add(Parameter::option(
                Collection::new(&mut countries, Nargs::AtLeastOne),
                "country",
                None,
            ))
        })
        .build();
    parser.parse();
    println!("Items: {items:?}");
    execute(verbose, foo_bar, initial, countries, items);
}
More examples
Hide additional examples
examples/dynamic_sub_command.rs (line 24)
4
5
6
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
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
fn main() {
    let contains_dynamic_x = env::var("DYNAMIC_X").is_ok();
    let contains_dynamic_y = env::var("DYNAMIC_Y").is_ok();

    let mut sub: u32 = 0;
    let mut arg_0: bool = false;
    let mut arg_1: bool = false;
    let mut arg_2: bool = false;

    let mut condition = Condition::new(Scalar::new(&mut sub), "sub")
        // "0" is an undocumented sub-command, but will only available when environment contains `DYNAMIC_X`.
        // "1" is a regular sub-command.
        .choice(1, "the one sub-command");

    if contains_dynamic_y {
        // "2" is a sub-command that will only be available when the environment contains `DYNAMIC_Y`.
        condition = condition.choice(2, "the two sub-command");
    }

    let clp = CommandLineParser::new("sub-command");
    let mut clp = clp.branch(condition).command(1, |sub_command| {
        sub_command.add(Parameter::argument(Scalar::new(&mut arg_1), "arg"))
    });

    if contains_dynamic_x {
        clp = clp.command(0, |sub_command| {
            sub_command.add(Parameter::argument(Scalar::new(&mut arg_0), "arg"))
        });
    }

    if contains_dynamic_y {
        clp = clp.command(2, |sub_command| {
            sub_command.add(Parameter::argument(Scalar::new(&mut arg_2), "arg"))
        });
    }

    let parser = clp.build();

    parser.parse();

    println!("Used sub-command '{sub}'.");
    match sub {
        0 => {
            println!("arg_0: {arg_0}");
            assert!(!arg_1);
            assert!(!arg_2);
        }
        1 => {
            assert!(!arg_0);
            println!("arg_1: {arg_1}");
            assert!(!arg_2);
        }
        2 => {
            assert!(!arg_0);
            assert!(!arg_1);
            println!("arg_2: {arg_2}");
        }
        _ => {
            panic!("impossible - the parser will reject any variants not specified via `add(..)`.")
        }
    }
}
examples/demo_sub_command.rs (lines 12-22)
3
4
5
6
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
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
fn main() {
    let mut sub: u32 = 0;
    let mut arg_0: bool = false;
    let mut opt_0: bool = false;
    let mut arg_1: bool = false;

    let clp = CommandLineParser::new("sub-command");
    let parser = clp
        .about("Describe the base command line parser.  Let's make it a little long for fun.")
        .branch(
            Condition::new(Scalar::new(&mut sub), "sub")
                // "0" is an undocumented sub-command.
                // "1" is a regular sub-command.
                .choice(1, "the one sub-command")
                // "2" is a regular sub-command.
                .choice(2, "the two sub-command")
                // "3" is a false sub-command.
                // It will appear in the documentation, but only those specified via `command(..)` actually affect the program structure.
                .choice(3, "the three sub-command"),
        )
        .command(0, |sub_command| {
            sub_command
                .about("Describe the 0 sub-command parser.  Let's make it a little long for fun.")
                .add(Parameter::argument(Scalar::new(&mut arg_0), "arg"))
                .add(Parameter::option(
                    Switch::new(&mut opt_0, true),
                    "opt",
                    None,
                ))
        })
        .command(1, |sub_command| {
            sub_command
                .about("Describe the 1 sub-command parser.")
                .add(Parameter::argument(Scalar::new(&mut arg_1), "arg"))
        })
        // Specify an argument-less & option-less sub-command by leaving the 'sub' untouched.
        .command(2, |sub_command| sub_command)
        // Since we never add "3", it isn't a true sub-command.
        .build();

    parser.parse();

    println!("Used sub-command '{sub}'.");
    match sub {
        0 => {
            println!("arg_0: {arg_0}");
            println!("opt_0: {opt_0}");
            assert!(!arg_1);
        }
        1 => {
            assert!(!arg_0);
            assert!(!opt_0);
            println!("arg_1: {arg_1}");
        }
        2 => {
            assert!(!arg_0);
            assert!(!opt_0);
            assert!(!arg_1);
            println!("argument-less & option-less");
        }
        _ => {
            panic!(
                "impossible - the parser will reject any variants not specified via `command(..)`."
            )
        }
    }
}
source

pub fn build_parser(self) -> Result<GeneralParser<'a>, ConfigError>

Build the command line parser as a Result. This finalizes the configuration and checks for errors (ex: a repeated parameter name).

source

pub fn build(self) -> GeneralParser<'a>

Build the command line parser. This finalizes the configuration and checks for errors (ex: a repeated parameter name). If an error is encountered, exits with error code 1 (via std::process::exit).

Examples found in repository?
examples/empty.rs (line 5)
3
4
5
6
7
8
fn main() {
    let ap = CommandLineParser::new("empty");
    let parser = ap.build();
    parser.parse();
    println!("empty parser");
}
More examples
Hide additional examples
examples/demo_summer_b.rs (line 12)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
    let mut items: Vec<u32> = Vec::default();

    let clp = CommandLineParser::new("summer");
    let parser = clp
        .add(
            Parameter::argument(Collection::new(&mut items, Nargs::AtLeastOne), "item")
                .help("The items to sum."),
        )
        .build();

    parser.parse();
    let sum: u32 = items.iter().sum();
    println!("Sum: {sum}");
}
examples/example.rs (line 13)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fn main() {
    let mut verbose: bool = false;
    let mut value: u32 = 0;
    let ap = CommandLineParser::new("example");
    let parser = ap
        .add(Parameter::option(
            Switch::new(&mut verbose, true),
            "verbose",
            Some('v'),
        ))
        .add(Parameter::argument(Scalar::new(&mut value), "value").meta(vec!["type: u32"]))
        .build();
    parser.parse();
    println!("value: {value}, verbose: {verbose}");
}
examples/demo_organization.rs (line 44)
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
fn parse_tokens(parse_fn: impl FnOnce(GeneralParser) -> Result<(), i32>) -> Params {
    let mut params = Params::init();

    let clp = CommandLineParser::new("organization");
    let parser = clp
        .add(Parameter::option(
            Switch::new(&mut params.verbose, true),
            "verbose",
            Some('v'),
        ))
        .add(Parameter::argument(
            Collection::new(&mut params.items, Nargs::AtLeastOne),
            "item",
        ))
        .build();

    // The parse_fn signature is a `Result`.
    // However, since `GeneralParser::parse` does not return an error (it uses `std::process::exit` under the hood), the `Err` case is only reached via test.
    parse_fn(parser).expect("test-reachable-only");
    params
}
examples/reducer.rs (line 80)
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
fn main() {
    let mut _verbose: bool = false;
    let mut operand: Operand = Operand::Add;
    let mut initial: Option<u32> = None;
    let mut _countries: HashSet<Country> = HashSet::default();
    let mut items: Vec<u32> = Vec::default();

    let ap = CommandLineParser::new("reducer");
    let parser = ap
        .add(
            Parameter::option(Switch::new(&mut _verbose, true), "verbose", Some('v'))
                .help("Do dee doo.  We're really stretching here HAAAAAAAA HAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"),
        )
        .add(
            Parameter::option(Scalar::new(&mut operand), "operand", Some('o'))
                .help("moot")
                .choice(Operand::Add, "+")
                .choice(Operand::Multiply, "*"),
        )
        .add(Parameter::option(Optional::new(&mut initial), "initial", None)
            .meta(vec!["testing a really long meta.. abcdefghijklmnopqrstuvwxyz"])
        )
        .add(Parameter::option(Collection::new(&mut _countries, Nargs::AtLeastOne), "country", None))
        .add(
            Parameter::argument(Collection::new(&mut items, Nargs::AtLeastOne), "item")
                .help("The items."),
        )
        .build();
    parser.parse();
    println!("Items: {items:?}");
    execute(_verbose, operand, initial, _countries, items);
}

Auto Trait Implementations§

§

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

§

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

§

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

§

impl<'a> Unpin for CommandLineParser<'a>

§

impl<'a> !UnwindSafe for CommandLineParser<'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> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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, U> TryFrom<U> for T
where U: Into<T>,

§

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

§

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.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more