Skip to content

Instantly share code, notes, and snippets.

@LuMarans30
Created November 13, 2025 16:32
Show Gist options
  • Select an option

  • Save LuMarans30/13898c56ee252f5bffecb190f8ae5922 to your computer and use it in GitHub Desktop.

Select an option

Save LuMarans30/13898c56ee252f5bffecb190f8ae5922 to your computer and use it in GitHub Desktop.
Example of Rust CLI program that uses the clap crate
use anyhow::Result;
use clap::Parser;
use std::{
io::Write,
path::{Path, PathBuf},
};
#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
/// Path to the input configuration file
#[arg(short, long, required = true)]
input: PathBuf,
/// Path for the output timetable file
#[arg(short, long, required = true)]
output: PathBuf,
}
fn main() -> Result<()> {
let Cli { input, output } = Cli::parse();
if !validate_args(&input, &output)? {
return Ok(());
}
Ok(())
}
fn confirm_overwrite() -> Result<bool> {
eprint!("Warning: output file already exists.\nOverwrite it? [y/N]: ");
std::io::stderr().flush()?;
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
let response = input.trim().to_lowercase();
Ok(matches!(response.as_str(), "y" | "yes"))
}
fn validate_args(input: &Path, output: &Path) -> Result<bool> {
if !input.try_exists()? {
anyhow::bail!("Input file does not exist: {}", input.display());
}
if !input.is_file() {
anyhow::bail!("Input path is not a file: {}", input.display());
}
if output.try_exists()? && !confirm_overwrite()? {
eprintln!("Exiting...");
return Ok(false);
}
//TODO: Check validity of input file format
Ok(true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment