I had a shell script for my sensor nodes that grew to well over 100 lines, most of it argument parsing with getopts. I rewrote it in Rust with clap, and I want to keep the skeleton here for the next tool. You get one binary, readable errors, and --help without extra work.
clap 4 was released in September 2022. The derive API is the simplest way to use it.
Setup
cargo new sensorctl && cd sensorctl
cargo add clap --features derive
Code
use clap::{Parser, Subcommand};
use std::path::PathBuf;
/// Small tool to manage sensor nodes
#[derive(Parser)]
#[command(author, version, about)]
struct Cli {
/// MQTT broker host
#[arg(long, default_value = "localhost", env = "MQTT_HOST")]
host: String,
/// More output (-v, -vv)
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// List known nodes
List,
/// Push a config file to a node
Push {
/// Node id, for example pico-01
node: String,
/// Config file
#[arg(short, long)]
file: PathBuf,
/// Only show what would happen
#[arg(long)]
dry_run: bool,
},
}
fn main() {
let cli = Cli::parse();
if cli.verbose > 0 {
eprintln!("broker: {}", cli.host);
}
match cli.command {
Command::List => println!("listing nodes on {}", cli.host),
Command::Push { node, file, dry_run } => {
println!("push {} to {} (dry run: {})", file.display(), node, dry_run);
}
}
}
Note: the env attribute needs the env feature: cargo add clap --features derive,env.
Trying it
cargo run -- --help
cargo run -- push pico-01 --file node.toml --dry-run
cargo run -- push pico-01
# error: the following required arguments were not provided:
# --file <FILE>
Doc comments (///) become the help text. bool fields become flags, Option<T> fields become optional arguments, and other types are required unless they have a default. Field names turn into --kebab-case options, so dry_run is --dry-run. Types are parsed for you: a u16 port rejects abc with a clear message.
A few small things I had to look up:
- Use
PathBuffor paths, notString. - For typed defaults use
default_value_t:#[arg(long, default_value_t = 1883)] port: u16. - Return
Resultfrommain(I useanyhow), so errors print cleanly and the exit code is not zero.
For a Pi, cargo build --release on the Pi itself works but is slow. I have not set up cross-compiling yet.
I still keep short scripts in shell. If the tool is 20 lines that call other programs, Rust is too much.