clap (Command Line Argument Parser) is a popular, full-featured, and highly performant command-line argument parser for Rust. It allows developers to define the structure of their command-line interface (CLI) applications, including arguments, flags, options, and subcommands, in an intuitive and declarative way.
`clap` is widely used in the Rust ecosystem due to its robust feature set and ease of use, especially when combined with its `derive` feature for a more ergonomic API.
Key Features:
* Declarative API: Define your CLI structure using builder patterns or, more commonly, with procedural macros (derive API) for structs and enums.
* Argument Types: Supports various argument types, including positional arguments, named options (e.g., `--opt value`), and boolean flags (e.g., `--flag`).
* Subcommands: Easily define hierarchical CLIs with subcommands, allowing for complex application structures (e.g., `git add`, `git commit`).
* Type Safety: Leverages Rust's strong type system to parse arguments directly into desired types (strings, integers, booleans, custom types, etc.).
* Validation: Provides built-in validation rules (e.g., required arguments, value ranges, custom validators) to ensure valid user input.
* Help Generation: Automatically generates comprehensive, well-formatted, and user-friendly `--help` messages, version information (`--version`), and even man pages.
* Shell Completions: Can generate shell completion scripts for various popular shells (Bash, Zsh, Fish, PowerShell, Elvish), enhancing user experience.
* Error Handling: Offers clear and descriptive error messages for invalid or missing command-line inputs.
* Performance: Optimized for speed and minimal overhead, making it suitable for performance-critical CLI tools.
`clap` significantly simplifies the development of robust and user-friendly CLI applications in Rust, handling much of the boilerplate associated with parsing and validating command-line input.
Example Code
```toml
[package]
name = "clap_example"
version = "0.1.0"
edition = "2021"
[dependencies]
clap = { version = "4.0", features = ["derive"] }
```
```rust
use clap::{Parser, Subcommand};
/// A simple CLI tool to manage tasks.
/// This example demonstrates basic arguments, flags, and subcommands.
#[derive(Parser, Debug)]
#[command(author, version, about = "A simple task manager CLI", long_about = None)]
struct Cli {
/// Optional name to greet
#[arg(short, long)]
name: Option<String>,
/// Turn debugging information on (can be specified multiple times for more verbosity)
#[arg(short, long, action = clap::ArgAction::Count)]
debug: u8,
/// Defines subcommands for the task manager.
#[command(subcommand)]
command: Option<Commands>,
}
#[derive(Subcommand, Debug)]
enum Commands {
/// Adds a new task to the list
Add {
/// The description of the task
task: String,
/// Mark the task as high priority
#[arg(short, long)]
priority: bool,
},
/// Lists all current tasks
List {
/// Show only high priority tasks
#[arg(short, long)]
high_priority_only: bool,
},
/// Marks a task as complete by its ID
Done {
/// The ID of the task to complete
id: u32,
},
}
fn main() {
let cli = Cli::parse();
if let Some(name) = cli.name {
println!("Hello, {}!", name);
}
match cli.debug {
0 => {},
1 => println!("Debug mode is on."),
2 => println!("Verbose debug mode is on."),
_ => println!("Too many debug flags, calm down!"),
}
match &cli.command {
Some(Commands::Add { task, priority }) => {
println!("Adding task: \"{}\" (Priority: {})", task, priority);
// In a real application, you would add this task to a storage system.
},
Some(Commands::List { high_priority_only }) => {
println!("Listing tasks (High priority only: {})", high_priority_only);
// Logic to retrieve and display tasks based on priority.
},
Some(Commands::Done { id }) => {
println!("Marking task ID {} as done.", id);
// Logic to update the status of the task with the given ID.
},
None => {
println!("No subcommand was used. Try `clap_example --help` for available commands.");
}
}
println!("\nExample usage:");
println!(" cargo run -- --help");
println!(" cargo run -- --name Alice --debug list --high-priority");
println!(" cargo run -- add \"Buy groceries\" --priority");
println!(" cargo run -- done 5");
}
```








clap