Rust, with its memory safety, zero-cost abstractions, and excellent cross-compilation capabilities, is becoming an ideal choice for building CLI operations tools. An increasing number of infrastructure tools (such as fd, ripgrep, bat) are implemented in Rust. This article introduces how to use the Rust ecosystem to build efficient operations CLI tools.
Argument Parsing and Colored Output
Use clap for declarative argument parsing, colored or termcolor for colorful terminal output, and anyhow for human-friendly error handling:
use clap::Parser;
use anyhow::{Result, Context};
use colored::*;
use std::path::PathBuf;
#[derive(Parser)]
#[command(name = "log-analyzer")]
#[command(about = "High-performance log analyzer", version = "1.0.0")]
struct Cli {
/// Path to the log file
#[arg(short, long, value_name = "FILE")]
file: PathBuf,
/// Search pattern
#[arg(short, long)]
pattern: String,
/// Output format (text/json)
#[arg(long, default_value = "text")]
format: String,
/// Limit the number of results
#[arg(short, long, default_value_t = 100)]
limit: usize,
}
fn main() -> Result<()> {
let cli = Cli::parse();
let content = std::fs::read_to_string(&cli.file)
.with_context(|| format!("Cannot read file: {}", cli.file.display()))?;
let matches: Vec<&str> = content
.lines()
.filter(|line| line.contains(&cli.pattern))
.take(cli.limit)
.collect();
println!("{}", format!("Analysis complete, {} matches found", matches.len()).green().bold());
if cli.format == "text" {
for (i, line) in matches.iter().enumerate() {
println!("{}. {}", (i + 1).to_string().cyan(), line);
}
}
Ok(())
}Ops Tool Development Patterns
Rust’s advantages in CLI ops tool development span several dimensions. Safety and performance ensure tools remain efficient and stable under large data volumes; cross-compilation allows a single codebase to target Linux, macOS, and Windows platforms easily; the tokio async runtime provides a solid foundation for parallel processing scenarios (such as batch SSH operations). Combined with serde for configuration serialization, reqwest for HTTP calls, and indicatif for progress bars, you can build fully-featured, professional-grade operations toolchains.