clap/examples/derive_ref/flatten_hand_args.rs
Ed Page ed45de2f03 fix(parser): Clean up remove types
The remove functions no longer return `Arc` but the core type, at the
cost of requiring `Clone`.  I originally held off on this
in #3732 in the hope of gracefully transition the derive and requiring
`Clone` would have been a breaking change but when it came to #3734, I didn't
find a way to make it work without a breaking change, so I made it
opt-in.  This means I can force the `Clone` requirement now.

I added the requirement for `Clone` everywhere else in the hopes that in
the future, we can drop the `Arc` without a breaking change.
2022-05-24 16:25:07 -05:00

66 lines
2 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")
.expect("matches definition"),
})
}
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")
.expect("matches definition")
{
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);
}