Rust CLI app for batch file renaming with prefix suffix options dry-run mode and robust error handling using clap and anyhow crates.
use std::fs;
use std::path::{Path, PathBuf};
use clap::{Arg, Command};
use anyhow::{Context, Result};
// Main function that performs the batch rename
fn batch_rename(dir: &Path, prefix: &str, suffix: &str, dry_run: bool) -> Result<()> {
// Reads the specified directory
let entries = fs::read_dir(dir).with_context(|| format!("Unable to read directory: {}", dir.display()))?;
for entry in entries {
let entry = entry?;
let path = entry.path();
// Processes only regular files
if path.is_file() {
if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
// Builds the new name with prefix and suffix
let new_name = format!("{}{}{}", prefix, file_name, suffix);
let new_path = dir.join(&new_name);
if dry_run {
println!("[DRY RUN] {} -> {}", file_name, new_name);
} else {
// Renames the file
fs::rename(&path, &new_path).with_context(|| {
format!("Error renaming '{}' to '{}'", file_name, new_name)
})?;
println!("Renamed: {} -> {}", file_name, new_name);
}
}
}
}
Ok(())
}
fn main() -> Result<()> {
// CLI argument definitions with clap
let matches = Command::new("batch_rename")
.version("1.0")
.author("Senior Software Engineer")
.about("Batch rename files by adding prefix and/or suffix")
.arg(
Arg::new("directory")
.short('d')
.long("directory")
.value_name("DIR")
.help("Directory containing files to rename")
.required(true)
.takes_value(true),
)
.arg(
Arg::new("prefix")
.short('p')
.long("prefix")
.value_name("PREFIX")
.help("Prefix to add to file names")
.default_value("")
.takes_value(true),
)
.arg(
Arg::new("suffix")
.short('s')
.long("suffix")
.value_name("SUFFIX")
.help("Suffix to add to file names")
.default_value("")
.takes_value(true),
)
.arg(
Arg::new("dry_run")
.long("dry-run")
.help("Simulate changes without renaming files")
.takes_value(false),
)
.get_matches();
// Retrieves argument values
let dir = matches.value_of("directory").unwrap();
let prefix = matches.value_of("prefix").unwrap_or("");
let suffix = matches.value_of("suffix").unwrap_or("");
let dry_run = matches.is_present("dry_run");
let dir_path = PathBuf::from(dir);
// Executes the batch rename
batch_rename(&dir_path, prefix, suffix, dry_run)?;
Ok(())
}Rust 1.60+ (compiler and toolchain)
External crate: clap (for command line argument parsing)
External crate: anyhow (for simplified error handling)
CONFIG: accepts arguments -d/--directory (target folder), -p/--prefix (prefix to add), -s/--suffix (suffix to add)
CONFIG: --dry-run option to simulate changes without actually renaming
CONFIG: --help option to show program usage