1use std::path::{Path, PathBuf};
2
3use bengali_spell_checker::SpellChecker;
4
5pub fn dict_dir() -> Result<PathBuf, String> {
6 match std::env::var("BNSPELL_DICT") {
7 Ok(value) if !value.is_empty() => return Ok(PathBuf::from(value)),
8 Ok(_) | Err(std::env::VarError::NotPresent) => {}
9 Err(std::env::VarError::NotUnicode(_)) => {
10 return Err("BNSPELL_DICT is not valid Unicode".to_string());
11 }
12 }
13 let start = std::env::current_dir().map_err(|err| format!("current directory: {err}"))?;
14 Ok(workspace_root_from(&start)?.join("packages/bengali-spell-checker/dictionary"))
15}
16
17pub fn load_checker(dir: &Path) -> Result<SpellChecker, String> {
18 let aff = read_file(&dir.join("bn_BD.aff"))?;
19 let dic = read_file(&dir.join("bn_BD.dic"))?;
20 let mut checker = SpellChecker::new(&aff, &dic).map_err(|err| err.to_string())?;
21 if let Some(freq) = read_if_file(&dir.join("bn_BD.freq"))? {
22 checker = checker.with_frequencies(&freq);
23 }
24 if let Some(variants) = read_if_file(&dir.join("bn_BD.variants"))? {
25 checker = checker.with_variants(&variants);
26 }
27 if let Some(removals) = read_if_file(&dir.join("bn_BD.removals"))? {
28 checker = checker.with_removals(&removals);
29 }
30 if let Some(names) = read_if_file(&dir.join("bn_BD.names"))? {
31 checker = checker.with_names(&names);
32 }
33 if let Some(compounds) = read_if_file(&dir.join("bn_BD.compounds"))? {
34 checker = checker.with_compounds(&compounds);
35 }
36 Ok(checker)
37}
38
39fn read_if_file(path: &Path) -> Result<Option<String>, String> {
40 if path.is_file() {
41 read_file(path).map(Some)
42 } else {
43 Ok(None)
44 }
45}
46
47fn workspace_root_from(start: &Path) -> Result<PathBuf, String> {
48 let mut dir = start.to_path_buf();
49 loop {
50 let manifest = dir.join("Cargo.toml");
51 if manifest.is_file() && is_workspace(&manifest) {
52 return Ok(dir);
53 }
54 if !dir.pop() {
55 return Err(
56 "could not find a Cargo.toml with [workspace] by walking up from the current directory"
57 .to_string(),
58 );
59 }
60 }
61}
62
63fn read_file(path: &Path) -> Result<String, String> {
64 std::fs::read_to_string(path).map_err(|err| format!("read {}: {err}", path.display()))
65}
66
67fn is_workspace(path: &Path) -> bool {
68 std::fs::read_to_string(path)
69 .ok()
70 .is_some_and(|text| text.lines().any(|line| line.trim() == "[workspace]"))
71}
72
73#[cfg(test)]
74mod tests {
75 use std::path::Path;
76
77 use super::workspace_root_from;
78
79 #[test]
80 fn workspace_root_walks_up_from_this_crate() {
81 let root = workspace_root_from(Path::new(env!("CARGO_MANIFEST_DIR"))).unwrap();
82 assert!(root.join("Cargo.toml").is_file());
83 assert!(root.join("packages/bengali-spell-checker").is_dir());
84 }
85}