Skip to Content
Course content

202: Building CLIs with Clap Derive API

Click on the "Edit" button in the top corner of the screen to edit your slide content.

By now, you've probably realized that parsing std::env::args() manually is a nightmare the moment you need more than one flag. That's why we use clap. While there's a builder API, the Derive API is where the real magic happens—it lets you define your CLI interface as a plain Rust struct, and clap handles the rest via macros.

How do I actually map a struct to command-line arguments?

First, you need to make sure you have the derive feature enabled in your Cargo.toml, otherwise the Parser trait won't be available. I've seen plenty of people spend an hour debugging "trait not found" errors only to realize they forgot the feature flag.

[dependencies]
clap = { version = "4.0", features = ["derive"] }

Let's say we're building a tool called log-scan that searches for specific keywords in a log file. You just define a struct and decorate it. I usually keep the struct name simple, like Cli or Args.

use clap::Parser;

#[derive(Parser)]
#[command(name = "log-scan")]
#[command(about = "A simple tool to sift through logs", long_about = None)]
struct Cli {
    /// The path to the log file to analyze
    path: std::path::PathBuf,

    /// The keyword to search for
    #[arg(short, long)]
    query: String,

    /// Number of lines of context to show
    #[arg(short, long, default_value_t = 2)]
    context: usize,
}

fn main() {
    let cli = Cli::parse();

    println!("Searching for {} in {:?} with {} lines of context", 
              cli.query, cli.path, cli.context);
}

Notice the doc comments (///). clap actually parses those and turns them into the --help text automatically. It's a great way to keep your documentation and your CLI interface in one place.

What if I need different "modes" of operation, like subcommands?

If your tool does more than one distinct thing, don't try to jam it all into a few flags. That's where subcommands come in. In the Derive API, you represent subcommands as an enum.

Let's expand log-scan so it can either search for a term or count the number of errors. Here is how I'd structure that:

use clap::{Parser, Subcommand};

#[derive(Parser)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Search for a specific pattern in the logs
    Search {
        query: String,
        #[arg(short, long)]
        case_insensitive: bool,
    },
    /// Count occurrences of a specific log level (e.g., ERROR, WARN)
    Count {
        level: String,
    },
}

fn main() {
    let cli = Cli::parse();

    match &cli.command {
        Commands::Search { query, case_insensitive } => {
            println!("Searching for {} (case-insensitive: {})", query, case_insensitive);
        }
        Commands::Count { level } => {
            println!("Counting logs with level: {}", level);
        }
    }
}

This pattern is incredibly powerful because it forces you to handle the logic for each command explicitly using a match statement, which is exactly how Rust's type system is meant to be used.

How do I handle optional arguments without everything becoming an Option<T>?

You'll notice that if you make a field an Option<String>, clap treats it as optional. That's fine, but often you want a sensible default instead of having to unwrap_or() every single variable in your main function.

You can use the default_value_t attribute for types that implement Display, or default_value for raw strings. Honestly, I prefer default_value_t because it's type-safe.

#[derive(Parser)]
struct Cli {
    /// Output format: json or text
    #[arg(short, long, default_value = "text")]
    format: String,

    /// Max threads to use for scanning
    #[arg(short, long, default_value_t = 4)]
    threads: usize,
}

One more tip: if you want a flag that is just a boolean "on/off" switch (like --verbose), just use bool. clap knows that if a field is a bool, it shouldn't expect a value after the flag—its presence alone sets it to true.




📋 Practical Task

Exercise: Build a "Project File Auditor"

Your task is to create a CLI tool called audit-tool that helps a developer find specific files in a project directory. The tool must meet the following requirements:

  • The Main Struct: Must take a positional argument for the root_dir (a PathBuf).
  • Subcommands: Implement two subcommands:
    • find-large: Takes an optional argument size_mb (a u64) which defaults to 100. It should print: "Searching for files larger than [size]MB in [root_dir]".
    • check-ext: Takes a required argument extension (a String) and a boolean flag recursive. It should print: "Checking for .[extension] files in [root_dir] (Recursive: [true/false])".

Ensure you use the derive feature of clap and implement the logic in main using a match statement to handle the subcommands.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.