okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-web: the served web chat page for 0.2.75d9f47922

main
7.7 KiB203 linesraw
1"""The web page's translations: read the English text out of serve/web, write locales/en.json, check the catalogs.
2
3    python tools/web_i18n.py            # check every catalog against the text in the code (exit 1 on a problem)
4    python tools/web_i18n.py --write    # also rewrite serve/web/locales/en.json from the code
5
6The English text lives in the code (see serve/web/i18n.js):
7    tr("key", "English text", vars)                          in serve/web/*.js
8    tr("key", {one: "{n} chat", other: "{n} chats"}, vars)   a plural
9    <span data-i18n="key">English text</span>                in serve/web/index.html (also data-i18n-title, -label, -placeholder)
10Both must be plain string literals (no template strings, no joined strings), so that this reader and a translator see
11the same text. serve/test_web_i18n.py runs the check.
12"""
13from __future__ import annotations
14
15import html.parser
16import json
17import re
18import sys
19from pathlib import Path
20
21WEB = Path(__file__).resolve().parents[1] / "serve" / "web"
22LOCALES = WEB / "locales"
23PLACEHOLDER = re.compile(r"\{(\w+)\}")
24CALL = re.compile(r"(?<![\w.$])tr\(\s*\"([\w.\-]+)\"\s*,\s*")
25PLURAL_CATEGORIES = ("zero", "one", "two", "few", "many", "other")
26
27
28class Problem(Exception):
29    pass
30
31
32def _string(src: str, i: int):
33    """A double-quoted JS string literal at src[i]: (the text, the index after it)."""
34    if src[i] != '"':
35        raise Problem(f"expected a string literal at: {src[i:i + 40]!r}")
36    j = i + 1
37    while j < len(src):
38        if src[j] == "\\":
39            j += 2
40            continue
41        if src[j] == '"':
42            try:
43                return json.loads(src[i:j + 1]), j + 1
44            except ValueError as e:
45                raise Problem(f"not a plain string literal ({e}): {src[i:j + 1]!r}")
46        j += 1
47    raise Problem("unterminated string literal")
48
49
50def _plural(src: str, i: int):
51    """{one: "...", other: "..."} at src[i]."""
52    j = i + 1
53    out = {}
54    while True:
55        m = re.compile(r"\s*(\w+)\s*:\s*").match(src, j)
56        if not m:
57            raise Problem(f"expected a plural form at: {src[j:j + 40]!r}")
58        text, j = _string(src, m.end())
59        out[m.group(1)] = text
60        m = re.compile(r"\s*([,}])").match(src, j)
61        if not m:
62            raise Problem(f"expected , or }} after a plural form at: {src[j:j + 40]!r}")
63        j = m.end()
64        if m.group(1) == "}":
65            break
66    if "other" not in out:
67        raise Problem(f"a plural needs an 'other' form: {out}")
68    return out, j
69
70
71def js_strings(src: str, name: str = "?") -> dict:
72    found = {}
73    for m in CALL.finditer(src):
74        key = m.group(1)
75        i = m.end()
76        try:
77            value, _ = _plural(src, i) if src[i] == "{" else _string(src, i)
78        except Problem as e:
79            line = src.count("\n", 0, m.start()) + 1
80            raise Problem(f"{name}:{line}: tr({key!r}): {e}")
81        found[key] = value
82    return found
83
84
85class _Html(html.parser.HTMLParser):
86    ATTRS = {"data-i18n-title": "title", "data-i18n-label": "aria-label", "data-i18n-placeholder": "placeholder"}
87
88    def __init__(self):
89        super().__init__(convert_charrefs=True)
90        self.found: dict = {}
91        self.open = []          # [(tag, key, [text])]
92
93    def handle_starttag(self, tag, attrs):
94        a = dict(attrs)
95        for mark, attr in self.ATTRS.items():
96            if mark in a:
97                self.found[a[mark]] = a.get(attr) or ""
98        if "data-i18n" in a:
99            self.open.append((tag, a["data-i18n"], []))
100        elif self.open:
101            self.open.append((tag, None, self.open[-1][2]))
102
103    def handle_data(self, data):
104        if self.open:
105            self.open[-1][2].append(data)
106
107    def handle_endtag(self, tag):
108        if self.open and self.open[-1][0] == tag:
109            _, key, text = self.open.pop()
110            if key:
111                self.found[key] = " ".join("".join(text).split())
112
113
114def html_strings(src: str) -> dict:
115    p = _Html()
116    p.feed(src)
117    return p.found
118
119
120def english() -> dict:
121    """Every key in serve/web with its English text; the same key twice must have the same text."""
122    out: dict = {}
123    sources = {p.name: js_strings(p.read_text(encoding="utf-8"), p.name) for p in sorted(WEB.glob("*.js")) if p.name != "i18n.js"}
124    sources["index.html"] = html_strings((WEB / "index.html").read_text(encoding="utf-8"))
125    for name, found in sources.items():
126        for key, value in found.items():
127            if key in out and out[key] != value:
128                raise Problem(f"{key!r} has two different English texts (one is in {name})")
129            out[key] = value
130    return dict(sorted(out.items()))
131
132
133def languages() -> list:
134    src = (WEB / "i18n.js").read_text(encoding="utf-8")
135    block = re.search(r"const LANGUAGES = (\[.*?\]);", src, re.S).group(1)
136    return [m for m in re.findall(r'\["([\w-]+)",', block)]
137
138
139def placeholders(value) -> set:
140    forms = value.values() if isinstance(value, dict) else [value]
141    return {name for form in forms for name in PLACEHOLDER.findall(form)}
142
143
144def check_catalog(code: str, catalog: dict, en: dict) -> list:
145    problems = []
146    for key in sorted(set(en) - set(catalog)):
147        problems.append(f"{code}: missing {key!r}")
148    for key in sorted(set(catalog) - set(en)):
149        problems.append(f"{code}: {key!r} is not in the page (renamed or removed?)")
150    for key, value in catalog.items():
151        if key not in en:
152            continue
153        forms = value if isinstance(value, dict) else {"": value}
154        if isinstance(value, dict):
155            bad = [c for c in value if c not in PLURAL_CATEGORIES]
156            if bad or "other" not in value:
157                problems.append(f"{code}: {key!r}: plural forms must be CLDR names with an 'other' form, got {sorted(value)}")
158            if not isinstance(en[key], dict):
159                problems.append(f"{code}: {key!r} is a plural here but not in the code")
160        elif isinstance(en[key], dict):
161            problems.append(f"{code}: {key!r} is a plain text here but a plural in the code")
162        for form, text in forms.items():
163            if not isinstance(text, str) or not text.strip():
164                problems.append(f"{code}: {key!r} {form} is empty or not a string")
165        if placeholders(value) != placeholders(en[key]) and not (
166                isinstance(value, dict) and isinstance(en[key], dict)
167                and all(placeholders(f) <= placeholders(en[key]) for f in value.values())):
168            problems.append(f"{code}: {key!r} uses {sorted(placeholders(value))}, the code uses {sorted(placeholders(en[key]))}")
169    return problems
170
171
172def check(write: bool = False) -> list:
173    en = english()
174    if write:
175        LOCALES.mkdir(exist_ok=True)
176        (LOCALES / "en.json").write_text(json.dumps(en, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
177    problems = []
178    on_disk = LOCALES / "en.json"
179    if not on_disk.is_file() or json.loads(on_disk.read_text(encoding="utf-8")) != en:
180        problems.append("en.json is not the text in the code (python tools/web_i18n.py --write)")
181    for code in languages():
182        if code == "en":
183            continue
184        f = LOCALES / f"{code}.json"
185        if not f.is_file():
186            problems.append(f"{code}: serve/web/locales/{code}.json is missing")
187            continue
188        problems += check_catalog(code, json.loads(f.read_text(encoding="utf-8")), en)
189    for f in sorted(LOCALES.glob("*.json")):
190        if f.stem not in languages():
191            problems.append(f"{f.name}: not in LANGUAGES of serve/web/i18n.js")
192    return problems
193
194
195if __name__ == "__main__":
196    try:
197        problems = check(write="--write" in sys.argv)
198    except Problem as e:
199        print(f"web_i18n: {e}")
200        sys.exit(1)
201    for p in problems:
202        print("web_i18n:", p)
203    sys.exit(1 if problems else 0)