From 93c0e8ecee430883c62120f9f0b6999acfac4435 Mon Sep 17 00:00:00 2001 From: Ruben Beltran del Rio Date: Sat, 5 Apr 2025 14:43:19 +0200 Subject: Update, panic less and propagate errors --- src/file_handler/file_strategies/file.rs | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) (limited to 'src/file_handler/file_strategies/file.rs') diff --git a/src/file_handler/file_strategies/file.rs b/src/file_handler/file_strategies/file.rs index 363f712..c31eae4 100644 --- a/src/file_handler/file_strategies/file.rs +++ b/src/file_handler/file_strategies/file.rs @@ -1,17 +1,31 @@ pub struct Strategy {} use std::fs::{copy, create_dir_all}; +use std::io::{Error, ErrorKind, Result}; use std::path::Path; use crate::file_handler::{File, FileType, Strategy as FileHandlerStrategy}; impl Strategy { - fn handle(source: &Path, destination: &Path, file: &File) { - let relative_path = file.path.strip_prefix(source).unwrap(); + fn handle(source: &Path, destination: &Path, file: &File) -> Result<()> { + let relative_path = file.path.strip_prefix(source).map_err(|_| { + Error::new( + ErrorKind::InvalidData, + "Path was not part of source directory.", + ) + })?; let complete_destination = destination.join(relative_path); - let destination_parent = complete_destination.parent().unwrap(); - create_dir_all(destination_parent).unwrap(); - copy(&file.path, &complete_destination).unwrap(); + match complete_destination.parent() { + Some(destination_parent) => { + create_dir_all(destination_parent)?; + copy(&file.path, &complete_destination)?; + Ok(()) + } + None => Err(Error::new( + ErrorKind::InvalidData, + "Destination parent was not readable.", + )), + } } } @@ -28,12 +42,12 @@ impl FileHandlerStrategy for Strategy { matches!(file_type, FileType::File) } - fn handle_html(&self, source: &Path, destination: &Path, file: &File, _l: &str) { - Strategy::handle(source, destination, file); + fn handle_html(&self, source: &Path, destination: &Path, file: &File, _l: &str) -> Result<()> { + Strategy::handle(source, destination, file) } - fn handle_gemini(&self, source: &Path, destination: &Path, file: &File) { - Strategy::handle(source, destination, file); + fn handle_gemini(&self, source: &Path, destination: &Path, file: &File) -> Result<()> { + Strategy::handle(source, destination, file) } } -- cgit