mirror of
https://github.com/clap-rs/clap
synced 2024-12-12 13:52:34 +00:00
eda0ca54c1
Clap has focused on reporting development errors through assertions rather than mixing user errors with development errors. Sometimes, developers need to handle things more flexibly so included in #3732 was the reporting of value accessor failures as internal errors with a distinct type. I've been going back and forth on whether the extra error pessimises the usability in the common case vs dealing with the proliferation of different function combinations. In working on deprecating the `value_of` functions, I decided that it was going to be worth duplicating so long as we can keep the documentation focused.
61 lines
1.9 KiB
Rust
61 lines
1.9 KiB
Rust
use clap::error::Error;
|
|
use clap::{Arg, ArgMatches, Args, Command, FromArgMatches, Parser};
|
|
|
|
#[derive(Debug)]
|
|
struct CliArgs {
|
|
foo: bool,
|
|
bar: bool,
|
|
quuz: Option<String>,
|
|
}
|
|
|
|
impl FromArgMatches for CliArgs {
|
|
fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
|
|
let mut matches = matches.clone();
|
|
Self::from_arg_matches_mut(&mut matches)
|
|
}
|
|
fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result<Self, Error> {
|
|
Ok(Self {
|
|
foo: matches.is_present("foo"),
|
|
bar: matches.is_present("bar"),
|
|
quuz: matches.remove_one::<String>("quuz"),
|
|
})
|
|
}
|
|
fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
|
|
let mut matches = matches.clone();
|
|
self.update_from_arg_matches_mut(&mut matches)
|
|
}
|
|
fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> {
|
|
self.foo |= matches.is_present("foo");
|
|
self.bar |= matches.is_present("bar");
|
|
if let Some(quuz) = matches.remove_one::<String>("quuz") {
|
|
self.quuz = Some(quuz);
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
impl Args for CliArgs {
|
|
fn augment_args(cmd: Command<'_>) -> Command<'_> {
|
|
cmd.arg(Arg::new("foo").short('f').long("foo"))
|
|
.arg(Arg::new("bar").short('b').long("bar"))
|
|
.arg(Arg::new("quuz").short('q').long("quuz").takes_value(true))
|
|
}
|
|
fn augment_args_for_update(cmd: Command<'_>) -> Command<'_> {
|
|
cmd.arg(Arg::new("foo").short('f').long("foo"))
|
|
.arg(Arg::new("bar").short('b').long("bar"))
|
|
.arg(Arg::new("quuz").short('q').long("quuz").takes_value(true))
|
|
}
|
|
}
|
|
|
|
#[derive(Parser, Debug)]
|
|
struct Cli {
|
|
#[clap(short, long)]
|
|
top_level: bool,
|
|
#[clap(flatten)]
|
|
more_args: CliArgs,
|
|
}
|
|
|
|
fn main() {
|
|
let args = Cli::parse();
|
|
println!("{:#?}", args);
|
|
}
|