summaryrefslogtreecommitdiffstats
path: root/third_party/rust/clap/examples/derive_ref/flatten_hand_args.rs
blob: 2969457e18934a021dd2db6176ec3130933d2ad3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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> {
        Ok(Self {
            foo: matches.is_present("foo"),
            bar: matches.is_present("bar"),
            quuz: matches.value_of("quuz").map(|quuz| quuz.to_owned()),
        })
    }
    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
        self.foo |= matches.is_present("foo");
        self.bar |= matches.is_present("bar");
        if let Some(quuz) = matches.value_of("quuz") {
            self.quuz = Some(quuz.to_owned());
        }
        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);
}