Zum Inhalt springen

Clap

https://lib.rs/crates/clap https://crates.io/crates/clap

Installation: cargo add clap --features derive

  1. Derive Parser from clap::Parser
#[derive(Parser)]
struct Cli {}
  1. Configure the Parser
#[derive(Parser)]
#[command(
name = "Cli",
author = "John Doe <[email protected]",
version = "1.0",
about = "Does awesome things",
long_about = None,
)]
struct Cli {}

Or read values from Cargo.toml:

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {}
  1. Change Parser behaviour

Change the help text. A list of possible placeholders can be found here:

#[command(help_template = "{name} ({version}) - {usage}")]

Disable the help flag (-h and —help):

#[command(disable_help_flag = true)]

Require each argument to have a help text:

#[command(help_expected = true)]
  1. Add arguments
  • Positional
#[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
#[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
  • Default
  1. Validate arguments
  • Enumerated Values
  • Validated Values
  • Argument Relations
  • Custom Validation

Set Append SetTrue SetFalse Count Help HelpShort HelpLong Version