use crate::models::entry::{Entries, Entry};
use crate::strings;
#[derive(Debug, Clone, Copy)]
pub struct PreProcessor;
impl PreProcessor {
pub fn run<O>(entries: &mut Entries, options: O)
where
O: Into<PreProcessOptions>,
{
let options: PreProcessOptions = options.into();
for entry in entries.values_mut() {
Self::sort_annotations(entry);
if options.extract_tags {
Self::extract_tags(entry);
}
if options.normalize_whitespace {
Self::normalize_whitespace(entry);
}
if options.convert_all_to_ascii {
Self::convert_all_to_ascii(entry);
}
if options.convert_symbols_to_ascii {
Self::convert_symbols_to_ascii(entry);
}
}
}
pub fn sort_annotations(entry: &mut Entry) {
entry.annotations.sort();
}
fn extract_tags(entry: &mut Entry) {
for annotation in &mut entry.annotations {
annotation.tags = strings::extract_tags(&annotation.notes);
annotation.notes = strings::remove_tags(&annotation.notes);
}
}
fn normalize_whitespace(entry: &mut Entry) {
for annotation in &mut entry.annotations {
annotation.body = strings::normalize_whitespace(&annotation.body);
}
}
fn convert_all_to_ascii(entry: &mut Entry) {
entry.book.title = strings::convert_all_to_ascii(&entry.book.title);
entry.book.author = strings::convert_all_to_ascii(&entry.book.author);
for annotation in &mut entry.annotations {
annotation.body = strings::convert_all_to_ascii(&annotation.body);
}
}
fn convert_symbols_to_ascii(entry: &mut Entry) {
entry.book.title = strings::convert_symbols_to_ascii(&entry.book.title);
entry.book.author = strings::convert_symbols_to_ascii(&entry.book.author);
for annotation in &mut entry.annotations {
annotation.body = strings::convert_symbols_to_ascii(&annotation.body);
}
}
}
#[derive(Debug, Clone, Copy)]
#[allow(clippy::struct_excessive_bools)]
pub struct PreProcessOptions {
pub extract_tags: bool,
pub normalize_whitespace: bool,
pub convert_all_to_ascii: bool,
pub convert_symbols_to_ascii: bool,
}
#[cfg(test)]
mod test {
use super::*;
mod tags {
use super::*;
use crate::models::annotation::Annotation;
use crate::models::book::Book;
#[test]
fn extract() {
let mut entry = Entry {
book: Book::default(),
annotations: vec![
Annotation {
notes: "#tag01 #tag02".to_string(),
..Default::default()
},
Annotation {
notes: "#tag02 #tag03".to_string(),
..Default::default()
},
Annotation {
notes: "#tag03 #tag01".to_string(),
..Default::default()
},
],
};
PreProcessor::extract_tags(&mut entry);
for annotation in entry.annotations {
assert_eq!(annotation.tags.len(), 2);
assert!(annotation.notes.is_empty());
}
}
}
}