Skip to main content

Parser

Trait Parser 

Source
pub trait Parser:
    Sized
    + FromArgMatches
    + CommandFactory {
    // Provided methods
    fn parse() -> Self { ... }
    fn try_parse() -> Result<Self, Error> { ... }
    fn parse_from<I, T>(itr: I) -> Self
       where I: IntoIterator<Item = T>,
             T: Into<OsString> + Clone { ... }
    fn try_parse_from<I, T>(itr: I) -> Result<Self, Error>
       where I: IntoIterator<Item = T>,
             T: Into<OsString> + Clone { ... }
    fn update_from<I, T>(&mut self, itr: I)
       where I: IntoIterator<Item = T>,
             T: Into<OsString> + Clone { ... }
    fn try_update_from<I, T>(&mut self, itr: I) -> Result<(), Error>
       where I: IntoIterator<Item = T>,
             T: Into<OsString> + Clone { ... }
}
Expand description

Parse command-line arguments into Self.

The primary one-stop-shop trait used to create an instance of a clap Command, conduct the parsing, and turn the resulting ArgMatches back into concrete instance of the user struct.

This trait is primarily a convenience on top of FromArgMatches + CommandFactory which uses those two underlying traits to build the two fundamental functions parse which uses the std::env::args_os iterator, and parse_from which allows the consumer to supply the iterator (along with fallible options for each).

See also Subcommand and Args.

NOTE: Deriving requires the derive feature flag

Provided Methods§

Source

fn parse() -> Self

Parse from std::env::args_os(), exit on error.

Examples found in repository?
examples/typed-derive/main.rs (line 20)
19fn main() {
20    let cli = Cli::parse();
21    println!("{cli:?}");
22}
More examples
Hide additional examples
examples/derive_ref/flatten_hand_args.rs (line 89)
88fn main() {
89    let args = Cli::parse();
90    println!("{args:#?}");
91}
examples/derive_ref/hand_subcommand.rs (line 78)
77fn main() {
78    let args = Cli::parse();
79    println!("{args:#?}");
80}
examples/tutorial_derive/04_02_parse.rs (line 12)
11fn main() {
12    let cli = Cli::parse();
13
14    println!("PORT = {}", cli.port);
15}
examples/tutorial_derive/04_02_validate.rs (line 14)
13fn main() {
14    let cli = Cli::parse();
15
16    println!("PORT = {}", cli.port);
17}
examples/tutorial_derive/05_01_assert.rs (line 11)
10fn main() {
11    let cli = Cli::parse();
12
13    println!("PORT = {}", cli.port);
14}
Source

fn try_parse() -> Result<Self, Error>

Parse from std::env::args_os(), return Err on error.

Examples found in repository?
examples/git-derive.rs (line 110)
109fn parse_aliases() -> Result<Cli, clap::Error> {
110    let args = Cli::try_parse()?;
111    expand_aliases(args, Vec::new())
112}
Source

fn parse_from<I, T>(itr: I) -> Self
where I: IntoIterator<Item = T>, T: Into<OsString> + Clone,

Parse from iterator, exit on error.

Source

fn try_parse_from<I, T>(itr: I) -> Result<Self, Error>
where I: IntoIterator<Item = T>, T: Into<OsString> + Clone,

Parse from iterator, return Err on error.

Examples found in repository?
examples/repl-derive.rs (line 31)
29fn respond(line: &str) -> Result<bool, String> {
30    let args = shlex::split(line).ok_or("error: Invalid quoting")?;
31    let cli = Cli::try_parse_from(args).map_err(|e| e.to_string())?;
32    match cli.command {
33        Commands::Ping => {
34            write!(std::io::stdout(), "Pong").map_err(|e| e.to_string())?;
35            std::io::stdout().flush().map_err(|e| e.to_string())?;
36        }
37        Commands::Exit => {
38            write!(std::io::stdout(), "Exiting ...").map_err(|e| e.to_string())?;
39            std::io::stdout().flush().map_err(|e| e.to_string())?;
40            return Ok(true);
41        }
42    }
43    Ok(false)
44}
More examples
Hide additional examples
examples/git-derive.rs (line 137)
114fn expand_aliases(args: Cli, mut expanded: Vec<String>) -> Result<Cli, clap::Error> {
115    let Commands::External(external_args) = &args.command else {
116        return Ok(args);
117    };
118    let Some(name) = external_args.first().and_then(|name| name.to_str()) else {
119        return Ok(args);
120    };
121
122    let aliases = aliases();
123    let Some(alias) = aliases.get(name) else {
124        return Ok(args);
125    };
126    if expanded.iter().any(|expanded| expanded == name) {
127        return Err(clap::Error::raw(
128            clap::error::ErrorKind::InvalidSubcommand,
129            format!("recursive alias `{}`", expanded[0]),
130        ));
131    }
132    expanded.push(name.to_owned());
133
134    let mut alias_args = vec![OsString::from("git")];
135    alias_args.extend(alias.iter().map(OsString::from));
136    alias_args.extend(external_args.iter().skip(1).cloned());
137    let args = Cli::try_parse_from(alias_args)?;
138
139    expand_aliases(args, expanded)
140}
Source

fn update_from<I, T>(&mut self, itr: I)
where I: IntoIterator<Item = T>, T: Into<OsString> + Clone,

Update from iterator, exit on error.

Unlike Parser::parse, this works with an existing instance of self. The assumption is that all required fields are already provided and any Args or Subcommands provided by the user will modify only what is specified.

Source

fn try_update_from<I, T>(&mut self, itr: I) -> Result<(), Error>
where I: IntoIterator<Item = T>, T: Into<OsString> + Clone,

Update from iterator, return Err on error.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<T> Parser for Box<T>
where T: Parser,

Source§

fn parse() -> Box<T>

Source§

fn try_parse() -> Result<Box<T>, Error>

Source§

fn parse_from<I, It>(itr: I) -> Box<T>
where I: IntoIterator<Item = It>, It: Into<OsString> + Clone,

Source§

fn try_parse_from<I, It>(itr: I) -> Result<Box<T>, Error>
where I: IntoIterator<Item = It>, It: Into<OsString> + Clone,

Implementors§