You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
meshcore-client/tools/l10n/check_arb.py

343 lines
12 KiB

#!/usr/bin/env python3
"""Fail the build when a translation would break or show the wrong text (#1323).
Compares every lib/l10n/app_<locale>.arb with the template, app_en.arb.
Fails on:
- a placeholder dropped, renamed or added compared with English;
- a broken plural or select (unbalanced braces, no `other` case, a repeated
case, an unknown plural category, or a plural over a placeholder English
does not declare as a number);
- an empty translation of a non-empty English string;
- a key, or its @metadata, that app_en.arb no longer has;
- a duplicate key, or an @@locale that does not match the file name;
- a translation identical to English (ignoring spacing), unless
it is allowed by
tools/l10n/l10n_check.json: `allow_identical` (reviewed, permanent) or
`pending_identical` (known untranslated, for the language batches of #1322).
A pending entry that is no longer identical fails too, so the list only
shrinks.
Reports, without failing, keys missing from a locale. `fail_on_missing` in the
config turns that into a failure once every locale is complete.
Parses messages the way `flutter gen-l10n` does with `use-escaping` off (the
l10n.yaml default): every brace is syntax. Fails outright if l10n.yaml turns
escaping on, rather than misreading quoted text.
Exit status: 0 when clean, 1 on any failure.
"""
from __future__ import annotations
import json
import os
import sys
from dataclasses import dataclass, field
L10N_DIR = os.path.join("lib", "l10n")
TEMPLATE = "app_en.arb"
CONFIG = os.path.join(os.path.dirname(os.path.abspath(__file__)), "l10n_check.json")
ICU_TYPES = ("plural", "select", "selectordinal")
PLURAL_CATEGORIES = {"zero", "one", "two", "few", "many", "other"}
NUMBER_TYPES = {"int", "num", "double"}
class MessageError(ValueError):
pass
@dataclass
class Message:
"""What a message references: every argument name, and its ICU blocks."""
names: set[str] = field(default_factory=set)
blocks: list[tuple[str, str, list[str]]] = field(default_factory=list)
text: str = ""
def parse_message(source: str) -> Message:
"""Parses one ARB message, raising MessageError when it is malformed."""
msg = Message()
end = _parse_body(source, 0, msg, nested=False)
if end != len(source):
raise MessageError(f"unexpected '}}' at {end}")
return msg
def _parse_body(s: str, i: int, msg: Message, nested: bool) -> int:
while i < len(s):
c = s[i]
if c == "{":
i = _parse_argument(s, i, msg)
elif c == "}":
if nested:
return i
raise MessageError(f"unexpected '}}' at {i}")
else:
msg.text += c
i += 1
if nested:
raise MessageError("unclosed '{'")
return i
def _skip_ws(s: str, i: int) -> int:
while i < len(s) and s[i].isspace():
i += 1
return i
def _read_word(s: str, i: int) -> tuple[str, int]:
start = i
while i < len(s) and (s[i].isalnum() or s[i] in "_="):
i += 1
return s[start:i], i
def _parse_argument(s: str, i: int, msg: Message) -> int:
open_at = i
i = _skip_ws(s, i + 1)
name, i = _read_word(s, i)
if not name or not (name[0].isalpha() or name[0] == "_"):
raise MessageError(f"bad argument name at {open_at}")
msg.names.add(name)
i = _skip_ws(s, i)
if i < len(s) and s[i] == "}":
return i + 1
if i >= len(s) or s[i] != ",":
raise MessageError(f"unclosed '{{{name}'")
i = _skip_ws(s, i + 1)
kind, i = _read_word(s, i)
if kind not in ICU_TYPES:
raise MessageError(f"'{{{name}, {kind}' is not plural, select or selectordinal")
i = _skip_ws(s, i)
if i >= len(s) or s[i] != ",":
raise MessageError(f"'{{{name}, {kind}' needs a ',' before its cases")
i += 1
cases: list[str] = []
while True:
i = _skip_ws(s, i)
if i >= len(s):
raise MessageError(f"unclosed '{{{name}, {kind}'")
if s[i] == "}":
i += 1
break
case, i = _read_word(s, i)
if not case:
raise MessageError(f"'{{{name}, {kind}' has a case with no name")
i = _skip_ws(s, i)
if i >= len(s) or s[i] != "{":
raise MessageError(f"case '{case}' of '{{{name}' has no '{{'")
i = _parse_body(s, i + 1, msg, nested=True) + 1
cases.append(case)
msg.blocks.append((name, kind, cases))
return i
def check_message(english: str, translated: str, placeholder_types: dict | None = None) -> list[str]:
"""Problems with one translated message, compared with its English source.
`placeholder_types` maps a placeholder to its type in app_en.arb's metadata.
"""
if english and not translated:
return ["empty translation"]
try:
en = parse_message(english)
except MessageError as e:
return [f"English message itself does not parse: {e}"]
try:
tr = parse_message(translated)
except MessageError as e:
return [f"does not parse: {e}"]
problems = []
dropped = sorted(en.names - tr.names)
added = sorted(tr.names - en.names)
if dropped:
problems.append("drops " + ", ".join("{" + n + "}" for n in dropped))
if added:
problems.append("adds " + ", ".join("{" + n + "}" for n in added))
english_blocks = {(name, kind) for name, kind, _ in en.blocks}
types = placeholder_types or {}
for name, kind, cases in tr.blocks:
if "other" not in cases:
problems.append(f"'{{{name}, {kind}' has no 'other' case")
repeated = sorted({c for c in cases if cases.count(c) > 1})
if repeated:
problems.append(f"'{{{name}, {kind}' repeats cases: {', '.join(repeated)}")
if kind != "select":
bad = [c for c in cases if c not in PLURAL_CATEGORIES and not _is_exact(c)]
if bad:
problems.append(f"'{{{name}, {kind}' has unknown cases: {', '.join(bad)}")
if (name, kind) not in english_blocks and types.get(name) not in NUMBER_TYPES:
problems.append(
f"'{{{name}, {kind}' counts a placeholder English does not declare as a number"
)
return problems
def same_text(a: str, b: str) -> bool:
"""True if two strings differ only in spacing. Case counts: German
capitalizes nouns, so "Min." can be the right translation of "min."."""
return " ".join(a.split()) == " ".join(b.split())
def _is_exact(case: str) -> bool:
return case.startswith("=") and case[1:].isdigit()
def has_words(message: str) -> bool:
"""True if the message has text a translator could change."""
try:
msg = parse_message(message)
except MessageError:
return True
return any(c.isalpha() for c in msg.text)
def load_arb(path: str) -> tuple[dict, list[str]]:
"""Loads an ARB, returning its entries and any duplicate keys."""
duplicates: list[str] = []
def pairs(items):
seen: dict = {}
for k, v in items:
if k in seen:
duplicates.append(k)
seen[k] = v
return seen
with open(path, encoding="utf-8") as fh:
return json.load(fh, object_pairs_hook=pairs), duplicates
def load_config(path: str = CONFIG) -> dict:
with open(path, encoding="utf-8") as fh:
config = json.load(fh)
return {
"allow_identical": config.get("allow_identical", {}),
"pending_identical": config.get("pending_identical", {}),
"fail_on_missing": bool(config.get("fail_on_missing", False)),
}
def _placeholder_types(template: dict, key: str) -> dict:
meta = template.get("@" + key)
placeholders = meta.get("placeholders", {}) if isinstance(meta, dict) else {}
return {name: spec.get("type") for name, spec in placeholders.items() if isinstance(spec, dict)}
def escaping_is_on(l10n_yaml: str) -> bool:
"""True if l10n.yaml turns on use-escaping, which this parser does not model."""
if not os.path.exists(l10n_yaml):
return False
with open(l10n_yaml, encoding="utf-8") as fh:
for line in fh:
key, _, value = line.partition(":")
setting = value.split("#")[0].strip().strip("'\"").lower()
if key.strip() == "use-escaping" and setting == "true":
return True
return False
def _allowed(table: dict, key: str, locale: str) -> bool:
locales = table.get(key)
return locales == "*" or (isinstance(locales, list) and locale in locales)
def check_locale(locale: str, data: dict, duplicates: list[str], template: dict, config: dict):
"""Returns (failures, missing keys) for one locale."""
failures = [f"duplicate key '{k}'" for k in duplicates]
if data.get("@@locale") != locale:
failures.append(f"@@locale is {data.get('@@locale')!r}, the file name says {locale!r}")
pending = set(config["pending_identical"].get(locale, []))
for key, value in data.items():
if key == "@@locale":
continue
if key.startswith("@"):
if key[1:] not in template:
failures.append(f"'{key}' is metadata for a key app_en.arb no longer has")
continue
if key not in template:
failures.append(f"'{key}' is not in app_en.arb")
continue
english = template[key]
if not isinstance(english, str):
continue
if not isinstance(value, str):
failures.append(f"'{key}' is not a string")
continue
for problem in check_message(english, value, _placeholder_types(template, key)):
failures.append(f"'{key}': {problem}")
if same_text(value, english) and has_words(english):
if key in pending:
continue
if not _allowed(config["allow_identical"], key, locale):
failures.append(
f"'{key}' is identical to English ({english!r}). Translate it, or add it "
"to allow_identical in tools/l10n/l10n_check.json if English is right here"
)
for key in sorted(pending):
if not isinstance(data.get(key), str) or not same_text(data[key], template.get(key, "")):
failures.append(
f"'{key}' is listed in pending_identical but is no longer identical to "
"English: remove it from tools/l10n/l10n_check.json"
)
missing = [k for k in template if not k.startswith("@") and k not in data]
return failures, missing
def run(l10n_dir: str = L10N_DIR, config_path: str = CONFIG, out=sys.stdout) -> int:
l10n_yaml = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(l10n_dir))), "l10n.yaml")
if escaping_is_on(l10n_yaml):
print(
"FAIL l10n.yaml: use-escaping is on, and this check parses messages as if it "
"were off. Teach tools/l10n/check_arb.py about quoted text first.",
file=out,
)
return 1
config = load_config(config_path)
template, template_dups = load_arb(os.path.join(l10n_dir, TEMPLATE))
failed = False
if template_dups:
failed = True
print(f"FAIL {TEMPLATE}: duplicate keys {', '.join(template_dups)}", file=out)
for key, value in template.items():
if key.startswith("@"):
continue
if not isinstance(value, str):
failed = True
print(f"FAIL {TEMPLATE}: '{key}' is not a string", file=out)
continue
try:
parse_message(value)
except MessageError as e:
failed = True
print(f"FAIL {TEMPLATE}: '{key}' does not parse: {e}", file=out)
names = sorted(f for f in os.listdir(l10n_dir) if f.startswith("app_") and f.endswith(".arb"))
for name in names:
if name == TEMPLATE:
continue
locale = name[len("app_") : -len(".arb")]
data, dups = load_arb(os.path.join(l10n_dir, name))
failures, missing = check_locale(locale, data, dups, template, config)
if missing and config["fail_on_missing"]:
failures.append(f"{len(missing)} keys missing: {', '.join(missing[:10])}")
for f in failures:
print(f"FAIL {name}: {f}", file=out)
failed = failed or bool(failures)
if missing and not config["fail_on_missing"]:
print(f"note {name}: {len(missing)} keys not translated yet", file=out)
print("check_arb: FAILED" if failed else "check_arb: OK", file=out)
return 1 if failed else 0
if __name__ == "__main__":
sys.stdout.reconfigure(encoding="utf-8")
raise SystemExit(run(*sys.argv[1:2]))

Powered by TurnKey Linux.