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