diff --git a/scripts/check-translations.py b/scripts/check-translations.py new file mode 100644 index 0000000..e48e4d1 --- /dev/null +++ b/scripts/check-translations.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python3 +"""Check the FWS translations files. + +Errors (exit status 1): + - a file is not valid TOML; + - a message has no "en" text (the fallback of every language); + - a language code does not look like an Anaconda one (fr, pt_BR, sr@latin); + - a translation does not use exactly the same {placeholders} as "en"; + - two files share a namespace (the first part of a key), which would leave + the code unsure of where a key lives; + - the code asks for a key that no file defines; + - in anaconda-translations.toml (texts added to Anaconda's own catalogs), a + translation whose placeholders, markup, keyboard shortcut or line breaks + differ from the English text. +Warnings: keys defined but never used. +The summary lists how many messages each language translates, per file. +""" + +import argparse +import pathlib +import re +import string +import sys +import tomllib + +REPO = pathlib.Path(__file__).resolve().parent.parent +TRANSLATIONS = REPO / "configs/baseline/airootfs/usr/local/share/fws" +DEFAULT_FILES = [TRANSLATIONS / "installer-translations.toml", + TRANSLATIONS / "system-translations.toml"] +ANACONDA_SUPPLEMENT = TRANSLATIONS / "anaconda-translations.toml" +CODE_ROOTS = [REPO / "configs/baseline/airootfs", REPO / "configs/releng/airootfs"] +CODE_SUFFIXES = {".py", ".sh", ".ks", ".qml", ".desktop", ".policy", ".json", ".ini", ".tmpl", ""} + +KEY = r"[a-z0-9_]+(?:\.[a-z0-9_]+)+" +LANGUAGE_CODE = re.compile(r"^[a-z]{2,3}(_[A-Z]{2})?(@[a-z]+)?$") +USAGES = [ + # t("key") in Python and QML. + re.compile(rf"""\bt\(\s*["']({KEY})["']"""), + # Shell: "fws:key" hands a key over to the installer's progress screen; + # fws-i18n prints one text; t comes from /usr/local/lib/fws/i18n.sh. + re.compile(rf"""\bfws:({KEY})\b"""), + re.compile(rf"""\bfws-i18n\s+(?:--catalog\s+\S+\s+)?({KEY})\b"""), + re.compile(rf"""(?:\$\(|^\s*)t\s+["']?({KEY})\b""", re.M), + # {{t:key}} markers of the configuration files rendered by the installer. + re.compile(rf"""\{{\{{t:({KEY})\}}\}}"""), + # Hyprland bind descriptions, translated by fws-keys when shown. + re.compile(rf"""^\s*bindd\s*=[^,\n]*,[^,\n]*,\s*({KEY})\s*,""", re.M), +] +# Whole prefixes: every key under them is used (translate-static-files.py). +PREFIX_USAGES = [ + re.compile(rf"""^X-FWS-Translation=({KEY})\s*$""", re.M), + re.compile(rf""""""), +] +# A quoted string that is exactly a key of a known namespace: a key kept in a +# table and passed to t() later. +QUOTED = re.compile(rf"""["']({KEY})["']""") + + +def flatten(table, prefix=""): + texts = {name: value for name, value in table.items() if not isinstance(value, dict)} + if texts and prefix: + yield prefix, texts + for name, value in table.items(): + if isinstance(value, dict): + yield from flatten(value, f"{prefix}.{name}" if prefix else name) + + +def placeholders(text): + return {field for _, field, _, _ in string.Formatter().parse(text) if field is not None} + + +def code_files(): + for root in CODE_ROOTS: + for path in root.rglob("*"): + if not path.is_file() or "__pycache__" in path.parts: + continue + if path.suffix not in CODE_SUFFIXES and path.name != ".xinitrc": + continue + if path.suffix == ".toml" or path.name == "translations.js": + continue + try: + yield path, path.read_text(encoding="utf-8") + except (UnicodeDecodeError, OSError): + continue + + +def used_keys(namespaces): + """({key: first file using it}, {prefix: first file using it}).""" + keys, prefixes = {}, {} + for path, text in code_files(): + where = path.relative_to(REPO) + for pattern in USAGES: + for match in pattern.finditer(text): + keys.setdefault(match.group(1), where) + for pattern in PREFIX_USAGES: + for match in pattern.finditer(text): + prefixes.setdefault(match.group(1), where) + for match in QUOTED.finditer(text): + if match.group(1).split(".", 1)[0] in namespaces: + keys.setdefault(match.group(1), where) + return keys, prefixes + + +def check_file(path, errors): + """{key: texts} of one file, its errors appended to `errors`.""" + try: + data = tomllib.loads(path.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError) as exc: + errors.append(f"{path.name}: {exc}") + return {}, {} + messages = dict(flatten(data)) + coverage = {} + for key, texts in messages.items(): + reference = texts.get("en") + if not isinstance(reference, str) or not reference: + errors.append(f"{key}: no \"en\" text") + continue + expected = placeholders(reference) + for language, text in texts.items(): + if not LANGUAGE_CODE.match(language): + errors.append(f"{key}: unexpected language code {language!r}") + continue + if not isinstance(text, str) or not text: + errors.append(f"{key}.{language}: empty or not a string") + continue + try: + found = placeholders(text) + except ValueError as exc: + errors.append(f"{key}.{language}: {exc}") + continue + if found != expected: + errors.append(f"{key}.{language}: placeholders {sorted(found)} " + f"instead of {sorted(expected)}") + coverage[language] = coverage.get(language, 0) + 1 + return messages, coverage + + +# Anaconda's texts use printf and str.format placeholders, Pango markup and +# GTK keyboard shortcuts ("_Root Password:"). +PRINTF = re.compile(r"%(?:\([^)]+\))?[-#0 +]*\d*(?:\.\d+)?[sdifgxXr]") +BRACES = re.compile(r"\{[^{}]*\}") +TAGS = re.compile(r"]*>") +MNEMONIC = re.compile(r"_(?=\w)") + + +def anaconda_signature(text): + return (sorted(PRINTF.findall(text)), sorted(BRACES.findall(text)), + sorted(re.sub(r"\s+", " ", tag) for tag in TAGS.findall(text)), + bool(MNEMONIC.search(text)), text.count("\n")) + + +def check_anaconda_supplement(path, errors): + """Summary line of anaconda-translations.toml, its errors appended.""" + try: + messages = tomllib.loads(path.read_text(encoding="utf-8")).get("message", []) + except (OSError, tomllib.TOMLDecodeError) as exc: + errors.append(f"{path.name}: {exc}") + return f"{path.name}: unreadable" + coverage = {} + for number, message in enumerate(messages, 1): + msgid = message.get("msgid") + if not isinstance(msgid, str) or not msgid: + errors.append(f"{path.name}: message {number} has no msgid") + continue + expected = anaconda_signature(msgid) + for language, text in message.items(): + if language in ("msgid", "context"): + continue + if not LANGUAGE_CODE.match(language) or not isinstance(text, str) or not text: + errors.append(f"{path.name}: {msgid[:40]!r}.{language}: bad language code or text") + continue + if anaconda_signature(text) != expected: + errors.append(f"{path.name}: {msgid[:40]!r}.{language}: placeholders, markup, " + "shortcut or line breaks differ from the English text") + coverage[language] = coverage.get(language, 0) + 1 + summary = ", ".join(f"{lang} {count}" for lang, count in + sorted(coverage.items(), key=lambda item: (-item[1], item[0]))) + return f"{path.name}: {len(messages)} texts — {summary or 'none'}" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--file", type=pathlib.Path, action="append", + help="file to check (repeatable; default: both catalogs)") + parser.add_argument("--skip-usage", action="store_true", + help="do not compare the keys with the code (checking a fragment)") + args = parser.parse_args() + + errors, warnings, summaries = [], [], [] + messages, owner = {}, {} + for path in args.file or DEFAULT_FILES: + file_messages, coverage = check_file(path, errors) + for key in file_messages: + namespace = key.split(".", 1)[0] + if owner.setdefault(namespace, path.name) != path.name: + errors.append(f"{key}: namespace {namespace!r} already used by {owner[namespace]}") + messages.update(file_messages) + total = len(file_messages) + summary = ", ".join(f"{lang} {count}/{total}" for lang, count in + sorted(coverage.items(), key=lambda item: (-item[1], item[0]))) + summaries.append(f"{path.name}: {total} messages — {summary or 'no translation'}") + + if not args.file and ANACONDA_SUPPLEMENT.exists(): + summaries.append(check_anaconda_supplement(ANACONDA_SUPPLEMENT, errors)) + + if not args.skip_usage: + used, prefixes = used_keys(set(owner)) + for prefix, where in prefixes.items(): + covered = [key for key in messages if key.startswith(prefix + ".")] + if not covered: + errors.append(f"{prefix}: used in {where} but no key starts with it") + for key in covered: + used.setdefault(key, where) + for key, where in sorted(used.items()): + if key not in messages: + errors.append(f"{key}: used in {where} but not defined") + for key in sorted(set(messages) - set(used)): + warnings.append(f"{key}: defined but never used") + + for line in warnings: + print(f"warning: {line}", file=sys.stderr) + for line in errors: + print(f"ERROR: {line}", file=sys.stderr) + print("\n".join(summaries)) + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main())