• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use std::path::PathBuf;
2 
3 use clap::{Parser, Subcommand};
4 
5 #[derive(Parser)]
6 #[clap(author, version, about, long_about = None)]
7 struct Cli {
8     /// Optional name to operate on
9     #[clap(value_parser)]
10     name: Option<String>,
11 
12     /// Sets a custom config file
13     #[clap(short, long, value_parser, value_name = "FILE")]
14     config: Option<PathBuf>,
15 
16     /// Turn debugging information on
17     #[clap(short, long, action = clap::ArgAction::Count)]
18     debug: u8,
19 
20     #[clap(subcommand)]
21     command: Option<Commands>,
22 }
23 
24 #[derive(Subcommand)]
25 enum Commands {
26     /// does testing things
27     Test {
28         /// lists test values
29         #[clap(short, long, action)]
30         list: bool,
31     },
32 }
33 
main()34 fn main() {
35     let cli = Cli::parse();
36 
37     // You can check the value provided by positional arguments, or option arguments
38     if let Some(name) = cli.name.as_deref() {
39         println!("Value for name: {}", name);
40     }
41 
42     if let Some(config_path) = cli.config.as_deref() {
43         println!("Value for config: {}", config_path.display());
44     }
45 
46     // You can see how many times a particular flag or argument occurred
47     // Note, only flags can have multiple occurrences
48     match cli.debug {
49         0 => println!("Debug mode is off"),
50         1 => println!("Debug mode is kind of on"),
51         2 => println!("Debug mode is on"),
52         _ => println!("Don't be crazy"),
53     }
54 
55     // You can check for the existence of subcommands, and if found use their
56     // matches just as you would the top level cmd
57     match &cli.command {
58         Some(Commands::Test { list }) => {
59             if *list {
60                 println!("Printing testing lists...");
61             } else {
62                 println!("Not printing testing lists...");
63             }
64         }
65         None => {}
66     }
67 
68     // Continued program logic goes here...
69 }
70