From 9264a8b2df90e3a52eb7ccd1cbe2ca788b010b9a Mon Sep 17 00:00:00 2001 From: Jakub Trzeciak Date: Thu, 15 Feb 2024 21:59:28 +0100 Subject: fix refactor main --- src/main.rs | 58 ++++++++++++++++++---------------------------------------- 1 file changed, 18 insertions(+), 40 deletions(-) diff --git a/src/main.rs b/src/main.rs index e06981e..dfc1906 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,5 @@ -use std::{env, fs::{self, File}, path::Path, io::{Error, BufReader, Read}, fmt::format, os::fd::IntoRawFd}; +use std::{env, fs::{self, File}, path::Path, fmt::format, os::fd::IntoRawFd}; +use std::io::{Error, ErrorKind, BufReader, Read}; use lofty::{Probe, TaggedFileExt, LoftyError, TagExt, Tag, Picture, Accessor, PictureType}; use clap::Parser; @@ -95,22 +96,6 @@ impl InnerTag { } } -fn truncate(s: &str, min_chars: usize, max_chars: usize) -> &str { - let e = match s.char_indices().nth(min_chars) { - None => s, - Some((idx, _)) => &s[idx..], - }; - - if max_chars < min_chars { - return ""; - } - - return match e.char_indices().nth(max_chars - min_chars) { - None => e, - Some((idx, _)) => &e[..idx], - } -} - fn tag_ogg_file(path: &Path) -> Result<(), LoftyError> { let mut tagged_file = Probe::open(path) .expect("ERROR: Bad path provided!") @@ -169,38 +154,31 @@ fn tag_ogg_file(path: &Path) -> Result<(), LoftyError> { return Ok(()); } -fn main() { +fn main() -> Result<(), Box> { let args = Args::parse(); - let music_path: String; - - if let Some(path) = args.path { - music_path = path; - } else if let Ok(home) = env::var("HOME") { + let music_path = args.path.unwrap_or_else(|| { println!("💡 Trying to find the music folder automatically"); - music_path = home + "/Music" - } else { - eprintln!("🔥 Couldn't find a music folder automatically"); - std::process::exit(1); - } - let music_dir: fs::ReadDir; + env::var("HOME").map(|home| format!("{}/Music", home)) + .expect("🔥 Couldn't find a music folder automatically") + }); - if let Ok(dir) = fs::read_dir(music_path.as_str()) { - music_dir = dir; - } else { - eprintln!("🔥 Dir \"{}\" doesn't exits", music_path.as_str()); - std::process::exit(1); - } + let music_dir = fs::read_dir(&music_path) + .map_err(|_| format!("🔥 Dir \"{}\" doesn't exist", music_path))?; println!("💡 Start scanning \"{}\" dir for ogg file", music_path.as_str()); - for path in music_dir { - // println!("Name: {}", path.unwrap().file_name().to_str().unwrap()) - if path.as_ref().unwrap().file_type().unwrap().is_file() { - tag_ogg_file(path.unwrap().path().as_path()); + for entry in music_dir { + let path = entry?.path(); + if path.is_file() { + // Improved error handling + if let Err(e) = tag_ogg_file(&path) { + eprintln!("🔥 Error tagging file {:?}: {}", path, e); + } } } - println!("💡 Ended successfully"); + + Ok(()) } -- cgit v1.2.3