From 1dd07adcdde0ca0781d1aaf23d3e680a20df3f0b Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Sun, 27 Aug 2023 14:28:41 +0100 Subject: [PATCH] rename files --- Cargo.lock | 7 +++++++ Cargo.toml | 1 + src/main.rs | 33 +++++++++++++++++---------------- 3 files changed, 25 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 07a107a..89712d1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,10 +2,17 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "anyhow" +version = "1.0.75" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6" + [[package]] name = "auto-file-mp4" version = "0.1.0" dependencies = [ + "anyhow", "mp4", "taglib", ] diff --git a/Cargo.toml b/Cargo.toml index 46a2065..8fc78cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,3 +8,4 @@ edition = "2021" [dependencies] mp4 = "0.14.0" taglib = "1.0.0" +anyhow = "1.0.75" diff --git a/src/main.rs b/src/main.rs index d74c53a..08f256c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,12 @@ -use std::fs::{self}; +use anyhow::{Context, Result}; +use std::{ + env::args, + fs::{create_dir_all, read_dir, rename}, + path::Path, +}; fn main() { - let directory = std::env::args().nth(1).unwrap(); + let directory = args().nth(1).unwrap(); println!("Renaming files in {}", directory); match rename_files(&directory) { Ok(count) => println!("Renamed {} files", count), @@ -9,25 +14,17 @@ fn main() { } } -fn rename_files(directory: &str) -> Result> { - // Read the directory entries - let entries = fs::read_dir(directory)?; - +fn rename_files(directory: &str) -> Result { + let entries = read_dir(directory).context("Failed to read directory")?; let mut count = 0; - - // Iterate over each entry for entry in entries { - let entry = entry?; - - // Get the file path + let entry = entry.context("Failed to read entry")?; let path = entry.path(); - if path.is_dir() { if let Some(sub_dir) = path.to_str() { - count += rename_files(sub_dir)?; + count += rename_files(sub_dir).context("Failed to rename files")?; } } - // Check if the entry is a file if path.is_file() { if let Ok(file) = taglib::File::new(&path) { if let Ok(tag) = file.tag() { @@ -35,19 +32,23 @@ fn rename_files(directory: &str) -> Result> { if let Some(artist) = tag.artist() { let album = parse_album(&title); count += 1; - // println!("{album}: {title} by {artist}"); let new_name = match album.len() { 0 => format!("{artist}/{title}.mp4a"), _ => format!("{artist}/{album}/{title}.mp4a"), }; println!("Renaming {} to {}", path.display(), new_name); + let target_path = Path::new(&new_name); + if !target_path.exists() { + create_dir_all(&path.parent().unwrap()) + .context("Failed to create directory")?; + } + rename(&path, &target_path).context("Failed to rename file")?; } } } } } } - Ok(count) }