From 82c6700cd6912e23fd65c896ebf92666ecfc644f Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Tue, 24 Sep 2024 21:00:54 +0100 Subject: [PATCH] feat: add support for --dry-run --- justfile | 5 ++++- src/main.rs | 39 ++++++++++++++++++++++++++------------- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/justfile b/justfile index b62eecc..20ae5cf 100644 --- a/justfile +++ b/justfile @@ -1,2 +1,5 @@ -default: +dry-run: + cargo run -- --dry-run ~/Nextcloud/Audible-Inbox/ + +run: cargo run -- ~/Nextcloud/Audible-Inbox/ diff --git a/src/main.rs b/src/main.rs index f45b3bc..2757203 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,30 +17,39 @@ struct Arguments { /// Path path: Option, + + /// Dry-Run + #[clap(long)] + dry_run: bool, +} +impl Arguments { + fn not_dry_run(&self) -> bool { + !self.dry_run + } } fn main() { let args = Arguments::parse(); if args.version { println!("Version {}", crate_version!()); - } else if let Some(path) = args.directory { - rename_files_in_directory(path); - } else if let Some(path) = args.path { - rename_files_in_directory(path); + } else if let Some(path) = &args.directory { + rename_files_in_directory(path.to_string(), &args); + } else if let Some(path) = &args.path { + rename_files_in_directory(path.to_string(), &args); } else { eprintln!("Please provide a directory"); } } -fn rename_files_in_directory(directory: String) { +fn rename_files_in_directory(directory: String, args: &Arguments) { println!("Renaming files in {}", directory); - match rename_files(&directory, &directory) { + match rename_files(&directory, &directory, args) { Ok(count) => println!("Renamed {} files", count), Err(e) => eprintln!("Error: {}", e), } } -fn rename_files(directory: &str, base: &str) -> Result { +fn rename_files(directory: &str, base: &str, args: &Arguments) -> Result { let entries = read_dir(directory).context("Failed to read directory")?; let mut count = 0; for entry in entries { @@ -48,7 +57,7 @@ fn rename_files(directory: &str, base: &str) -> Result { let path = entry.path(); if path.is_dir() { if let Some(sub_dir) = path.to_str() { - count += rename_files(sub_dir, base).context("Failed to rename files")?; + count += rename_files(sub_dir, base, args).context("Failed to rename files")?; } } if path.is_file() { @@ -68,13 +77,17 @@ fn rename_files(directory: &str, base: &str) -> Result { let dir = target_path.parent().with_context(|| { format!("Failed to get parent: {:#?}", target_path) })?; - create_dir_all(dir).with_context(|| { - format!("Failed to create directory: {:#?}", dir) + if args.not_dry_run() { + create_dir_all(dir).with_context(|| { + format!("Failed to create directory: {:#?}", dir) + })?; + } + } + if args.not_dry_run() { + rename(&path, &target_path).with_context(|| { + format!("Failed to rename file: {:#?}", target_path) })?; } - rename(&path, &target_path).with_context(|| { - format!("Failed to rename file: {:#?}", target_path) - })?; } } }