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