#!/usr/bin/env python3 """Check the nine native catalogs against the English base and the Kotlin call sites.""" from __future__ import annotations import json from collections import Counter from pathlib import Path import re import sys ROOT = Path(__file__).resolve().parents[1] RESOURCES = ROOT / "app/src/main/assets/localization" LANGUAGES = ("en", "zh-Hans", "zh-Hant", "zh-HK", "ja", "ko", "th", "id", "ms") QUOTED = r'"(?:\\.|[^"\\])*"' ENTRY = re.compile(rf"({QUOTED})\s*=\s*({QUOTED})\s*;") CALL = re.compile(r"L10n\.(?:text|format)\(\s*") # Loan words and acronyms that are correctly identical across languages. SHARED_WORD_KEYS = { "board.eventKind", "timer.live", "timer.accessibility", "settings.data", "groups.edit", "groupEditor.previewTickets", "groupEditor.secondsPlaceholder", } PLACEHOLDER = re.compile( r"%(?:(?P\d+)\$)?[-+ #0']*" r"(?:\d+|\*(?:\d+\$)?)?(?:\.(?:\d+|\*(?:\d+\$)?))?" r"(?Phh|ll|[hljztL])?(?P[@diuoxXfFeEgGaAcCsSpn])" ) def load(path: Path) -> dict[str, str]: source = path.read_text(encoding="utf-8") matches = list(ENTRY.finditer(source)) keys = [json.loads(match.group(1)) for match in matches] duplicates = [key for key, count in Counter(keys).items() if count > 1] if duplicates: raise ValueError(f"{path.name}: duplicate keys: {', '.join(duplicates)}") rest = ENTRY.sub("", source) leftover = [line for line in rest.splitlines() if line.strip() and not line.strip().startswith("//")] if leftover: raise ValueError(f"{path.name}: unexpected content: {leftover[0][:60]}") return {json.loads(m.group(1)): json.loads(m.group(2)) for m in matches} def arguments(value: str) -> Counter[tuple[int, str]]: """Order-independent positional signature of the printf placeholders.""" value = value.replace("%%", "") signature: Counter[tuple[int, str]] = Counter() next_position = 1 for match in PLACEHOLDER.finditer(value): position = int(match.group("position") or next_position) signature[(position, (match.group("length") or "") + match.group("type"))] += 1 if not match.group("position"): next_position += 1 return signature def referenced_keys(source: str) -> set[str]: keys: set[str] = set() quoted = re.compile(QUOTED) for call in CALL.finditer(source): position = call.end() depth = 0 while position < len(source): literal = quoted.match(source, position) if literal: keys.add(json.loads(literal.group())) position = literal.end() continue character = source[position] if depth == 0 and character in ",)": break if character == "(": depth += 1 elif character == ")": depth -= 1 position += 1 return keys def main() -> int: try: catalogs = {language: load(RESOURCES / f"{language}.strings") for language in LANGUAGES} except (OSError, ValueError) as error: print(f"Localization verification failed: {error}", file=sys.stderr) return 1 base = catalogs["en"] errors: list[str] = [] for language, values in catalogs.items(): missing = base.keys() - values.keys() extra = values.keys() - base.keys() if missing: errors.append(f"{language}: missing keys: {', '.join(sorted(missing))}") if extra: errors.append(f"{language}: unexpected keys: {', '.join(sorted(extra))}") for key in base.keys() & values.keys(): if arguments(base[key]) != arguments(values[key]): errors.append(f"{language}: incompatible format arguments for {key}") if not values[key].strip(): errors.append(f"{language}: empty translation for {key}") if language != "en" and values[key] == base[key] and len(base[key]) > 3 \ and key not in SHARED_WORD_KEYS: errors.append(f"{language}: untranslated value for {key}") expected_event = {"en": "MEET & GREET", "zh-Hans": "特典会", "zh-Hant": "特典會", "zh-HK": "特典會", "ja": "特典会"}.get(language) if expected_event and values.get("board.eventKind") != expected_event: errors.append(f"{language}: board.eventKind must be {expected_event!r}") # zh-HK must not be a copy of zh-Hant. shared = sum(1 for key in base if catalogs["zh-HK"].get(key) == catalogs["zh-Hant"].get(key)) if shared > len(base) * 0.5: errors.append(f"zh-HK: {shared}/{len(base)} values identical to zh-Hant") references: set[str] = set() for path in (ROOT / "app/src/main/java").rglob("*.kt"): references |= referenced_keys(path.read_text(encoding="utf-8")) for key in sorted(references - base.keys()): errors.append(f"Kotlin source references missing localization key: {key}") # Keys used indirectly: validation messages arrive as a key from the core layer, # so any "validation.*" literal anywhere in the sources counts as a reference. sources = "\n".join(path.read_text(encoding="utf-8") for path in (ROOT / "app/src/main/java").rglob("*.kt")) indirect = { key for key in base if (key.startswith("validation.") or key.startswith("audio.import.")) and key in sources } unused = sorted(base.keys() - references - indirect) if unused: errors.append(f"unused keys: {', '.join(unused)}") if errors: print("\n".join(errors), file=sys.stderr) return 1 print(f"Verified {len(base)} keys across {len(LANGUAGES)} native localizations; " f"{len(references)} static source references resolve.") return 0 if __name__ == "__main__": sys.exit(main())