feat: add support for --dry-run

This commit is contained in:
Paul Campbell 2024-09-24 21:00:54 +01:00
parent cd27b983a9
commit f0927a600c
2 changed files with 30 additions and 14 deletions

View file

@ -1,2 +1,5 @@
default:
dry-run:
cargo run -- --dry-run ~/Nextcloud/Audible-Inbox/
run:
cargo run -- ~/Nextcloud/Audible-Inbox/

View file

@ -17,30 +17,39 @@ struct Arguments {
/// Path
path: Option<String>,
/// 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<i32> {
fn rename_files(directory: &str, base: &str, args: &Arguments) -> Result<i32> {
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<i32> {
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<i32> {
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)
})?;
}
}
}