Comprehensive Guide to Using Clap for Command-Line Parsing
Command-Line Argument Parsing with Rust Clap
The clap crate in Rust is a powerful library for parsing command-line arguments, building CLI applications with ease. It provides features like argument validation, subcommands, help generation, and environment variable support. This guide dives into clap usage with examples to help you build robust CLI tools.
Adding Clap to Your Rust Project
Add the following dependency in your Cargo.toml file:
[dependencies] clap = { version = "4.0", features = ["derive"] }
The "derive" feature allows you to use the #[derive(Parser)] attribute to simplify argument parsing.
Example: Basic CLI Tool with Clap
Code:
use clap::Parser;
/// Basic example of a CLI tool using clap
#[derive(Parser, Debug)]
#[command(name = "MyCLI", version = "1.0", about = "A simple CLI tool")]
struct Cli {
/// A required input file path
input: String,
/// Enable verbose mode
#[arg(short, long)]
verbose: bool,
}
fn main() {
// Parse command-line arguments into the struct
let args = Cli::parse();
// Print the parsed input
println!("Input file: {}", args.input);
// Check for verbose mode
if args.verbose {
println!("Verbose mode is enabled");
}
}
Code Explanation:
- The Cli struct defines the expected arguments using #[derive(Parser)].
- #[command]: Provides metadata like the name, version, and description of the application.
- #[arg]: Configures individual arguments, such as short for -v and long for --verbose.
- Cli::parse() parses the command-line inputs and maps them to the Cli struct.
- 4. Accessing Arguments:
- Use args.input and args.verbose to access parsed values.
1. Struct Definition:
2. Attributes:
3. Parsing Arguments:
Run Example:
Code:
cargo run -- input.txt --verbose
Output:
Input file: input.txt Verbose mode is enabled
Adding Subcommands with Clap
Subcommands let you structure your CLI tool into distinct operations.
Code:
use clap::{Parser, Subcommand};
/// CLI tool with subcommands
#[derive(Parser, Debug)]
#[command(name = "AppTool", version = "1.0", about = "A tool with subcommands")]
struct Cli {
/// Subcommands for specific actions
#[command(subcommand)]
command: Commands,
}
/// Define available subcommands
#[derive(Subcommand, Debug)]
enum Commands {
/// Add a new item
Add {
/// Name of the item to add
name: String,
},
/// Remove an item by its ID
Remove {
/// ID of the item to remove
id: u32,
},
}
fn main() {
let cli = Cli::parse();
match &cli.command {
Commands::Add { name } => {
println!("Adding item: {}", name);
}
Commands::Remove { id } => {
println!("Removing item with ID: {}", id);
}
}
}
Subcommands Explanation
- The Commands enum specifies the different subcommands (Add, Remove).
- #[command(subcommand)] allows parsing into the Commands enum.
- A match block processes each subcommand.
1. Enum for Subcommands:
2. Parsing Subcommands:
3. Handling Subcommands:
Run Examples:
Code:
cargo run -- add "New Item"
Output:
Adding item: New Item cargo run -- remove --id 42
Removing item with ID: 42
Advanced Features of Clap
- Use #[arg(default_value = "value")] to set defaults for arguments.
- Bind arguments to environment variables using #[arg(env = "ENV_VAR_NAME")].
- Add custom validation with #[arg(value_parser)].
1. Default Values:
2. Environment Variables:
3. Validation:
Example with Environment Variables:
Code:
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
/// Port number, default from environment
#[arg(env = "APP_PORT", default_value = "8080")]
port: u16,
}
fn main() {
let args = Cli::parse();
println!("Using port: {}", args.port);
}
Benefits of Using Clap
- Simple struct-based configuration.
- Includes subcommands, validation, and auto-generated help.
- Widely used and actively maintained.
1. Ease of Use:
2. Rich Feature Set:
3. Community Support:
Rust Language Questions, Answers, and Code Snippets Collection.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics