• 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(
17             arg!(
18                 -d --debug "Turn debugging information on"
19             )
20             .action(ArgAction::Count),
21         )
22         .subcommand(
23             Command::new("test")
24                 .about("does testing things")
25                 .arg(arg!(-l --list "lists test values").action(ArgAction::SetTrue)),
26         )
27         .get_matches();
28 
29     // You can check the value provided by positional arguments, or option arguments
30     if let Some(name) = matches.get_one::<String>("name") {
31         println!("Value for name: {}", name);
32     }
33 
34     if let Some(config_path) = matches.get_one::<PathBuf>("config") {
35         println!("Value for config: {}", config_path.display());
36     }
37 
38     // You can see how many times a particular flag or argument occurred
39     // Note, only flags can have multiple occurrences
40     match matches
41         .get_one::<u8>("debug")
42         .expect("Count's are defaulted")
43     {
44         0 => println!("Debug mode is off"),
45         1 => println!("Debug mode is kind of on"),
46         2 => println!("Debug mode is on"),
47         _ => println!("Don't be crazy"),
48     }
49 
50     // You can check for the existence of subcommands, and if found use their
51     // matches just as you would the top level cmd
52     if let Some(matches) = matches.subcommand_matches("test") {
53         // "$ myapp test" was run
54         if *matches.get_one::<bool>("list").expect("defaulted by clap") {
55             // "$ myapp test -l" was run
56             println!("Printing testing lists...");
57         } else {
58             println!("Not printing testing lists...");
59         }
60     }
61 
62     // Continued program logic goes here...
63 }
64