Skip to main content

egui_pop_i18n/
check.rs

1//! Checks a directory of catalogues (`<dir>/<locale>/*.ftl`): per
2//! locale, coverage, missing and orphan keys, and keys whose English
3//! changed since they were translated; across them, the faults that must
4//! fail a build.
5//!
6//! A key is one translatable unit: a message's value (`id`) or one of its
7//! attributes (`id.attr`).
8//!
9//! **Faults** (a build fails): a file that does not parse, a key defined
10//! twice in a locale, no English catalogue. Coverage, missing, orphan and
11//! changed keys are a report: a translation lags behind English, and that
12//! is normal. (Keys used by the code but absent in English are found by
13//! the extractor, [`crate::extract`].)
14//!
15//! **Changed English.** Each translated locale keeps a sidecar,
16//! `<dir>/<locale>/english.hashes`: one line per translated key, `key
17//! hash`, the hash of the English text the translation was made from. A
18//! key whose English hash differs now is reported as changed; a
19//! translated key with no recorded hash is reported as unstamped.
20//! [`stamp`] records the hashes of newly translated keys, or of every one
21//! once the changed translations were reviewed. A sidecar rather than
22//! comments in the `.ftl` files, so translation tools that rewrite
23//! comments cannot lose it.
24
25use std::collections::{BTreeMap, BTreeSet};
26use std::fmt;
27use std::fmt::Write as _;
28use std::io;
29use std::path::Path;
30
31use fluent_syntax::ast::{Entry, Identifier, Message, Pattern, Resource};
32
33use crate::locale::ENGLISH;
34
35/// The sidecar holding, per translated key, the hash of its English.
36pub const HASHES: &str = "english.hashes";
37
38/// One catalogue file.
39#[derive(Clone, Debug)]
40pub struct File {
41    pub locale: String,
42    pub name: String,
43    pub source: String,
44}
45
46/// The catalogues of a directory: its `.ftl` files and each locale's hashes.
47#[derive(Clone, Debug, Default)]
48pub struct Catalogs {
49    pub files: Vec<File>,
50    pub hashes: BTreeMap<String, BTreeMap<String, String>>,
51}
52
53impl Catalogs {
54    /// Reads `dir/<locale>/*.ftl` and `dir/<locale>/english.hashes`.
55    pub fn read(dir: &Path) -> io::Result<Self> {
56        let mut out = Self::default();
57        let mut locales: Vec<_> = std::fs::read_dir(dir)?
58            .filter_map(|e| e.ok().map(|e| e.path()))
59            .filter(|p| p.is_dir())
60            .collect();
61        locales.sort();
62        for ldir in locales {
63            let locale = ldir
64                .file_name()
65                .and_then(|n| n.to_str())
66                .unwrap_or_default();
67            let mut files: Vec<_> = std::fs::read_dir(&ldir)?
68                .filter_map(|e| e.ok().map(|e| e.path()))
69                .filter(|p| p.extension().is_some_and(|e| e == "ftl"))
70                .collect();
71            files.sort();
72            for f in files {
73                out.files.push(File {
74                    locale: locale.to_string(),
75                    name: f
76                        .file_name()
77                        .and_then(|n| n.to_str())
78                        .unwrap_or_default()
79                        .into(),
80                    source: std::fs::read_to_string(&f)?,
81                });
82            }
83            if let Ok(text) = std::fs::read_to_string(ldir.join(HASHES)) {
84                out.hashes.insert(locale.to_string(), parse_hashes(&text));
85            }
86        }
87        Ok(out)
88    }
89
90    fn locales(&self) -> BTreeSet<&str> {
91        self.files.iter().map(|f| f.locale.as_str()).collect()
92    }
93}
94
95/// What must fail a build.
96#[derive(Clone, Debug, PartialEq)]
97pub enum Fault {
98    Unparsable { file: String, errors: Vec<String> },
99    Duplicate { locale: String, key: String },
100    NoEnglish,
101}
102
103impl fmt::Display for Fault {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        match self {
106            Fault::Unparsable { file, errors } => {
107                write!(f, "{file} does not parse: {}", errors.join("; "))
108            }
109            Fault::Duplicate { locale, key } => write!(f, "{locale}: `{key}` is defined twice"),
110            Fault::NoEnglish => write!(f, "no English catalogue (en/*.ftl)"),
111        }
112    }
113}
114
115/// One translated locale against English.
116#[derive(Clone, Debug, Default, PartialEq)]
117pub struct LocaleReport {
118    pub locale: String,
119    /// English's keys.
120    pub english: usize,
121    /// English's keys this locale translates.
122    pub translated: usize,
123    /// In English, not translated.
124    pub missing: Vec<String>,
125    /// Translated, no longer in English.
126    pub orphans: Vec<String>,
127    /// Translated from an English text that has changed since.
128    pub changed: Vec<String>,
129    /// Translated, with no English hash recorded.
130    pub unstamped: Vec<String>,
131}
132
133impl LocaleReport {
134    /// The share of English's keys translated, in percent.
135    pub fn coverage(&self) -> f64 {
136        if self.english == 0 {
137            100.0
138        } else {
139            100.0 * self.translated as f64 / self.english as f64
140        }
141    }
142}
143
144#[derive(Clone, Debug, Default, PartialEq)]
145pub struct Report {
146    pub english: usize,
147    pub locales: Vec<LocaleReport>,
148    pub faults: Vec<Fault>,
149}
150
151impl fmt::Display for Report {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        writeln!(f, "en: {} keys", self.english)?;
154        for l in &self.locales {
155            writeln!(
156                f,
157                "{}: {:.1}% ({}/{}), {} missing, {} orphan, {} changed, {} unstamped",
158                l.locale,
159                l.coverage(),
160                l.translated,
161                l.english,
162                l.missing.len(),
163                l.orphans.len(),
164                l.changed.len(),
165                l.unstamped.len()
166            )?;
167            for (what, keys) in [
168                ("orphan", &l.orphans),
169                ("changed", &l.changed),
170                ("unstamped", &l.unstamped),
171            ] {
172                for k in keys {
173                    writeln!(f, "  {what}: {k}")?;
174                }
175            }
176        }
177        for fault in &self.faults {
178            writeln!(f, "fault: {fault}")?;
179        }
180        Ok(())
181    }
182}
183
184/// The keys of a source with the canonical text of each, or why it does
185/// not parse.
186fn units(source: &str) -> Result<Vec<(String, String)>, Vec<String>> {
187    let resource = fluent_syntax::parser::parse(source).map_err(|(_, errors)| {
188        errors
189            .iter()
190            .map(|e| {
191                let line = source[..e.pos.start.min(source.len())]
192                    .matches('\n')
193                    .count()
194                    + 1;
195                format!("line {line}: {}", e.kind)
196            })
197            .collect::<Vec<_>>()
198    })?;
199    let mut out = Vec::new();
200    for entry in &resource.body {
201        if let Entry::Message(m) = entry {
202            if let Some(v) = &m.value {
203                out.push((m.id.name.to_string(), canonical(v)));
204            }
205            for a in &m.attributes {
206                out.push((format!("{}.{}", m.id.name, a.id.name), canonical(&a.value)));
207            }
208        }
209    }
210    Ok(out)
211}
212
213/// A pattern as Fluent's serializer writes it: the same text, whatever
214/// its layout in the file.
215fn canonical(pattern: &Pattern<&str>) -> String {
216    let resource = Resource {
217        body: vec![Entry::Message(Message {
218            id: Identifier { name: "m" },
219            value: Some(pattern.clone()),
220            attributes: Vec::new(),
221            comment: None,
222        })],
223    };
224    fluent_syntax::serializer::serialize(&resource)
225}
226
227/// The hash recorded for an English text: 64-bit FNV-1a, in hex. Stable
228/// across Rust versions and platforms, unlike the standard hasher.
229pub fn hash(text: &str) -> String {
230    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
231    for b in text.bytes() {
232        h ^= u64::from(b);
233        h = h.wrapping_mul(0x0100_0000_01b3);
234    }
235    format!("{h:016x}")
236}
237
238fn parse_hashes(text: &str) -> BTreeMap<String, String> {
239    text.lines()
240        .map(str::trim)
241        .filter(|l| !l.is_empty() && !l.starts_with('#'))
242        .filter_map(|l| {
243            let (k, h) = l.split_once(char::is_whitespace)?;
244            Some((k.to_string(), h.trim().to_string()))
245        })
246        .collect()
247}
248
249/// The sidecar's text for a locale.
250pub fn write_hashes(hashes: &BTreeMap<String, String>) -> String {
251    let mut out = String::from(
252        "# The hash of the English text each key was translated from: a key\n\
253         # whose English changed since is reported by the catalogue check.\n",
254    );
255    for (k, h) in hashes {
256        let _ = writeln!(out, "{k} {h}");
257    }
258    out
259}
260
261/// Every locale's keys, with their canonical text; faults found on the way.
262fn keys(
263    catalogs: &Catalogs,
264    faults: &mut Vec<Fault>,
265) -> BTreeMap<String, BTreeMap<String, String>> {
266    let mut out: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
267    for file in &catalogs.files {
268        let locale = out.entry(file.locale.clone()).or_default();
269        match units(&file.source) {
270            Err(errors) => faults.push(Fault::Unparsable {
271                file: format!("{}/{}", file.locale, file.name),
272                errors,
273            }),
274            Ok(units) => {
275                for (key, text) in units {
276                    if locale.insert(key.clone(), text).is_some() {
277                        let fault = Fault::Duplicate {
278                            locale: file.locale.clone(),
279                            key,
280                        };
281                        if !faults.contains(&fault) {
282                            faults.push(fault);
283                        }
284                    }
285                }
286            }
287        }
288    }
289    out
290}
291
292/// Checks every locale against English.
293pub fn check(catalogs: &Catalogs) -> Report {
294    let mut faults = Vec::new();
295    let keys = keys(catalogs, &mut faults);
296    let Some(english) = keys.get(ENGLISH) else {
297        faults.push(Fault::NoEnglish);
298        return Report {
299            faults,
300            ..Report::default()
301        };
302    };
303    let none = BTreeMap::new();
304    let locales = catalogs
305        .locales()
306        .into_iter()
307        .filter(|l| *l != ENGLISH)
308        .map(|locale| {
309            let theirs = &keys[locale];
310            let hashes = catalogs.hashes.get(locale).unwrap_or(&none);
311            let mut r = LocaleReport {
312                locale: locale.to_string(),
313                english: english.len(),
314                ..LocaleReport::default()
315            };
316            for (key, text) in english {
317                if !theirs.contains_key(key) {
318                    r.missing.push(key.clone());
319                    continue;
320                }
321                r.translated += 1;
322                match hashes.get(key) {
323                    None => r.unstamped.push(key.clone()),
324                    Some(h) if *h != hash(text) => r.changed.push(key.clone()),
325                    Some(_) => {}
326                }
327            }
328            r.orphans = theirs
329                .keys()
330                .filter(|k| !english.contains_key(*k))
331                .cloned()
332                .collect();
333            r
334        })
335        .collect();
336    Report {
337        english: english.len(),
338        locales,
339        faults,
340    }
341}
342
343/// A locale's sidecar brought up to date: the hash of the current English
344/// for each translated key that has none (every translated key with
345/// `all`), keys no longer translated or no longer in English dropped.
346pub fn stamp(
347    catalogs: &Catalogs,
348    locale: &str,
349    all: bool,
350) -> Result<BTreeMap<String, String>, String> {
351    let mut faults = Vec::new();
352    let keys = keys(catalogs, &mut faults);
353    if let Some(f) = faults.first() {
354        return Err(f.to_string());
355    }
356    let english = keys
357        .get(ENGLISH)
358        .ok_or_else(|| Fault::NoEnglish.to_string())?;
359    let theirs = keys
360        .get(locale)
361        .ok_or_else(|| format!("no catalogue for `{locale}`"))?;
362    let old = catalogs.hashes.get(locale).cloned().unwrap_or_default();
363    Ok(theirs
364        .keys()
365        .filter_map(|k| {
366            let current = hash(english.get(k)?);
367            let h = match old.get(k) {
368                Some(h) if !all => h.clone(),
369                _ => current,
370            };
371            Some((k.clone(), h))
372        })
373        .collect())
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379
380    fn file(locale: &str, name: &str, source: &str) -> File {
381        File {
382            locale: locale.into(),
383            name: name.into(),
384            source: source.into(),
385        }
386    }
387
388    const EN: &str = "\
389panel-a =
390    .title = Graph
391panel-b =
392    .title = Queue
393panel-c =
394    .title = Log
395";
396
397    fn catalogs(fr: &str) -> Catalogs {
398        Catalogs {
399            files: vec![file("en", "panels.ftl", EN), file("fr", "panels.ftl", fr)],
400            hashes: BTreeMap::new(),
401        }
402    }
403
404    #[test]
405    fn missing_orphan_and_changed_keys_are_reported() {
406        let mut c = catalogs(
407            "panel-a =\n    .title = Graphe\npanel-b =\n    .title = File\npanel-z =\n    .title = Vieux\n",
408        );
409        let stamped = stamp(&c, "fr", false).unwrap();
410        assert_eq!(stamped.len(), 2, "{stamped:?}");
411        c.hashes.insert("fr".into(), stamped);
412        // English rewords the queue's title after its translation.
413        c.files[0].source = EN.replace("Queue", "Jobs");
414        let r = check(&c);
415        assert!(r.faults.is_empty(), "{r}");
416        let fr = &r.locales[0];
417        assert_eq!(fr.english, 3);
418        assert_eq!(fr.translated, 2);
419        assert_eq!(fr.missing, ["panel-c.title"]);
420        assert_eq!(fr.orphans, ["panel-z.title"]);
421        assert_eq!(fr.changed, ["panel-b.title"]);
422        assert!(fr.unstamped.is_empty());
423        assert!((fr.coverage() - 66.6).abs() < 0.1);
424        // Restamping everything accepts the reviewed translations.
425        let all = stamp(&c, "fr", true).unwrap();
426        c.hashes.insert("fr".into(), all);
427        assert!(check(&c).locales[0].changed.is_empty());
428    }
429
430    #[test]
431    fn unstamped_translations_are_listed() {
432        let r = check(&catalogs("panel-a =\n    .title = Graphe\n"));
433        assert_eq!(r.locales[0].unstamped, ["panel-a.title"]);
434    }
435
436    #[test]
437    fn unparsable_files_and_duplicates_are_faults() {
438        let mut c = catalogs("panel-a =\n    .title = Graphe\npanel-a =\n    .title = Encore\n");
439        c.files
440            .push(file("fr", "broken.ftl", "ok = fine\nbad = {\n"));
441        let r = check(&c);
442        assert_eq!(r.faults.len(), 2, "{r}");
443        assert!(matches!(&r.faults[0], Fault::Duplicate { key, .. } if key == "panel-a.title"));
444        assert!(matches!(&r.faults[1], Fault::Unparsable { file, .. } if file == "fr/broken.ftl"));
445        let r = check(&Catalogs {
446            files: vec![file("fr", "a.ftl", "a = b\n")],
447            ..Catalogs::default()
448        });
449        assert_eq!(r.faults, [Fault::NoEnglish]);
450    }
451
452    #[test]
453    fn the_hash_ignores_layout() {
454        let a = units("m =\n    .title = Graph\n").unwrap();
455        let b = units("m =\n    .title =\n        Graph\n").unwrap();
456        assert_eq!(hash(&a[0].1), hash(&b[0].1));
457        assert_eq!(hash(""), "cbf29ce484222325");
458    }
459
460    #[test]
461    fn egui_pops_catalogues_have_no_fault() {
462        let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("locales");
463        let r = check(&Catalogs::read(&dir).unwrap());
464        assert!(r.faults.is_empty(), "{r}");
465    }
466}