files are mp4b

This commit is contained in:
Paul Campbell 2023-08-27 15:00:26 +01:00
parent 1dd07adcdd
commit c3a0a37e0a

View file

@ -8,13 +8,13 @@ use std::{
fn main() { fn main() {
let directory = args().nth(1).unwrap(); let directory = args().nth(1).unwrap();
println!("Renaming files in {}", directory); println!("Renaming files in {}", directory);
match rename_files(&directory) { match rename_files(&directory, &directory) {
Ok(count) => println!("Renamed {} files", count), Ok(count) => println!("Renamed {} files", count),
Err(e) => eprintln!("Error: {}", e), Err(e) => eprintln!("Error: {}", e),
} }
} }
fn rename_files(directory: &str) -> Result<i32> { fn rename_files(directory: &str, base: &str) -> Result<i32> {
let entries = read_dir(directory).context("Failed to read directory")?; let entries = read_dir(directory).context("Failed to read directory")?;
let mut count = 0; let mut count = 0;
for entry in entries { for entry in entries {
@ -22,7 +22,7 @@ fn rename_files(directory: &str) -> Result<i32> {
let path = entry.path(); let path = entry.path();
if path.is_dir() { if path.is_dir() {
if let Some(sub_dir) = path.to_str() { if let Some(sub_dir) = path.to_str() {
count += rename_files(sub_dir).context("Failed to rename files")?; count += rename_files(sub_dir, base).context("Failed to rename files")?;
} }
} }
if path.is_file() { if path.is_file() {
@ -34,15 +34,21 @@ fn rename_files(directory: &str) -> Result<i32> {
count += 1; count += 1;
let new_name = match album.len() { let new_name = match album.len() {
0 => format!("{artist}/{title}.mp4a"), 0 => format!("{artist}/{title}.mp4a"),
_ => format!("{artist}/{album}/{title}.mp4a"), _ => format!("{artist}/{album}/{title}.mp4b"),
}; };
println!("Renaming {} to {}", path.display(), new_name); println!("Renaming {} to {}", path.display(), new_name);
let target_path = Path::new(&new_name); let target_path = Path::new(&base).join(new_name);
if !target_path.exists() { if !target_path.exists() {
create_dir_all(&path.parent().unwrap()) let dir = target_path.parent().with_context(|| {
.context("Failed to create directory")?; format!("Failed to get parent: {:#?}", target_path)
})?;
create_dir_all(&dir).with_context(|| {
format!("Failed to create directory: {:#?}", dir)
})?;
} }
rename(&path, &target_path).context("Failed to rename file")?; rename(&path, &target_path).with_context(|| {
format!("Failed to rename file: {:#?}", target_path)
})?;
} }
} }
} }