w3resource

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:

    1. Struct Definition:

    • The Cli struct defines the expected arguments using #[derive(Parser)].

    2. Attributes:

    • #[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.

    3. Parsing Arguments:

    • 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.

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

    1. Enum for Subcommands:

    • The Commands enum specifies the different subcommands (Add, Remove).

    2. Parsing Subcommands:

    • #[command(subcommand)] allows parsing into the Commands enum.

    3. Handling Subcommands:

    • A match block processes each subcommand.

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

    1. Default Values:

    • Use #[arg(default_value = "value")] to set defaults for arguments.

    2. Environment Variables:

    • Bind arguments to environment variables using #[arg(env = "ENV_VAR_NAME")].

    3. Validation:

    • Add custom validation with #[arg(value_parser)].

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

    1. Ease of Use:

    • Simple struct-based configuration.

    2. Rich Feature Set:

    • Includes subcommands, validation, and auto-generated help.

    3. Community Support:

    • Widely used and actively maintained.

Rust Language Questions, Answers, and Code Snippets Collection.



Follow us on Facebook and Twitter for latest update.