SPB Git

Repository Public BSD-3-Clause

localize.py 12.3 KB 272 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : ORIX Maps10# File             : scripts/localize.py11# Description      : ORIX Maps — builds the String Catalogs of the application12#                    from the compiler's extraction and the French table.13# Module           : scripts14# Repository       : https://git.spboucher.ai/orix-maps15# Created          : 2026-11-2516# Last Modified    : 2026-11-2517#18# =============================================================================19# AUTHOR & PROFESSIONAL AFFILIATION20# =============================================================================21#22# Author           : Simon-Pierre Boucher23# Position         : Professor of Finance24# Institution      : Université du Québec en Outaouais (UQO)25# Department       : Département des sciences administratives26# Organization     : SP Boucher27#28# Website          : https://spboucher.ai29# Git              : https://git.spboucher.ai30#31# =============================================================================32# OFFICIAL CONTACT DIRECTORY33# =============================================================================34#35# General          : info@spboucher.ai36# Professional     : contact@spboucher.ai37# Direct           : simon@spboucher.ai38# Research         : research@spboucher.ai39# Development      : dev@spboucher.ai40# Support          : support@spboucher.ai41# Security/Admin   : admin@spboucher.ai42# Notifications    : notifications@spboucher.ai43#44# Preferred Contact: support@spboucher.ai45#46# =============================================================================47# COPYRIGHT & INTELLECTUAL PROPERTY48# =============================================================================49#50# Copyright (c) 202651# Simon-Pierre Boucher52#53# All rights reserved where applicable.54#55# This file is governed by the applicable project license,56# copyright notices, institutional agreements and relevant law.57#58# Unless expressly authorized by the applicable license or59# rights holder, copying, redistribution, sublicensing,60# publication and commercial exploitation are not permitted.61#62# Existing third-party rights and notices remain unaffected.63#64# =============================================================================65# CONFIDENTIALITY & SECURITY66# =============================================================================67#68# Classification   : Public69# Distribution     : Public repository; use is governed by the project license70# Security Contact : admin@spboucher.ai71#72# Access to this source does not independently grant permission73# to redistribute or disclose confidential materials.74#75# Do not embed credentials, private keys, access tokens,76# certificates or confidential personal information.77#78# =============================================================================79# LICENSE & MAINTENANCE80# =============================================================================81#82# License          : Proprietary, all rights reserved (see license file)83# License File     : LICENSE84# Maintainer       : Simon-Pierre Boucher85# Technical Contact: dev@spboucher.ai86#87# =============================================================================88# END OF SP BOUCHER SOURCE HEADER89# =============================================================================9091"""ORIX Maps — builds the String Catalogs of the application from the compiler's extraction and the French table.9293usage: scripts/localize.py [--no-build] [--check]94951. Builds the application once (scripts/build.sh debug) so that the Swift compiler writes one `.stringsdata` file per96   source file (SWIFT_EMIT_LOC_STRINGS): every localizable string, including interpolated keys such as "Delete %@".972. Merges those keys with the hand-maintained table scripts/translations-fr.json.983. Writes Apps/ORIXMaps/Resources/Localizable.xcstrings and InfoPlist.xcstrings (source language en, French in `fr`,99   written in Québec French; `fr` serves fr-CA and every other French locale).100101It fails, listing them, when a string has no French translation, when a translation's key no longer exists in the102code, when a translation does not carry the same format specifiers as its key, or when an Info.plist value differs103from the English text recorded in the table. `--check` verifies without writing (exit status 1 on any problem, or when104the catalogs on disk are not up to date). `--no-build` reuses the `.stringsdata` of the last build.105Standard library only.106"""107import glob108import json109import os110import plistlib111import re112import subprocess113import sys114115ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))116APP = os.path.join(ROOT, "Apps", "ORIXMaps")117TABLE = os.path.join(ROOT, "scripts", "translations-fr.json")118RESOURCES = os.path.join(APP, "Resources")119INTERMEDIATES = os.path.join(ROOT, "build", "DerivedData", "Build", "Intermediates.noindex", "ORIXMaps.build")120LANGUAGE = "fr"121# Plural categories each language needs (CLDR): French also has "many" (millions).122CATEGORIES = {"en": ["one", "other"], "fr": ["one", "many", "other"]}123SPECIFIER = re.compile(r"%(?:(\d+)\$)?(#@\w+@|l{0,2}[dux]|[@sfgc]|\.\d+f)|%%")124125126def specifiers(text):127    """Format specifiers of a string as a sorted list of (argument number, type); positions are resolved in order."""128    out, implicit = [], 0129    for m in SPECIFIER.finditer(text):130        if m.group(0) == "%%":131            continue132        if m.group(1):133            number = int(m.group(1))134        else:135            implicit += 1136            number = implicit137        out.append((number, m.group(2)))138    return sorted(out)139140141def literal_percents(text):142    return len(re.findall(r"%%", text))143144145def stray_percent(text):146    """True when a '%' is neither a known specifier nor an escaped '%%' (it would corrupt the formatted string)."""147    return "%" in SPECIFIER.sub("", text)148149150def extracted_keys():151    """Keys of the Localizable table found in the .stringsdata files of the application target, with their source files."""152    files = glob.glob(os.path.join(INTERMEDIATES, "Debug-iphonesimulator", "ORIXMaps.build", "Objects-normal", "*", "*.stringsdata"))153    if not files:154        sys.exit("localize: no .stringsdata found under build/DerivedData — run without --no-build")155    keys, sources = {}, set()156    for path in files:157        with open(path, encoding="utf-8") as f:158            data = json.load(f)159        source = data.get("source", "")160        # A file deleted from the project leaves its .stringsdata behind until the next clean build: ignore it.161        if not source.startswith(os.path.join(APP, "Sources") + os.sep) or not os.path.isfile(source):162            continue163        sources.add(source)164        for table, items in data.get("tables", {}).items():165            if table != "Localizable":166                sys.exit(f"localize: unexpected string table {table!r} in {os.path.relpath(source, ROOT)}")167            for item in items:168                keys.setdefault(item["key"], set()).add(os.path.relpath(source, os.path.join(APP, "Sources")))169    swift = {p for p in glob.glob(os.path.join(APP, "Sources", "**", "*.swift"), recursive=True)}170    missing = sorted(os.path.relpath(p, ROOT) for p in swift - sources)171    if missing:172        sys.exit("localize: no extraction for these sources (stale build?): " + ", ".join(missing))173    return keys174175176def unit(value):177    return {"stringUnit": {"state": "translated", "value": value}}178179180def main():181    arguments = set(sys.argv[1:])182    unknown = arguments - {"--no-build", "--check"}183    if unknown:184        sys.exit(__doc__)185    if "--no-build" not in arguments:186        result = subprocess.run([os.path.join(ROOT, "scripts", "build.sh"), "debug"], capture_output=True, text=True)187        if result.returncode != 0:188            sys.exit("localize: the build failed\n" + result.stdout + result.stderr)189    keys = extracted_keys()190    with open(TABLE, encoding="utf-8") as f:191        table = json.load(f)192    translations = table["strings"]193    problems = []194195    untranslated = sorted(k for k in keys if k not in translations)196    for k in untranslated:197        problems.append(f"no French translation: {json.dumps(k, ensure_ascii=False)}  ({', '.join(sorted(keys[k]))})")198    for k in sorted(k for k in translations if k not in keys):199        problems.append(f"translation whose key no longer exists: {json.dumps(k, ensure_ascii=False)}")200201    strings = {}202    plural_count = 0203    for key in sorted(keys):204        entry = translations.get(key)205        if entry is None:206            continue207        expected = specifiers(key)208        if isinstance(entry, str):209            forms = {LANGUAGE: {"": entry}}210        else:211            forms = entry.get("plural", {})212            plural_count += 1213            if [t for _, t in expected].count("lld") != 1:214                problems.append(f"plural entry needs exactly one %lld in its key: {json.dumps(key, ensure_ascii=False)}")215            for language, categories in CATEGORIES.items():216                if sorted(forms.get(language, {})) != sorted(categories):217                    problems.append(f"plural forms of {json.dumps(key, ensure_ascii=False)} in {language} must be exactly {categories}")218        localizations = {}219        for language, values in forms.items():220            for category, value in values.items():221                where = f"{json.dumps(key, ensure_ascii=False)} [{language}{' ' + category if category else ''}]"222                if not value.strip():223                    problems.append(f"empty translation: {where}")224                if specifiers(value) != expected or literal_percents(value) != literal_percents(key) or stray_percent(value):225                    problems.append(f"format specifiers differ from the key: {where} → {json.dumps(value, ensure_ascii=False)}")226                if language == LANGUAGE and ("'" in value or '"' in value):227                    problems.append(f"straight quote or apostrophe (use ’ and « »): {where}")228            if "" in values:229                localizations[language] = unit(values[""])230            else:231                localizations[language] = {"variations": {"plural": {c: unit(v) for c, v in sorted(values.items())}}}232        strings[key] = {"localizations": localizations}233234    # Info.plist strings: the English text in the table must be the one the project puts in Info.plist.235    info = {}236    with open(os.path.join(APP, "Info.plist"), "rb") as f:237        plist = plistlib.load(f)238    for name, values in sorted(table["infoPlist"].items()):239        if plist.get(name) != values["en"]:240            problems.append(f"Info.plist {name} is {plist.get(name)!r} but the table records {values['en']!r}")241        if not values.get(LANGUAGE, "").strip():242            problems.append(f"no French translation: Info.plist {name}")243        info[name] = {"extractionState": "manual", "localizations": {"en": unit(values["en"]), LANGUAGE: unit(values.get(LANGUAGE, ""))}}244245    if problems:246        print(f"localize: {len(problems)} problem(s)", file=sys.stderr)247        for p in problems:248            print("  - " + p, file=sys.stderr)249        sys.exit(1)250251    outputs = {252        os.path.join(RESOURCES, "Localizable.xcstrings"): {"sourceLanguage": "en", "strings": strings, "version": "1.0"},253        os.path.join(RESOURCES, "InfoPlist.xcstrings"): {"sourceLanguage": "en", "strings": info, "version": "1.0"},254    }255    stale = []256    for path, document in outputs.items():257        text = json.dumps(document, ensure_ascii=False, indent=2, sort_keys=True, separators=(",", " : ")) + "\n"258        current = open(path, encoding="utf-8").read() if os.path.isfile(path) else None259        if current != text:260            stale.append(os.path.relpath(path, ROOT))261            if "--check" not in arguments:262                with open(path, "w", encoding="utf-8") as f:263                    f.write(text)264    summary = f"{len(strings)} strings ({plural_count} with plural forms) + {len(info)} Info.plist strings, all translated to {LANGUAGE}"265    if "--check" in arguments and stale:266        sys.exit(f"localize: {summary}; out of date: {', '.join(stale)} — run scripts/localize.py")267    print(f"localize: {summary}" + (f"; wrote {', '.join(stale)}" if stale else "; catalogs already up to date"))268269270if __name__ == "__main__":271    main()272
Files main
Menu

Theme