CLI Application for Batch File Renaming

Rust CLI app for batch file renaming with prefix suffix options dry-run mode and robust error handling using clap and anyhow crates.

Brief Introduction

CLI Application for Batch File Renaming (rust)
DESCRIPTION:
Command line application written in Rust that allows batch renaming of files in a specified directory, adding a prefix or suffix chosen by the user.

ADDITIONAL NOTES:
The application is simple and robust, uses clap for clear argument handling and anyhow for more readable error management. It also supports dry-run mode to avoid accidental changes.

EXPLANATIONS:
- Uses clap to define and validate command line arguments, improving usability and maintenance.
- The batch_rename function reads the directory, filters only regular files, and builds the new name by adding prefix and suffix.
- If dry-run mode is active, it only prints the changes that would be made without actually renaming the files.
- anyhow is used to propagate errors with context, facilitating debugging in case of problems.
- The code is commented in Italian to facilitate understanding even for those who are not native English speakers.

Example Code: rust

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(())
}
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

What do you need?

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