Clap

crates.io

Installation: cargo add clap --features derive

  1. Derive Parser from clap::Parser
#![allow(unused)]
fn main() {
#[derive(Parser)]
struct Cli {}
}
  1. 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 {}
}
  1. 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)]
}
  1. 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
  1. Validate arguments
  • Enumerated Values
  • Validated Values
  • Argument Relations
  • Custom Validation

Arg Actions

Set Append SetTrue SetFalse Count Help HelpShort HelpLong Version