use anyhow::Result;
use std::collections::HashSet;
use std::path::Path;
use parking_lot::Mutex;
use crate::processors::flush_words;
use crate::graph::Product;
pub struct WordManager {
custom_words: HashSet<String>,
words_to_add: Mutex<HashSet<String>>,
words_file: String,
header_line: Option<&'static str>,
}
impl WordManager {
pub fn new(
custom_words: HashSet<String>,
words_file: String,
header_line: Option<&'static str>,
) -> Self {
Self {
custom_words,
words_to_add: Mutex::new(HashSet::new()),
words_file,
header_line,
}
}
pub fn is_known(&self, word: &str) -> bool {
self.custom_words.contains(word)
}
pub fn handle_misspelled(
&self,
misspelled: &[impl AsRef<str>],
file: &Path,
auto_add_words: bool,
) -> Result<()> {
if misspelled.is_empty() {
return Ok(());
}
if auto_add_words {
let mut words_to_add = self.words_to_add.lock();
for word in misspelled {
words_to_add.insert(word.as_ref().to_lowercase());
}
drop(words_to_add);
Ok(())
} else {
let words: Vec<&str> = misspelled.iter().map(std::convert::AsRef::as_ref).collect();
anyhow::bail!(
"Misspelled words in {}:\n{}",
file.display(),
words.join("\n"),
)
}
}
pub fn flush(&self) -> Result<()> {
let words_to_add = self.words_to_add.lock();
let words_path = Path::new(&self.words_file);
flush_words(
&self.custom_words,
&words_to_add,
words_path,
self.header_line,
)
}
pub fn execute_with_flush(
&self,
product: &Product,
auto_add_words: bool,
check_fn: impl FnOnce(&Path) -> Result<()>,
processor_name: &str,
) -> Result<()> {
let result = check_fn(product.primary_input());
if auto_add_words
&& let Err(e) = self.flush()
{
eprintln!("Warning: failed to flush {processor_name} words file: {e}");
}
result
}
pub fn execute_batch_with_flush(
&self,
products: &[&Product],
auto_add_words: bool,
check_fn: impl Fn(&Path) -> Result<()>,
processor_name: &str,
) -> Vec<Result<()>> {
let results: Vec<Result<()>> = products
.iter()
.map(|p| check_fn(p.primary_input()))
.collect();
if auto_add_words
&& let Err(e) = self.flush()
{
eprintln!("Warning: failed to flush {processor_name} words file: {e}");
}
results
}
}