#!/usr/bin/env python3 """Write the app's string resources: English from `strings.py`, the eight translations from the server's catalogues and `strings_own.json`. See `strings.py` for the rule. scripts/gen-strings.py the catalogues at that ref of the server's git checkout (../LLeMbas, or LEMBAS_SERVER) -- the same ref the contract and the tokens are pinned to scripts/gen-strings.py the server's working tree as it is scripts/gen-strings.py --check fail if a key the code uses has no English, or the other way round A ref, not the working tree, is the way to regenerate: the server's checkout is shared, and whatever is uncommitted in it is not what a released server says. """ from __future__ import annotations import importlib.util import json import os import re import subprocess import sys from pathlib import Path from xml.sax.saxutils import escape ROOT = Path(__file__).resolve().parent.parent SERVER = Path(os.environ.get("LEMBAS_SERVER", ROOT.parent / "LLeMbas")) RES = ROOT / "app/src/main/res" LANGS = ("cs", "de", "es", "fr", "hu", "it", "pl", "sk") HEADER = "" sys.path.insert(0, str(Path(__file__).parent)) from strings import SERVER_ENGLISH, STRINGS # noqa: E402 def android(text: str) -> str: """Escaped for a : XML, then Android's own apostrophe and quote rules.""" return escape(text).replace("'", "\\'").replace('"', '\\"') def server_catalogue(code: str, ref: str | None = None) -> dict[str, str]: path = SERVER / "src/lembas/web/i18n" / f"{code}.py" if ref: shown = subprocess.run( ["git", "-C", str(SERVER), "show", f"{ref}:src/lembas/web/i18n/{code}.py"], capture_output=True, text=True, ) if shown.returncode != 0: return {} scope: dict = {"__name__": f"catalogue_{code}"} exec(compile(shown.stdout, f"{ref}:{code}.py", "exec"), scope) # the server's own file return dict(scope.get("MESSAGES", {})) if not path.exists(): return {} spec = importlib.util.spec_from_file_location(f"catalogue_{code}", path) module = importlib.util.module_from_spec(spec) sys.dont_write_bytecode = True spec.loader.exec_module(module) return dict(getattr(module, "MESSAGES", {})) def numbered(server_english: str, translation: str) -> str: """A server translation with its named placeholders (`%(n)s`) numbered as Android's (`%1$s`), in the order the server's English names them. `%%` stays as it is: both write a percent sign that way.""" names: list[str] = [] for name in re.findall(r"%\((\w+)\)s", server_english): if name not in names: names.append(name) for i, name in enumerate(names, start=1): translation = translation.replace(f"%({name})s", f"%{i}$s") return translation def server_text(catalogue: dict[str, str], key: str, english: str) -> str | None: """The server's translation of a sentence: by the app's English, or by the server's own English for it (`SERVER_ENGLISH`), placeholders numbered.""" if english in catalogue: return catalogue[english] source = SERVER_ENGLISH.get(key) if source and source in catalogue: text = numbered(source, catalogue[source]) return None if "%(" in text else text return None def used_keys() -> set[str]: keys: set[str] = set() for path in (ROOT / "app/src").rglob("*"): if path.suffix in (".kt", ".xml") and "/res/values" not in str(path): keys |= set(re.findall(r"(?:R\.string\.|@string/)([a-z_]+)", path.read_text(errors="ignore"))) return keys def write(folder: Path, entries: dict[str, str]) -> None: folder.mkdir(parents=True, exist_ok=True) lines = ['', HEADER, ""] for key, text in entries.items(): extra = ' translatable="false"' if key == "app_name" else "" lines.append(f' {android(text)}') lines.append("") (folder / "strings.xml").write_text("\n".join(lines) + "\n", encoding="utf-8") def write_locale_config() -> None: """`res/xml/locales_config.xml`: the languages the app has, for Android 13+'s per-app language (the manifest's `android:localeConfig`). Written from LANGS, so it cannot list a language the app has no strings for, or miss one it has.""" lines = ['', HEADER.replace("Edit scripts/strings.py or strings_own.json", "Edit LANGS there"), '', ' '] lines += [f' ' for code in LANGS] lines.append("") (RES / "xml/locales_config.xml").write_text("\n".join(lines) + "\n", encoding="utf-8") def main() -> None: used = used_keys() missing = sorted(used - set(STRINGS)) unused = sorted(set(STRINGS) - used) if missing or unused: print(f"gen-strings: used but not in strings.py: {missing}; in strings.py but unused: {unused}") if "--check" in sys.argv or missing: sys.exit(1) if "--check" in sys.argv: print(f"gen-strings: {len(STRINGS)} strings, all used") return args = [a for a in sys.argv[1:] if not a.startswith("--")] ref = None if args: ref = subprocess.run( ["git", "-C", str(SERVER), "rev-parse", "--verify", f"{args[0]}^{{commit}}"], capture_output=True, text=True, check=True, ).stdout.strip() own = json.loads((Path(__file__).parent / "strings_own.json").read_text(encoding="utf-8")) write(RES / "values", STRINGS) write_locale_config() for code in LANGS: catalogue = server_catalogue(code, ref) mine = own.get(code, {}) out = {} for key, english in STRINGS.items(): if key == "app_name": continue text = mine.get(key) or server_text(catalogue, key, english) if text and all(text.count(f"%{i}$s") == english.count(f"%{i}$s") for i in (1, 2, 3)): out[key] = text write(RES / f"values-{code}", out) print(f"gen-strings: {code}: {len(out)}/{len(STRINGS) - 1}" + (f" (server {ref[:12]})" if ref else "")) if __name__ == "__main__": main()