Command Line Arguments With clap
Define a CLI interface with clap derives so arguments are parsed, validated, and documented from one struct declaration.
Code
use clap::Parser;
use std::path::PathBuf;
#[derive(Parser, Debug)]
#[command(name = "convert", about = "Convert files between formats")]
struct Cli {
input: PathBuf,
#[arg(short, long, default_value_t = 1)]
level: u8,
#[arg(short, long)]
output: Option<PathBuf>,
#[arg(long, default_value_t = false)]
verbose: bool,
}
fn main() {
let cli = Cli::parse();
if cli.level == 0 || cli.level > 9 {
eprintln!("level must be between 1 and 9");
std::process::exit(2);
}
let output = cli.output.unwrap_or_else(|| cli.input.with_extension("out"));
if cli.verbose {
println!("input={:?} output={:?} level={}", cli.input, output, cli.level);
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.