]>
Commit | Line | Data |
---|---|---|
923072b8 FG |
1 | // Note: this requires the `cargo` feature |
2 | ||
3 | use std::path::PathBuf; | |
4 | ||
5 | use clap::{arg, command, value_parser, ArgAction, Command}; | |
04454e1e FG |
6 | |
7 | fn main() { | |
8 | let matches = command!() | |
9 | .arg(arg!([name] "Optional name to operate on")) | |
10 | .arg( | |
11 | arg!( | |
12 | -c --config <FILE> "Sets a custom config file" | |
13 | ) | |
14 | // We don't have syntax yet for optional options, so manually calling `required` | |
15 | .required(false) | |
923072b8 FG |
16 | .value_parser(value_parser!(PathBuf)), |
17 | ) | |
18 | .arg( | |
19 | arg!( | |
20 | -d --debug "Turn debugging information on" | |
21 | ) | |
22 | .action(ArgAction::Count), | |
04454e1e | 23 | ) |
04454e1e FG |
24 | .subcommand( |
25 | Command::new("test") | |
26 | .about("does testing things") | |
923072b8 | 27 | .arg(arg!(-l --list "lists test values").action(ArgAction::SetTrue)), |
04454e1e FG |
28 | ) |
29 | .get_matches(); | |
30 | ||
31 | // You can check the value provided by positional arguments, or option arguments | |
923072b8 | 32 | if let Some(name) = matches.get_one::<String>("name") { |
04454e1e FG |
33 | println!("Value for name: {}", name); |
34 | } | |
35 | ||
923072b8 | 36 | if let Some(config_path) = matches.get_one::<PathBuf>("config") { |
04454e1e FG |
37 | println!("Value for config: {}", config_path.display()); |
38 | } | |
39 | ||
40 | // You can see how many times a particular flag or argument occurred | |
41 | // Note, only flags can have multiple occurrences | |
923072b8 FG |
42 | match matches |
43 | .get_one::<u8>("debug") | |
44 | .expect("Count's are defaulted") | |
45 | { | |
04454e1e FG |
46 | 0 => println!("Debug mode is off"), |
47 | 1 => println!("Debug mode is kind of on"), | |
48 | 2 => println!("Debug mode is on"), | |
49 | _ => println!("Don't be crazy"), | |
50 | } | |
51 | ||
52 | // You can check for the existence of subcommands, and if found use their | |
53 | // matches just as you would the top level cmd | |
54 | if let Some(matches) = matches.subcommand_matches("test") { | |
55 | // "$ myapp test" was run | |
923072b8 | 56 | if *matches.get_one::<bool>("list").expect("defaulted by clap") { |
04454e1e FG |
57 | // "$ myapp test -l" was run |
58 | println!("Printing testing lists..."); | |
59 | } else { | |
60 | println!("Not printing testing lists..."); | |
61 | } | |
62 | } | |
63 | ||
64 | // Continued program logic goes here... | |
65 | } |