Skip to content

Commit

Permalink
refactor: use thiserror crate to implement custom errors (#67)
Browse files Browse the repository at this point in the history
* 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 34c1a5b.

* Revert "build: update tantivy"

This reverts commit c672c0a.
  • Loading branch information
SimonThormeyer authored May 3, 2024
1 parent 43a81c6 commit c8d84a9
Show file tree
Hide file tree
Showing 8 changed files with 58 additions and 85 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ shellexpand = "3.1.0"
uuid = "1.3.2"
colored = "2"
open = "4.1.0"
thiserror = "1.0"
1 change: 1 addition & 0 deletions index/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
30 changes: 11 additions & 19 deletions index/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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<T> = std::result::Result<T, LittIndexError>;
1 change: 1 addition & 0 deletions litt/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
68 changes: 33 additions & 35 deletions litt/src/main.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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 {
Expand Down Expand Up @@ -76,29 +70,29 @@ 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")
.arg("/c")
.arg("start")
.arg(&path)
.spawn()
.map_err(|e| LittError(e.to_string()))?;
.map_err(|e| LittError::General(e.to_string()))?;

Ok(())
}

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
Expand All @@ -108,7 +102,7 @@ fn main() -> Result<(), LittError> {
if let Ok(last_result) = &first_arg.trim().parse::<u32>() {
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)
Expand All @@ -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(());
}
Expand All @@ -145,23 +139,23 @@ 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: {}: ",
index_name,
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()
Expand All @@ -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(),
Expand All @@ -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(());
Expand All @@ -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 {
Expand All @@ -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
Expand All @@ -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.",
Expand Down Expand Up @@ -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<u32, (String, u32, String)> = HashMap::new();
Expand All @@ -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: {})",
Expand All @@ -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 {:?}.",
Expand Down
25 changes: 6 additions & 19 deletions litt/src/tracker.rs
Original file line number Diff line number Diff line change
@@ -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<T> = std::result::Result<T, LittIndexTrackerError>;

pub struct IndexTracker {
Expand Down
1 change: 1 addition & 0 deletions search/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ crate-type = ["lib"]

[dependencies]
tantivy = { workspace = true }
thiserror = { workspace = true }
litt_shared = { path = "../shared" }
litt_index = { path = "../index" }

16 changes: 4 additions & 12 deletions search/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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<T> = std::result::Result<T, LittSearchError>;

0 comments on commit c8d84a9

Please sign in to comment.