mod file_strategies; use file_strategies::file::Strategy as FileStrategy; use file_strategies::gemini::Strategy as GeminiStrategy; use file_strategies::layout::Strategy as LayoutStrategy; use std::fs::read_to_string; use std::io::{Error, ErrorKind, Result}; use std::path::{Path, PathBuf}; pub struct FileHandler { pub strategies: Vec>, pub layout: Option, } impl Default for FileHandler { fn default() -> FileHandler { FileHandler { strategies: vec![ Box::new(GeminiStrategy {}), Box::new(LayoutStrategy {}), Box::new(FileStrategy {}), ], layout: None, } } } impl FileHandler { pub fn identify(&self, path: &Path) -> FileType { for strategy in &self.strategies { if strategy.is(path) { return strategy.identify(); } } FileType::Unknown } pub fn get_layout(&mut self, files: &[File]) -> Result<()> { for file in files { if file.file_type == FileType::Layout { let layout_text = read_to_string(&file.path)?; self.layout = Some(layout_text); return Ok(()); } } Err(Error::new( ErrorKind::NotFound, "No layout found. Please ensure there's a _layout.html file at the root", )) } pub fn handle_all( &self, source: &Path, html_destination: &Path, gemini_destination: &Path, files: &[File], ) -> Result<()> { for file in files { self.handle(source, html_destination, gemini_destination, file)?; } Ok(()) } pub fn handle( &self, source: &Path, html_destination: &Path, gemini_destination: &Path, file: &File, ) -> Result<()> { match self .strategies .iter() .find(|s| s.can_handle(&file.file_type)) { Some(strategy) => { let layout = self.layout.as_ref().ok_or_else(|| { Error::new( ErrorKind::NotFound, "Layout should be initialized before handling files", ) })?; strategy.handle_html(source, html_destination, file, layout)?; strategy.handle_gemini(source, gemini_destination, file)?; Ok(()) } // We silently ignore files we can't process. None => Ok(()), } } } pub trait Strategy { fn is(&self, path: &Path) -> bool; fn identify(&self) -> FileType; fn can_handle(&self, file_type: &FileType) -> bool; fn handle_html( &self, source: &Path, destination: &Path, file: &File, layout: &str, ) -> Result<()>; fn handle_gemini(&self, source: &Path, destination: &Path, file: &File) -> Result<()>; } #[derive(Debug, Clone, PartialEq)] pub enum FileType { Gemini, File, Layout, Unknown, } #[derive(PartialEq, Debug)] pub struct File { pub path: PathBuf, pub file_type: FileType, } #[cfg(test)] mod tests { use std::fs::create_dir_all; use std::path::PathBuf; use super::*; use test_utilities::*; fn create_test_internal_file(path: &str, file_type: FileType) -> File { File { path: PathBuf::from(path), file_type, } } #[test] fn test_identify_gemini_file() { let handler = FileHandler::default(); let path = PathBuf::from("test.gmi"); assert!(matches!(handler.identify(&path), FileType::Gemini)); } #[test] fn test_identify_layout_file() { let handler = FileHandler::default(); let path = PathBuf::from("_layout.html"); assert!(matches!(handler.identify(&path), FileType::Layout)); } #[test] fn test_identify_regular_file() { let handler = FileHandler::default(); let path = PathBuf::from("regular.html"); assert!(matches!(handler.identify(&path), FileType::File)); } #[test] fn test_identify_unknown_file() { let handler = FileHandler::default(); let path = PathBuf::from("tests"); assert!(matches!(handler.identify(&path), FileType::Unknown)); } #[test] fn test_get_layout_success() { let test_dir = setup_test_dir(); let layout_path = test_dir.join("_layout.html"); create_test_file(&layout_path, ""); let mut handler = FileHandler::default(); let files = vec![ create_test_internal_file("test.gmi", FileType::Gemini), create_test_internal_file( layout_path.to_str().expect("Could not encode layout"), FileType::Layout, ), create_test_internal_file("regular.html", FileType::File), ]; assert!(handler.get_layout(&files).is_ok()); } #[test] fn test_get_layout_failure() { let mut handler = FileHandler::default(); let files = vec![ create_test_internal_file("test.gmi", FileType::Gemini), create_test_internal_file("regular.html", FileType::File), ]; assert!(handler.get_layout(&files).is_err()); } // Mock strategy for testing struct MockStrategy { is_match: bool, file_type: FileType, } impl Strategy for MockStrategy { fn is(&self, _path: &Path) -> bool { self.is_match } fn identify(&self) -> FileType { self.file_type.clone() } fn can_handle(&self, file_type: &FileType) -> bool { &self.file_type == file_type } fn handle_html( &self, _source: &Path, _destination: &Path, _file: &File, _layout: &str, ) -> Result<()> { Ok(()) } fn handle_gemini(&self, _source: &Path, _destination: &Path, _file: &File) -> Result<()> { Ok(()) } } // Mock strategy for testing struct ErroringMockStrategy { is_match: bool, file_type: FileType, } impl Strategy for ErroringMockStrategy { fn is(&self, _path: &Path) -> bool { self.is_match } fn identify(&self) -> FileType { self.file_type.clone() } fn can_handle(&self, file_type: &FileType) -> bool { &self.file_type == file_type } fn handle_html( &self, _source: &Path, _destination: &Path, _file: &File, _layout: &str, ) -> Result<()> { Err(Error::new( ErrorKind::Other, "Forced to fail by my cruel author.", )) } fn handle_gemini(&self, _source: &Path, _destination: &Path, _file: &File) -> Result<()> { Err(Error::new( ErrorKind::Other, "Forced to fail by my benevolent author.", )) } } #[test] fn test_custom_strategy() { let mock_strategy = MockStrategy { is_match: true, file_type: FileType::Gemini, }; let handler = FileHandler { strategies: vec![Box::new(mock_strategy)], layout: Some("None".to_string()), }; let path = PathBuf::from("test.whatever"); let file = File { path: path.clone(), file_type: FileType::Gemini, }; assert!(matches!(handler.identify(&path), FileType::Gemini)); assert!(handler.handle(&path, &path, &path, &file).is_ok()); } #[test] fn test_failure_propagates_in_handler() { let mock_strategy = ErroringMockStrategy { is_match: true, file_type: FileType::Gemini, }; let handler = FileHandler { strategies: vec![Box::new(mock_strategy)], layout: Some("None".to_string()), }; let path = PathBuf::from("test.whatever"); let file = File { path: path.clone(), file_type: FileType::Gemini, }; assert!(matches!(handler.identify(&path), FileType::Gemini)); assert!(handler.handle(&path, &path, &path, &file).is_err()); } #[test] fn silently_ignore_unhandleable_files() { let mock_strategy = MockStrategy { is_match: false, file_type: FileType::Gemini, }; let handler = FileHandler { strategies: vec![Box::new(mock_strategy)], layout: Some("None".to_string()), }; let path = PathBuf::from("test.whatever"); let file = File { path: path.clone(), file_type: FileType::Layout, }; assert!(handler.handle(&path, &path, &path, &file).is_ok()); } #[test] fn test_handle_all_empty_files() { let handler = FileHandler::default(); let files: Vec = vec![]; // Should not panic with empty vector assert!( handler .handle_all( &PathBuf::from("source"), &PathBuf::from("output_html"), &PathBuf::from("output_gemini"), &files, ) .is_ok() ); } #[test] fn test_handle_with_layout() { let handler = FileHandler { layout: Some("test layout".to_string()), ..Default::default() }; let test_dir = setup_test_dir(); create_dir_all(test_dir.join("output_html")) .expect("Could not create output html test directory"); create_dir_all(test_dir.join("output_gemini")) .expect("Could not create output gemini test directory"); let test_path = test_dir.join("test.gmi"); create_test_file(&test_path, ""); let file = create_test_internal_file( test_path .to_str() .expect("Could not encode gemini test file"), FileType::Gemini, ); // Should not panic with valid layout assert!( handler .handle( &test_dir, &test_dir.join("output_html"), &test_dir.join("output_gemini"), &file, ) .is_ok() ); } #[test] fn test_handle_without_layout() { let handler = FileHandler::default(); let file = create_test_internal_file("test.gmi", FileType::Gemini); assert!( handler .handle( &PathBuf::from("source"), &PathBuf::from("output_html"), &PathBuf::from("output_gemini"), &file, ) .is_err() ); } #[test] fn test_slice_handling() { let test_dir = setup_test_dir(); let layout_path = test_dir.join("_layout.html"); create_test_file(&layout_path, ""); create_test_file(&test_dir.join("test1.gmi"), ""); create_test_file(&test_dir.join("test2.gmi"), ""); create_test_file(&test_dir.join("test3.gmi"), ""); create_dir_all(test_dir.join("output_html")) .expect("Could not create output html test directory"); create_dir_all(test_dir.join("output_gemini")) .expect("Could not create output gemini test directory"); let mut handler = FileHandler::default(); let files = [ create_test_internal_file( test_dir .join("test1.gmi") .to_str() .expect("Could not encode test1"), FileType::Gemini, ), create_test_internal_file( layout_path.to_str().expect("Could not encode layout"), FileType::Layout, ), create_test_internal_file( test_dir .join("test2.gmi") .to_str() .expect("Could not encode test2"), FileType::Gemini, ), create_test_internal_file( test_dir .join("test3.gmi") .to_str() .expect("Could not encode test3"), FileType::Gemini, ), ]; let _ = handler.get_layout(&files[1..]); // Test with slice assert!( handler .handle_all( &test_dir, &test_dir.join("output_html"), &test_dir.join("output_gemini"), &files[1..], // Test with slice of last three elements ) .is_ok() ); } }