Struct ArgumentParser

Source
pub struct ArgumentParser<'parser> { /* private fields */ }
Expand description

The main argument parser class

Implementations§

Source§

impl<'parser> ArgumentParser<'parser>

Source

pub fn new() -> ArgumentParser<'parser>

Create an empty argument parser

Examples found in repository?
examples/subcommands.rs (line 30)
27fn play_command(verbose: bool, args: Vec<String>) {
28    let mut output = "".to_string();
29    {
30        let mut ap = ArgumentParser::new();
31        ap.set_description("Plays a sound");
32        ap.refer(&mut output)
33            .add_option(&["--output"], Store,
34                r#"Output sink to play to"#);
35        match ap.parse(args, &mut stdout(), &mut stderr()) {
36            Ok(()) =>  {}
37            Err(x) => {
38                std::process::exit(x);
39            }
40        }
41    }
42    println!("Verbosity: {}, Output: {}", verbose, output);
43}
44
45fn record_command(verbose: bool, args: Vec<String>) {
46    let mut input = "".to_string();
47    {
48        let mut ap = ArgumentParser::new();
49        ap.set_description("Records a sound");
50        ap.refer(&mut input)
51            .add_option(&["--input"], Store,
52                r#"Output source to record from"#);
53        match ap.parse(args, &mut stdout(), &mut stderr()) {
54            Ok(()) =>  {}
55            Err(x) => {
56                std::process::exit(x);
57            }
58        }
59    }
60    println!("Verbosity: {}, Input: {}", verbose, input);
61}
62
63fn main() {
64    let mut verbose = false;
65    let mut subcommand = Command::play;
66    let mut args = vec!();
67    {
68        let mut ap = ArgumentParser::new();
69        ap.set_description("Plays or records sound");
70        ap.refer(&mut verbose)
71            .add_option(&["-v", "--verbose"], StoreTrue,
72            "Be verbose");
73        ap.refer(&mut subcommand).required()
74            .add_argument("command", Store,
75                r#"Command to run (either "play" or "record")"#);
76        ap.refer(&mut args)
77            .add_argument("arguments", List,
78                r#"Arguments for command"#);
79        ap.stop_on_first_argument(true);
80        ap.parse_args_or_exit();
81    }
82
83    args.insert(0, format!("subcommand {:?}", subcommand));
84    match subcommand {
85        Command::play => play_command(verbose, args),
86        Command::record => record_command(verbose, args),
87    }
88}
More examples
Hide additional examples
examples/greeting.rs (line 9)
5fn main() {
6    let mut verbose = false;
7    let mut name = "World".to_string();
8    {
9        let mut ap = ArgumentParser::new();
10        ap.set_description("Greet somebody.");
11        ap.add_option(&["-V", "--version"],
12            Print(env!("CARGO_PKG_VERSION").to_string()), "Show version");
13        ap.refer(&mut verbose)
14            .add_option(&["-v", "--verbose"], StoreTrue,
15            "Be verbose");
16        ap.refer(&mut name)
17            .add_option(&["--name"], Store,
18            "Name for the greeting");
19        ap.parse_args_or_exit();
20    }
21
22    if verbose {
23        println!("name is {}", name);
24    }
25    println!("Hello {}!", name);
26}
examples/structure.rs (line 18)
12fn main() {
13    let mut options = Options {
14        verbose: false,
15        name: "World".to_string(),
16    };
17    {
18        let mut ap = ArgumentParser::new();
19        ap.set_description("Greet somebody.");
20        ap.refer(&mut options.verbose)
21            .add_option(&["-v", "--verbose"], StoreTrue,
22            "Be verbose");
23        ap.refer(&mut options.name)
24            .add_option(&["--name"], Store,
25            "Name for the greeting");
26        match ap.parse_args() {
27            Ok(()) => {}
28            Err(x) => {
29                exit(x);
30            }
31        }
32    }
33
34    if options.verbose {
35        println!("name is {}", options.name);
36    }
37    println!("Hello {}!", options.name);
38}
Source

pub fn refer<'x, T>( &'x mut self, val: &'parser mut T, ) -> Box<Ref<'parser, 'x, T>>

Borrow mutable variable for an argument

This returns Ref object which should be used configure the option

Examples found in repository?
examples/subcommands.rs (line 32)
27fn play_command(verbose: bool, args: Vec<String>) {
28    let mut output = "".to_string();
29    {
30        let mut ap = ArgumentParser::new();
31        ap.set_description("Plays a sound");
32        ap.refer(&mut output)
33            .add_option(&["--output"], Store,
34                r#"Output sink to play to"#);
35        match ap.parse(args, &mut stdout(), &mut stderr()) {
36            Ok(()) =>  {}
37            Err(x) => {
38                std::process::exit(x);
39            }
40        }
41    }
42    println!("Verbosity: {}, Output: {}", verbose, output);
43}
44
45fn record_command(verbose: bool, args: Vec<String>) {
46    let mut input = "".to_string();
47    {
48        let mut ap = ArgumentParser::new();
49        ap.set_description("Records a sound");
50        ap.refer(&mut input)
51            .add_option(&["--input"], Store,
52                r#"Output source to record from"#);
53        match ap.parse(args, &mut stdout(), &mut stderr()) {
54            Ok(()) =>  {}
55            Err(x) => {
56                std::process::exit(x);
57            }
58        }
59    }
60    println!("Verbosity: {}, Input: {}", verbose, input);
61}
62
63fn main() {
64    let mut verbose = false;
65    let mut subcommand = Command::play;
66    let mut args = vec!();
67    {
68        let mut ap = ArgumentParser::new();
69        ap.set_description("Plays or records sound");
70        ap.refer(&mut verbose)
71            .add_option(&["-v", "--verbose"], StoreTrue,
72            "Be verbose");
73        ap.refer(&mut subcommand).required()
74            .add_argument("command", Store,
75                r#"Command to run (either "play" or "record")"#);
76        ap.refer(&mut args)
77            .add_argument("arguments", List,
78                r#"Arguments for command"#);
79        ap.stop_on_first_argument(true);
80        ap.parse_args_or_exit();
81    }
82
83    args.insert(0, format!("subcommand {:?}", subcommand));
84    match subcommand {
85        Command::play => play_command(verbose, args),
86        Command::record => record_command(verbose, args),
87    }
88}
More examples
Hide additional examples
examples/greeting.rs (line 13)
5fn main() {
6    let mut verbose = false;
7    let mut name = "World".to_string();
8    {
9        let mut ap = ArgumentParser::new();
10        ap.set_description("Greet somebody.");
11        ap.add_option(&["-V", "--version"],
12            Print(env!("CARGO_PKG_VERSION").to_string()), "Show version");
13        ap.refer(&mut verbose)
14            .add_option(&["-v", "--verbose"], StoreTrue,
15            "Be verbose");
16        ap.refer(&mut name)
17            .add_option(&["--name"], Store,
18            "Name for the greeting");
19        ap.parse_args_or_exit();
20    }
21
22    if verbose {
23        println!("name is {}", name);
24    }
25    println!("Hello {}!", name);
26}
examples/structure.rs (line 20)
12fn main() {
13    let mut options = Options {
14        verbose: false,
15        name: "World".to_string(),
16    };
17    {
18        let mut ap = ArgumentParser::new();
19        ap.set_description("Greet somebody.");
20        ap.refer(&mut options.verbose)
21            .add_option(&["-v", "--verbose"], StoreTrue,
22            "Be verbose");
23        ap.refer(&mut options.name)
24            .add_option(&["--name"], Store,
25            "Name for the greeting");
26        match ap.parse_args() {
27            Ok(()) => {}
28            Err(x) => {
29                exit(x);
30            }
31        }
32    }
33
34    if options.verbose {
35        println!("name is {}", options.name);
36    }
37    println!("Hello {}!", options.name);
38}
Source

pub fn add_option<F: IFlagAction + 'parser>( &mut self, names: &[&'parser str], action: F, help: &'parser str, )

Add option to argument parser

This is only useful for options that don’t store value. For example Print(...)

Examples found in repository?
examples/greeting.rs (lines 11-12)
5fn main() {
6    let mut verbose = false;
7    let mut name = "World".to_string();
8    {
9        let mut ap = ArgumentParser::new();
10        ap.set_description("Greet somebody.");
11        ap.add_option(&["-V", "--version"],
12            Print(env!("CARGO_PKG_VERSION").to_string()), "Show version");
13        ap.refer(&mut verbose)
14            .add_option(&["-v", "--verbose"], StoreTrue,
15            "Be verbose");
16        ap.refer(&mut name)
17            .add_option(&["--name"], Store,
18            "Name for the greeting");
19        ap.parse_args_or_exit();
20    }
21
22    if verbose {
23        println!("name is {}", name);
24    }
25    println!("Hello {}!", name);
26}
Source

pub fn set_description(&mut self, descr: &'parser str)

Set description of the command

Examples found in repository?
examples/subcommands.rs (line 31)
27fn play_command(verbose: bool, args: Vec<String>) {
28    let mut output = "".to_string();
29    {
30        let mut ap = ArgumentParser::new();
31        ap.set_description("Plays a sound");
32        ap.refer(&mut output)
33            .add_option(&["--output"], Store,
34                r#"Output sink to play to"#);
35        match ap.parse(args, &mut stdout(), &mut stderr()) {
36            Ok(()) =>  {}
37            Err(x) => {
38                std::process::exit(x);
39            }
40        }
41    }
42    println!("Verbosity: {}, Output: {}", verbose, output);
43}
44
45fn record_command(verbose: bool, args: Vec<String>) {
46    let mut input = "".to_string();
47    {
48        let mut ap = ArgumentParser::new();
49        ap.set_description("Records a sound");
50        ap.refer(&mut input)
51            .add_option(&["--input"], Store,
52                r#"Output source to record from"#);
53        match ap.parse(args, &mut stdout(), &mut stderr()) {
54            Ok(()) =>  {}
55            Err(x) => {
56                std::process::exit(x);
57            }
58        }
59    }
60    println!("Verbosity: {}, Input: {}", verbose, input);
61}
62
63fn main() {
64    let mut verbose = false;
65    let mut subcommand = Command::play;
66    let mut args = vec!();
67    {
68        let mut ap = ArgumentParser::new();
69        ap.set_description("Plays or records sound");
70        ap.refer(&mut verbose)
71            .add_option(&["-v", "--verbose"], StoreTrue,
72            "Be verbose");
73        ap.refer(&mut subcommand).required()
74            .add_argument("command", Store,
75                r#"Command to run (either "play" or "record")"#);
76        ap.refer(&mut args)
77            .add_argument("arguments", List,
78                r#"Arguments for command"#);
79        ap.stop_on_first_argument(true);
80        ap.parse_args_or_exit();
81    }
82
83    args.insert(0, format!("subcommand {:?}", subcommand));
84    match subcommand {
85        Command::play => play_command(verbose, args),
86        Command::record => record_command(verbose, args),
87    }
88}
More examples
Hide additional examples
examples/greeting.rs (line 10)
5fn main() {
6    let mut verbose = false;
7    let mut name = "World".to_string();
8    {
9        let mut ap = ArgumentParser::new();
10        ap.set_description("Greet somebody.");
11        ap.add_option(&["-V", "--version"],
12            Print(env!("CARGO_PKG_VERSION").to_string()), "Show version");
13        ap.refer(&mut verbose)
14            .add_option(&["-v", "--verbose"], StoreTrue,
15            "Be verbose");
16        ap.refer(&mut name)
17            .add_option(&["--name"], Store,
18            "Name for the greeting");
19        ap.parse_args_or_exit();
20    }
21
22    if verbose {
23        println!("name is {}", name);
24    }
25    println!("Hello {}!", name);
26}
examples/structure.rs (line 19)
12fn main() {
13    let mut options = Options {
14        verbose: false,
15        name: "World".to_string(),
16    };
17    {
18        let mut ap = ArgumentParser::new();
19        ap.set_description("Greet somebody.");
20        ap.refer(&mut options.verbose)
21            .add_option(&["-v", "--verbose"], StoreTrue,
22            "Be verbose");
23        ap.refer(&mut options.name)
24            .add_option(&["--name"], Store,
25            "Name for the greeting");
26        match ap.parse_args() {
27            Ok(()) => {}
28            Err(x) => {
29                exit(x);
30            }
31        }
32    }
33
34    if options.verbose {
35        println!("name is {}", options.name);
36    }
37    println!("Hello {}!", options.name);
38}
Source

pub fn print_help(&self, name: &str, writer: &mut dyn Write) -> IoResult<()>

Print help

Usually command-line option is used for printing help, this is here for any awkward cases

Source

pub fn print_usage(&self, name: &str, writer: &mut dyn Write) -> IoResult<()>

Print usage

Usually printed into stderr on error of command-line parsing

Source

pub fn parse( &self, args: Vec<String>, stdout: &mut dyn Write, stderr: &mut dyn Write, ) -> Result<(), i32>

Parse arguments

This is most powerful method. Usually you need parse_args or parse_args_or_exit instead

Examples found in repository?
examples/subcommands.rs (line 35)
27fn play_command(verbose: bool, args: Vec<String>) {
28    let mut output = "".to_string();
29    {
30        let mut ap = ArgumentParser::new();
31        ap.set_description("Plays a sound");
32        ap.refer(&mut output)
33            .add_option(&["--output"], Store,
34                r#"Output sink to play to"#);
35        match ap.parse(args, &mut stdout(), &mut stderr()) {
36            Ok(()) =>  {}
37            Err(x) => {
38                std::process::exit(x);
39            }
40        }
41    }
42    println!("Verbosity: {}, Output: {}", verbose, output);
43}
44
45fn record_command(verbose: bool, args: Vec<String>) {
46    let mut input = "".to_string();
47    {
48        let mut ap = ArgumentParser::new();
49        ap.set_description("Records a sound");
50        ap.refer(&mut input)
51            .add_option(&["--input"], Store,
52                r#"Output source to record from"#);
53        match ap.parse(args, &mut stdout(), &mut stderr()) {
54            Ok(()) =>  {}
55            Err(x) => {
56                std::process::exit(x);
57            }
58        }
59    }
60    println!("Verbosity: {}, Input: {}", verbose, input);
61}
Source

pub fn error(&self, command: &str, message: &str, writer: &mut dyn Write)

Write an error similar to one produced by the library itself

Only needed if you like to do some argument validation that is out of scope of the argparse

Source

pub fn stop_on_first_argument(&mut self, want_stop: bool)

Configure parser to ignore options when first non-option argument is encountered.

Useful for commands that want to pass following options to the subcommand or subprocess, but need some options to be set before command is specified.

Examples found in repository?
examples/subcommands.rs (line 79)
63fn main() {
64    let mut verbose = false;
65    let mut subcommand = Command::play;
66    let mut args = vec!();
67    {
68        let mut ap = ArgumentParser::new();
69        ap.set_description("Plays or records sound");
70        ap.refer(&mut verbose)
71            .add_option(&["-v", "--verbose"], StoreTrue,
72            "Be verbose");
73        ap.refer(&mut subcommand).required()
74            .add_argument("command", Store,
75                r#"Command to run (either "play" or "record")"#);
76        ap.refer(&mut args)
77            .add_argument("arguments", List,
78                r#"Arguments for command"#);
79        ap.stop_on_first_argument(true);
80        ap.parse_args_or_exit();
81    }
82
83    args.insert(0, format!("subcommand {:?}", subcommand));
84    match subcommand {
85        Command::play => play_command(verbose, args),
86        Command::record => record_command(verbose, args),
87    }
88}
Source

pub fn silence_double_dash(&mut self, silence: bool)

Do not put double-dash (bare --) into argument

The double-dash is used to stop parsing options and treat all the following tokens as the arguments regardless of whether they start with dash (minus) or not.

The method only useful for List arguments. On by default. The method allows to set option to false so that cmd xx -- yy will get xx -- yy as arguments instead of xx yy by default. This is useful if your -- argument is meaningful. Only first double-dash is ignored by default.

Source

pub fn parse_args(&self) -> Result<(), i32>

Convenience method to parse arguments

On error returns error code that is supposed to be returned by an application. (i.e. zero on --help and 2 on argument error)

Examples found in repository?
examples/structure.rs (line 26)
12fn main() {
13    let mut options = Options {
14        verbose: false,
15        name: "World".to_string(),
16    };
17    {
18        let mut ap = ArgumentParser::new();
19        ap.set_description("Greet somebody.");
20        ap.refer(&mut options.verbose)
21            .add_option(&["-v", "--verbose"], StoreTrue,
22            "Be verbose");
23        ap.refer(&mut options.name)
24            .add_option(&["--name"], Store,
25            "Name for the greeting");
26        match ap.parse_args() {
27            Ok(()) => {}
28            Err(x) => {
29                exit(x);
30            }
31        }
32    }
33
34    if options.verbose {
35        println!("name is {}", options.name);
36    }
37    println!("Hello {}!", options.name);
38}
Source

pub fn parse_args_or_exit(&self)

The simplest conveninece method

The method returns only in case of successful parsing or exits with appropriate code (including successful on --help) otherwise.

Examples found in repository?
examples/greeting.rs (line 19)
5fn main() {
6    let mut verbose = false;
7    let mut name = "World".to_string();
8    {
9        let mut ap = ArgumentParser::new();
10        ap.set_description("Greet somebody.");
11        ap.add_option(&["-V", "--version"],
12            Print(env!("CARGO_PKG_VERSION").to_string()), "Show version");
13        ap.refer(&mut verbose)
14            .add_option(&["-v", "--verbose"], StoreTrue,
15            "Be verbose");
16        ap.refer(&mut name)
17            .add_option(&["--name"], Store,
18            "Name for the greeting");
19        ap.parse_args_or_exit();
20    }
21
22    if verbose {
23        println!("name is {}", name);
24    }
25    println!("Hello {}!", name);
26}
More examples
Hide additional examples
examples/subcommands.rs (line 80)
63fn main() {
64    let mut verbose = false;
65    let mut subcommand = Command::play;
66    let mut args = vec!();
67    {
68        let mut ap = ArgumentParser::new();
69        ap.set_description("Plays or records sound");
70        ap.refer(&mut verbose)
71            .add_option(&["-v", "--verbose"], StoreTrue,
72            "Be verbose");
73        ap.refer(&mut subcommand).required()
74            .add_argument("command", Store,
75                r#"Command to run (either "play" or "record")"#);
76        ap.refer(&mut args)
77            .add_argument("arguments", List,
78                r#"Arguments for command"#);
79        ap.stop_on_first_argument(true);
80        ap.parse_args_or_exit();
81    }
82
83    args.insert(0, format!("subcommand {:?}", subcommand));
84    match subcommand {
85        Command::play => play_command(verbose, args),
86        Command::record => record_command(verbose, args),
87    }
88}

Auto Trait Implementations§

§

impl<'parser> Freeze for ArgumentParser<'parser>

§

impl<'parser> !RefUnwindSafe for ArgumentParser<'parser>

§

impl<'parser> !Send for ArgumentParser<'parser>

§

impl<'parser> !Sync for ArgumentParser<'parser>

§

impl<'parser> Unpin for ArgumentParser<'parser>

§

impl<'parser> !UnwindSafe for ArgumentParser<'parser>

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.

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

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.