Clap
Installation: cargo add clap --features derive
- Derive Parser from
clap::Parser
#![allow(unused)] fn main() { #[derive(Parser)] struct Cli {} }
- Configure the Parser
#![allow(unused)] fn main() { #[derive(Parser)] #[command( name = "Cli", author = "John Doe <john.doe@example.com", version = "1.0", about = "Does awesome things", long_about = None, )] struct Cli {} }
Or read values from Cargo.toml:
#![allow(unused)] fn main() { #[derive(Parser)] #[command(author, version, about, long_about = None)] struct Cli {} }
- Change Parser behaviour
Change the help text. A list of possible placeholders can be found here:
#![allow(unused)] fn main() { #[command(help_template = "{name} ({version}) - {usage}")] }
Disable the help flag (-h and --help):
#![allow(unused)] fn main() { #[command(disable_help_flag = true)] }
Require each argument to have a help text:
#![allow(unused)] fn main() { #[command(help_expected = true)] }
- Add arguments
- Positional
#![allow(unused)] fn main() { #[derive(Parser)] struct Cli { /// This is a positional, required argument positional: String, /// This is an optinal argument positional: Optional<String>, // Variadic positional arguments name: Vec<String>, } }
- Flag
#![allow(unused)] fn main() { #[derive(Parser)] struct Cli { /// On/Off switch #[arg(short, long)] release: bool, /// Set the default value to true #[arg(short, long, action = clap::ArgAction::SetFalse)] quiet: bool, /// Flag that counts how often it is set, eg. -vvv would be 3, -vv would be 2 #[arg(short, long, action = clap::ArgAction::Count)] verbose: u8 } }
- Subcommand
#![allow(unused)] fn main() { }
- Default
- Validate arguments
- Enumerated Values
- Validated Values
- Argument Relations
- Custom Validation
Arg Actions
Set Append SetTrue SetFalse Count Help HelpShort HelpLong Version