bnspell-cli 0.1.0

Command-line Bengali (Bangla) spell checker
use std::path::{Path, PathBuf};

use bengali_spell_checker::SpellChecker;

pub fn current_dir() -> Result<PathBuf, String> {
    std::env::current_dir().map_err(|err| format!("current directory: {err}"))
}

pub 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(),
            );
        }
    }
}

pub fn resolve_dict(start: &Path, flag: Option<&Path>) -> Result<PathBuf, String> {
    let env = match std::env::var("BNSPELL_DICT") {
        Ok(value) => Ok(Some(value)),
        Err(std::env::VarError::NotPresent) => Ok(None),
        Err(std::env::VarError::NotUnicode(_)) => {
            Err("BNSPELL_DICT is not valid Unicode".to_string())
        }
    }?;
    resolve_dict_from(start, flag, env)
}

fn resolve_dict_from(
    start: &Path,
    flag: Option<&Path>,
    env: Option<String>,
) -> Result<PathBuf, String> {
    if let Some(dir) = flag {
        return Ok(dir.to_path_buf());
    }
    if let Some(value) = env.filter(|value| !value.is_empty()) {
        return Ok(PathBuf::from(value));
    }
    Ok(workspace_root_from(start)?.join("packages/bengali-spell-checker/dictionary"))
}

pub fn package_dir(start: &Path) -> Result<PathBuf, String> {
    Ok(workspace_root_from(start)?.join("packages/bengali-spell-checker"))
}

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

pub struct DictText {
    pub aff: String,
    pub dic: String,
    pub freq: Option<String>,
    pub variants: Option<String>,
    pub removals: Option<String>,
    pub names: Option<String>,
    pub compounds: Option<String>,
}

pub fn read_resources(dir: &Path) -> Result<DictText, String> {
    Ok(DictText {
        aff: read_file(&dir.join("bn_BD.aff"))?,
        dic: read_file(&dir.join("bn_BD.dic"))?,
        freq: read_if_file(&dir.join("bn_BD.freq"))?,
        variants: read_if_file(&dir.join("bn_BD.variants"))?,
        removals: read_if_file(&dir.join("bn_BD.removals"))?,
        names: read_if_file(&dir.join("bn_BD.names"))?,
        compounds: read_if_file(&dir.join("bn_BD.compounds"))?,
    })
}

pub fn checker_from(files: &DictText) -> Result<SpellChecker, String> {
    let mut checker = SpellChecker::new(&files.aff, &files.dic).map_err(|err| err.to_string())?;
    if let Some(freq) = files.freq.as_deref() {
        checker = checker.with_frequencies(freq);
    }
    if let Some(variants) = files.variants.as_deref() {
        checker = checker.with_variants(variants);
    }
    if let Some(removals) = files.removals.as_deref() {
        checker = checker.with_removals(removals);
    }
    if let Some(names) = files.names.as_deref() {
        checker = checker.with_names(names);
    }
    if let Some(compounds) = files.compounds.as_deref() {
        checker = checker.with_compounds(compounds);
    }
    Ok(checker)
}

pub fn load_checker(dir: &Path) -> Result<SpellChecker, String> {
    checker_from(&read_resources(dir)?)
}

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

pub fn read_input(path: Option<&Path>) -> Result<String, String> {
    match path {
        None => read_stdin(),
        Some(path) if path == Path::new("-") => read_stdin(),
        Some(path) => read_file(path),
    }
}

fn read_stdin() -> Result<String, String> {
    use std::io::Read;
    let mut buf = String::new();
    std::io::stdin()
        .read_to_string(&mut buf)
        .map_err(|err| format!("read stdin: {err}"))?;
    Ok(buf)
}

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/src/normalize.ts")
                .is_file()
        );
    }

    #[test]
    fn dict_flag_beats_the_env_var_and_the_env_var_beats_the_workspace() {
        let start = Path::new(env!("CARGO_MANIFEST_DIR"));
        let flagged =
            super::resolve_dict_from(start, Some(Path::new("/opt/dict")), Some("/env".into()))
                .unwrap();
        assert_eq!(flagged, Path::new("/opt/dict"));
        let from_env = super::resolve_dict_from(start, None, Some("/env".into())).unwrap();
        assert_eq!(from_env, Path::new("/env"));
        let from_workspace = super::resolve_dict_from(start, None, Some(String::new())).unwrap();
        assert!(from_workspace.ends_with("packages/bengali-spell-checker/dictionary"));
    }
}