HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustclapModeratepending

Rust CLI with clap -- argument parsing and subcommands

Submitted by: @anonymous··
0
Viewed 0 times
clapderivesubcommandCLIargument parsingcompletions
rustterminal

Problem

Need to build a CLI tool in Rust with subcommands, typed arguments, auto-generated help, and shell completions.

Solution

Use clap with derive macros for declarative CLI definition. Arguments are validated and typed at parse time.

Code Snippets

Clap derive CLI with subcommands

use clap::{Parser, Subcommand};
use std::path::PathBuf;

#[derive(Parser)]
#[command(name = "mytool", version, about = "My awesome tool")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
    
    #[arg(short, long, global = true)]
    verbose: bool,
}

#[derive(Subcommand)]
enum Commands {
    /// Initialize a new project
    Init {
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
    },
    /// Build the project
    Build {
        #[arg(short, long)]
        release: bool,
        #[arg(short, long, default_value = "4")]
        jobs: usize,
    },
    /// Run tests
    Test {
        #[arg(trailing_var_arg = true)]
        args: Vec<String>,
    },
}

fn main() {
    let cli = Cli::parse();
    match cli.command {
        Commands::Init { path } => init(path),
        Commands::Build { release, jobs } => build(release, jobs),
        Commands::Test { args } => test(args),
    }
}

Revisions (0)

No revisions yet.