Trait clap::Parser

source ·
pub trait Parser: FromArgMatches + CommandFactory + Sized {
    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.

See the derive reference for attributes and best practices.

NOTE: Deriving requires the derive feature flag

Examples

The following example creates a Context struct that would be used throughout the application representing the normalized values coming from the CLI.

/// My super CLI
#[derive(clap::Parser)]
#[command(name = "demo")]
struct Context {
   /// More verbose output
   #[arg(long)]
   verbose: bool,
   /// An optional name
   #[arg(short, long)]
   name: Option<String>,
}

The equivalent Command struct + From implementation:

Command::new("demo")
    .about("My super CLI")
    .arg(Arg::new("verbose")
        .long("verbose")
        .action(ArgAction::SetTrue)
        .help("More verbose output"))
    .arg(Arg::new("name")
        .long("name")
        .short('n')
        .help("An optional name")
        .action(ArgAction::Set));

struct Context {
    verbose: bool,
    name: Option<String>,
}

impl From<ArgMatches> for Context {
    fn from(m: ArgMatches) -> Self {
        Context {
            verbose: *m.get_one::<bool>("verbose").expect("defaulted_by_clap"),
            name: m.get_one::<String>("name").cloned(),
        }
    }
}

Provided Methods§

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

Examples found in repository?
src/derive.rs (line 399)
398
399
400
    fn parse() -> Self {
        Box::new(<T as Parser>::parse())
    }

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

Examples found in repository?
src/derive.rs (line 403)
402
403
404
    fn try_parse() -> Result<Self, Error> {
        <T as Parser>::try_parse().map(Box::new)
    }

Parse from iterator, exit on error

Examples found in repository?
src/derive.rs (line 411)
406
407
408
409
410
411
412
    fn parse_from<I, It>(itr: I) -> Self
    where
        I: IntoIterator<Item = It>,
        It: Into<OsString> + Clone,
    {
        Box::new(<T as Parser>::parse_from(itr))
    }

Parse from iterator, return Err on error.

Examples found in repository?
src/derive.rs (line 419)
414
415
416
417
418
419
420
    fn try_parse_from<I, It>(itr: I) -> Result<Self, Error>
    where
        I: IntoIterator<Item = It>,
        It: Into<OsString> + Clone,
    {
        <T as Parser>::try_parse_from(itr).map(Box::new)
    }

Update from iterator, exit on error

Update from iterator, return Err on error.

Implementations on Foreign Types§

Implementors§