Rust Primer

Clap (Rust) CLI Primer

Clap is the de-facto argument parser for Rust CLIs. It generates help text, validates flags, and powers everything from cargo to internal Meridian tooling. This primer walks through the derive API, subcommands, and how we wire Clap into the Meridian edge agent so operators get consistent ergonomics across every binary we ship.

1. Install and scaffold

Add Clap to Cargo.toml with the derive feature enabled. The derive macros turn a plain struct into a fully validated argument parser without runtime reflection, which keeps cold-start cost negligible for short-lived CLI binaries.

2. Model commands as enums

Subcommands compose cleanly with Rust enums. Each variant becomes a verb (deploy, status), and pattern-matching on cli.command gives the compiler exhaustiveness checks for free. Add a new variant and the build breaks until you handle it.

3. Wire it into Meridian

The reference snippet below is the same shape we use in the Meridian agent. Region and replica flags get parsed up front, the runtime never sees raw argv, and --help output is generated automatically from the doc comments on each field.

use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(name = "meridian")]
#[command(about = "Meridian CLI", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    Deploy {
        #[arg(short, long)]
        region: String,
        #[arg(short, long, default_value_t = 1)]
        replicas: u32,
    },
    Status {
        #[arg(short, long)]
        verbose: bool,
    },
}

fn main() {
    let cli = Cli::parse();
    match cli.command {
        Commands::Deploy { region, replicas } => {
            println!("Deploying {replicas} replica(s) to {region}");
        }
        Commands::Status { verbose } => {
            println!("Status (verbose={verbose})");
        }
    }
}