From c8d84a94edbc3f5eeb80d56236b633caad88ac07 Mon Sep 17 00:00:00 2001 From: SimonThormeyer <49559340+SimonThormeyer@users.noreply.github.com> Date: Fri, 3 May 2024 14:58:55 +0200 Subject: [PATCH] refactor: use thiserror crate to implement custom errors (#67) * refactor: use thiserror crate to implement custom errors * build: track cargo.lock * build: update tantivy * style: run fmt * Revert "build: track cargo.lock" This reverts commit 34c1a5b8255f5dc0c894f5d108c7be3b426b661e. * Revert "build: update tantivy" This reverts commit c672c0a1bbc1099c38b6fa5937df7e32f1846384. --- Cargo.toml | 1 + index/Cargo.toml | 1 + index/src/lib.rs | 30 ++++++++------------ litt/Cargo.toml | 1 + litt/src/main.rs | 68 ++++++++++++++++++++++----------------------- litt/src/tracker.rs | 25 ++++------------- search/Cargo.toml | 1 + search/src/lib.rs | 16 +++-------- 8 files changed, 58 insertions(+), 85 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 51b9398..839e798 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,3 +17,4 @@ shellexpand = "3.1.0" uuid = "1.3.2" colored = "2" open = "4.1.0" +thiserror = "1.0" \ No newline at end of file diff --git a/index/Cargo.toml b/index/Cargo.toml index e529c60..19412c6 100644 --- a/index/Cargo.toml +++ b/index/Cargo.toml @@ -9,6 +9,7 @@ edition = "2021" tantivy = { workspace = true } uuid = { workspace = true } serde_json = { workspace = true } +thiserror = { workspace = true } walkdir = "2.3.3" litt_shared = { path = "../shared" } rayon = "1.8.0" diff --git a/index/src/lib.rs b/index/src/lib.rs index e660f27..160ac96 100644 --- a/index/src/lib.rs +++ b/index/src/lib.rs @@ -1,35 +1,27 @@ -use std::fmt; -use std::fmt::Formatter; +use thiserror::Error; pub mod index; -#[derive(Debug)] +#[derive(Debug, Error)] pub enum LittIndexError { + #[error("Index Creation Error: `{0}`")] CreationError(String), + #[error("Error updating the index: `{0}`")] UpdateError(String), + #[error("Error opening existing index: `{0}`")] OpenError(String), + #[error("Error reloading index writer: `{0}`")] ReloadError(String), + #[error("Index Write Error: `{0}`")] WriteError(String), + #[error("Index is not in assumed state: `{0}`")] StateError(String), + #[error("Index Read Error: `{0}`")] ReadError(String), + #[error("Error parsing PDF: `{0}`")] PdfParseError(String), + #[error("Error parsing txt-file: `{0}`")] TxtParseError(String), } -impl fmt::Display for LittIndexError { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - match &self { - LittIndexError::CreationError(s) => write!(f, "Index Creation Error: {}", s), - LittIndexError::OpenError(s) => write!(f, "Error opening existing index: {}", s), - LittIndexError::UpdateError(s) => write!(f, "Error updating the index: {}", s), - LittIndexError::WriteError(s) => write!(f, "Index Write Error: {}", s), - LittIndexError::ReadError(s) => write!(f, "Index Read Error: {}", s), - LittIndexError::StateError(s) => write!(f, "Index is not in assumed state: {}", s), - LittIndexError::PdfParseError(s) => write!(f, "Error parsing PDF: {}", s), - LittIndexError::TxtParseError(s) => write!(f, "Error parsing txt-file: {}", s), - LittIndexError::ReloadError(s) => write!(f, "Error reloading index writer: {}", s), - } - } -} - pub type Result = std::result::Result; diff --git a/litt/Cargo.toml b/litt/Cargo.toml index 3675abf..50d5ef1 100644 --- a/litt/Cargo.toml +++ b/litt/Cargo.toml @@ -5,6 +5,7 @@ edition = "2021" [dependencies] tantivy = { workspace = true } +thiserror = { workspace = true } clap = { workspace = true, features = ["derive"] } serde = { workspace = true } serde_json = { workspace = true } diff --git a/litt/src/main.rs b/litt/src/main.rs index 16566f6..fe676c6 100644 --- a/litt/src/main.rs +++ b/litt/src/main.rs @@ -1,7 +1,5 @@ use std::collections::HashMap; use std::env; -use std::fmt; -use std::fmt::Formatter; use std::fs; use std::path::Path; use std::time::Instant; @@ -21,16 +19,12 @@ use cli::Cli; use tracker::IndexTracker; use colored::*; +use thiserror::Error; -#[derive(Debug)] -struct LittError(String); - -impl fmt::Display for LittError { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - match &self { - LittError(s) => write!(f, "{}", s.red()), - } - } +#[derive(Debug, Error)] +enum LittError { + #[error("Error:`{0}`")] + General(String), } fn get_first_term(query: &str) -> String { @@ -76,13 +70,13 @@ fn open_std_programm(path: String) -> Result<(), LittError> { std::process::Command::new("open") .arg(&path) .spawn() - .map_err(|e| LittError(e.to_string()))?; + .map_err(|e| LittError::General(e.to_string()))?; #[cfg(target_os = "linux")] std::process::Command::new("xdg-open") .arg(&path) .spawn() - .map_err(|e| LittError(e.to_string()))?; + .map_err(|e| LittError::General(e.to_string()))?; #[cfg(windows)] std::process::Command::new("cmd") @@ -90,7 +84,7 @@ fn open_std_programm(path: String) -> Result<(), LittError> { .arg("start") .arg(&path) .spawn() - .map_err(|e| LittError(e.to_string()))?; + .map_err(|e| LittError::General(e.to_string()))?; Ok(()) } @@ -98,7 +92,7 @@ fn open_std_programm(path: String) -> Result<(), LittError> { fn main() -> Result<(), LittError> { let mut index_tracker = match IndexTracker::create(".litt".into()) { Ok(index_tracker) => index_tracker, - Err(e) => return Err(LittError(e.to_string())), + Err(e) => return Err(LittError::General(e.to_string())), }; // Check for fast last-number access @@ -108,7 +102,7 @@ fn main() -> Result<(), LittError> { if let Ok(last_result) = &first_arg.trim().parse::() { let fast_results = match index_tracker.load_fast_results() { Ok(fast_results) => fast_results, - Err(e) => return Err(LittError(e.to_string())), + Err(e) => return Err(LittError::General(e.to_string())), }; let path = fast_results .get(last_result) @@ -135,7 +129,7 @@ fn main() -> Result<(), LittError> { println!(" - {:?}", index); } } - Err(e) => return Err(LittError(e.to_string())), + Err(e) => return Err(LittError::General(e.to_string())), } return Ok(()); } @@ -145,15 +139,15 @@ fn main() -> Result<(), LittError> { None => { Cli::command() .print_help() - .map_err(|e| LittError(e.to_string()))?; - return Err(LittError("Litt index missing!".into())); + .map_err(|e| LittError::General(e.to_string()))?; + return Err(LittError::General("Litt index missing!".into())); } Some(index_name) => index_name, }; // initialize new index if !cli.init.is_empty() { - let current_dir = env::current_dir().map_err(|e| LittError(e.to_string()))?; + let current_dir = env::current_dir().map_err(|e| LittError::General(e.to_string()))?; let path = current_dir.join(cli.init); println!( "Creating new index \"{}\" at: {}: ", @@ -161,7 +155,7 @@ fn main() -> Result<(), LittError> { path.to_string_lossy() ); if index_tracker.exists(&index_name) || index_tracker.path_exists(&path).is_some() { - return Err(LittError(format!( + return Err(LittError::General(format!( "Failed to create index since it already exists: name: {}, path: {}", index_tracker.get_name(&path).unwrap_or_default(), path.to_string_lossy() @@ -171,20 +165,22 @@ fn main() -> Result<(), LittError> { // failiure) let start = Instant::now(); if let Err(e) = index_tracker.add(index_name, path.clone()) { - return Err(LittError(e.to_string())); + return Err(LittError::General(e.to_string())); } let mut index = match Index::create(&path, SearchSchema::default()) { Ok(index) => index, - Err(e) => return Err(LittError(e.to_string())), + Err(e) => return Err(LittError::General(e.to_string())), }; index = match index.add_all_documents() { Ok(index_with_documents) => index_with_documents, - Err(e) => return Err(LittError(e.to_string())), + Err(e) => return Err(LittError::General(e.to_string())), }; - let searcher = index.searcher().map_err(|e| LittError(e.to_string()))?; + let searcher = index + .searcher() + .map_err(|e| LittError::General(e.to_string()))?; println!( "Successfully indexed {} document pages in {:?}", searcher.num_docs(), @@ -197,13 +193,13 @@ fn main() -> Result<(), LittError> { // remove litt directory at index path let path = match index_tracker.get_path(&index_name) { Ok(path) => path, - Err(e) => return Err(LittError(e.to_string())), + Err(e) => return Err(LittError::General(e.to_string())), }; let index_path = path.join(LITT_DIRECTORY_NAME); fs::remove_dir_all(index_path).expect("Could not remove index-file"); // remove litt-index from tracker. if let Err(e) = index_tracker.remove(index_name.clone()) { - return Err(LittError(e.to_string())); + return Err(LittError::General(e.to_string())); } println!("Deleted index \"{}\".", index_name); return Ok(()); @@ -212,12 +208,14 @@ fn main() -> Result<(), LittError> { // get index: let index_path = index_tracker .get_path(&index_name) - .map_err(|e| LittError(e.to_string()))?; + .map_err(|e| LittError::General(e.to_string()))?; let index = match Index::open(index_path.clone(), SearchSchema::default()) { Ok(index) => index, - Err(e) => return Err(LittError(e.to_string())), + Err(e) => return Err(LittError::General(e.to_string())), }; - let searcher = index.searcher().map_err(|e| LittError(e.to_string()))?; + let searcher = index + .searcher() + .map_err(|e| LittError::General(e.to_string()))?; // update existing index if cli.update { @@ -236,7 +234,7 @@ fn main() -> Result<(), LittError> { ); Ok(()) } - Err(e) => Err(LittError(e.to_string())), + Err(e) => Err(LittError::General(e.to_string())), }; } // reload existing index @@ -245,7 +243,7 @@ fn main() -> Result<(), LittError> { let old_num_docs = searcher.num_docs(); let start = Instant::now(); if let Err(e) = index.reload() { - return Err(LittError(e.to_string())); + return Err(LittError::General(e.to_string())); } println!( "Reload done. Successfully indexed {} new document pages in {:?}. Now {} document pages.", @@ -273,7 +271,7 @@ fn main() -> Result<(), LittError> { }; let results = match search.search(&search_term, cli.offset, cli.limit) { Ok(results) => results, - Err(e) => return Err(LittError(e.to_string())), + Err(e) => return Err(LittError::General(e.to_string())), }; println!("Found results in {} document(s):", results.len()); let mut fast_store_results: HashMap = HashMap::new(); @@ -300,7 +298,7 @@ fn main() -> Result<(), LittError> { ); let preview = match search.get_preview(page, &search_term) { Ok(preview) => preview, - Err(e) => return Err(LittError(e.to_string())), + Err(e) => return Err(LittError::General(e.to_string())), }; println!( " - [{}] p.{}: \"{}\", (score: {})", @@ -313,7 +311,7 @@ fn main() -> Result<(), LittError> { } } if let Err(e) = index_tracker.store_fast_results(fast_store_results) { - return Err(LittError(e.to_string())); + return Err(LittError::General(e.to_string())); } println!( "{} results from {} pages in {:?}.", diff --git a/litt/src/tracker.rs b/litt/src/tracker.rs index 75baaf5..bd31b45 100644 --- a/litt/src/tracker.rs +++ b/litt/src/tracker.rs @@ -1,36 +1,23 @@ use std::collections::HashMap; -use std::fmt::Formatter; +use std::fs; use std::path::{Path, PathBuf}; -use std::{fmt, fs}; +use thiserror::Error; use litt_shared::LITT_DIRECTORY_NAME; const INDICIES_FILENAME: &str = "indices.json"; const FAST_RESULTS_FILENAME: &str = "last_results.json"; -#[derive(Debug)] +#[derive(Debug, Error)] pub enum LittIndexTrackerError { + #[error("Unknown error reading from index-config: `{0}`")] UnknownError(String), + #[error("The given index `{0}` does not exist")] NotFound(String), + #[error("The index-config could not be stored: `{0}`")] SaveError(String), } -impl fmt::Display for LittIndexTrackerError { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - match &self { - LittIndexTrackerError::UnknownError(s) => { - write!(f, "Unknown error reading from index-config: {}", s) - } - LittIndexTrackerError::NotFound(s) => { - write!(f, "The given index {} does not exist", s) - } - LittIndexTrackerError::SaveError(s) => { - write!(f, "The index-config could not be stored: {}", s) - } - } - } -} - pub type Result = std::result::Result; pub struct IndexTracker { diff --git a/search/Cargo.toml b/search/Cargo.toml index 9af05b8..0f93c2b 100644 --- a/search/Cargo.toml +++ b/search/Cargo.toml @@ -8,6 +8,7 @@ crate-type = ["lib"] [dependencies] tantivy = { workspace = true } +thiserror = { workspace = true } litt_shared = { path = "../shared" } litt_index = { path = "../index" } diff --git a/search/src/lib.rs b/search/src/lib.rs index 487acf1..d9b819d 100644 --- a/search/src/lib.rs +++ b/search/src/lib.rs @@ -1,21 +1,13 @@ -use std::fmt; -use std::fmt::Formatter; +use thiserror::Error; pub mod search; -#[derive(Debug)] +#[derive(Debug, Error)] pub enum LittSearchError { + #[error("Error initializing new search: `{0}`")] InitError(String), + #[error("Error during search: `{0}`")] SearchError(String), } -impl fmt::Display for LittSearchError { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - match &self { - LittSearchError::InitError(s) => write!(f, "Error initializing new search: {}", s), - LittSearchError::SearchError(s) => write!(f, "Error during search: {}", s), - } - } -} - pub type Result = std::result::Result;