bnspell-api 0.1.0

HTTP API for the Bengali spell checker
Documentation
use std::path::{Path, PathBuf};

use bengali_spell_checker::SpellChecker;

pub fn dict_dir() -> Result<PathBuf, String> {
    match std::env::var("BNSPELL_DICT") {
        Ok(value) if !value.is_empty() => return Ok(PathBuf::from(value)),
        Ok(_) | Err(std::env::VarError::NotPresent) => {}
        Err(std::env::VarError::NotUnicode(_)) => {
            return Err("BNSPELL_DICT is not valid Unicode".to_string());
        }
    }
    let start = std::env::current_dir().map_err(|err| format!("current directory: {err}"))?;
    Ok(workspace_root_from(&start)?.join("packages/bengali-spell-checker/dictionary"))
}

pub fn load_checker(dir: &Path) -> Result<SpellChecker, String> {
    let aff = read_file(&dir.join("bn_BD.aff"))?;
    let dic = read_file(&dir.join("bn_BD.dic"))?;
    let mut checker = SpellChecker::new(&aff, &dic).map_err(|err| err.to_string())?;
    if let Some(freq) = read_if_file(&dir.join("bn_BD.freq"))? {
        checker = checker.with_frequencies(&freq);
    }
    if let Some(variants) = read_if_file(&dir.join("bn_BD.variants"))? {
        checker = checker.with_variants(&variants);
    }
    if let Some(removals) = read_if_file(&dir.join("bn_BD.removals"))? {
        checker = checker.with_removals(&removals);
    }
    if let Some(names) = read_if_file(&dir.join("bn_BD.names"))? {
        checker = checker.with_names(&names);
    }
    if let Some(compounds) = read_if_file(&dir.join("bn_BD.compounds"))? {
        checker = checker.with_compounds(&compounds);
    }
    Ok(checker)
}

fn read_if_file(path: &Path) -> Result<Option<String>, String> {
    if path.is_file() {
        read_file(path).map(Some)
    } else {
        Ok(None)
    }
}

fn workspace_root_from(start: &Path) -> Result<PathBuf, String> {
    let mut dir = start.to_path_buf();
    loop {
        let manifest = dir.join("Cargo.toml");
        if manifest.is_file() && is_workspace(&manifest) {
            return Ok(dir);
        }
        if !dir.pop() {
            return Err(
                "could not find a Cargo.toml with [workspace] by walking up from the current directory"
                    .to_string(),
            );
        }
    }
}

fn read_file(path: &Path) -> Result<String, String> {
    std::fs::read_to_string(path).map_err(|err| format!("read {}: {err}", path.display()))
}

fn is_workspace(path: &Path) -> bool {
    std::fs::read_to_string(path)
        .ok()
        .is_some_and(|text| text.lines().any(|line| line.trim() == "[workspace]"))
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::workspace_root_from;

    #[test]
    fn workspace_root_walks_up_from_this_crate() {
        let root = workspace_root_from(Path::new(env!("CARGO_MANIFEST_DIR"))).unwrap();
        assert!(root.join("Cargo.toml").is_file());
        assert!(root.join("packages/bengali-spell-checker").is_dir());
    }
}