SPB Git

Repository Public License

localize.py 5.1 KB 110 lines python

1#!/usr/bin/env python32# ORIX OS Automation3# File: Scripts/localize.py4# Description: Builds App/Resources/Localizable.xcstrings (English source, French Canada) from every Localization/fr.json, and reports user-facing strings found in the sources that have no translation.5#6# Author: Simon-Pierre Boucher7# Contact: contact@spboucher.ai8"""9  Scripts/localize.py            write the string catalog10  Scripts/localize.py --missing  list strings found in Swift sources without a French entry (exit 1 if any)1112Every SwiftUI `Text("…")` and `String(localized: "…")` in the packages resolves in the app's main bundle, so one13catalog in the app covers all of them. Keys are the English strings, with interpolations written the way SwiftUI14builds them: %@ for strings, %lld for integers, %lf for doubles.15"""16import glob17import json18import os19import re20import sys2122ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))23CATALOG = os.path.join(ROOT, "App", "Resources", "Localizable.xcstrings")2425# Calls whose first string literal is user-facing.26CALLS = r'(?:Text|Label|Button|Toggle|Picker|Section|Menu|TextField|SecureField|Link|DisclosureGroup|LabeledContent|Tab|EmptyState|PageHeader|SectionHeader|KeyValueRow|MetricTile|NavigationLink|ProgressView|GroupBox|ControlGroup|Stepper|DatePicker|ColorPicker|Slider|Gauge|ContentUnavailableView|CommandMenu|WindowGroup)'27PATTERNS = [28    re.compile(CALLS + r'\(\s*"((?:[^"\\]|\\.)*)"'),29    re.compile(r'String\(localized:\s*"((?:[^"\\]|\\.)*)"'),30    re.compile(r'(?:title|message|subtitle|actionTitle|label|key|placeholder|prompt|help)\s*:\s*"((?:[^"\\]|\\.)*)"'),31    re.compile(r'\.(?:help|navigationTitle|accessibilityLabel|accessibilityHint|accessibilityValue|confirmationDialog|alert)\(\s*(?:Text\()?\s*"((?:[^"\\]|\\.)*)"'),32    re.compile(r'return\s+"((?:[^"\\]|\\.)*)"\s*$', re.M),33]343536def to_key(literal: str) -> str:37    """Swift literal -> catalog key: interpolations become format specifiers."""38    out, i, depth, start = "", 0, 0, 039    while i < len(literal):40        if literal.startswith("\\(", i):41            depth, j = 1, i + 242            while j < len(literal) and depth:43                depth += literal[j] == "("44                depth -= literal[j] == ")"45                j += 146            expr = literal[i + 2:j - 1]47            integer = re.search(r'\bcount\b|\.count\b|Count\b|\bn\b|index|version|revision|\bInt\(|days|minutes|seconds|total|number', expr) and "Format." not in expr48            out += "%lld" if integer else "%@"49            i = j50        elif literal.startswith('\\"', i):51            out += '"'; i += 252        elif literal.startswith("\\n", i):53            out += "\n"; i += 254        else:55            out += literal[i]; i += 156    return out575859def source_strings():60    found = {}61    files = glob.glob(os.path.join(ROOT, "App", "Sources", "**", "*.swift"), recursive=True)62    for pkg in ["ORIXAppUI"] + [os.path.basename(p) for p in glob.glob(os.path.join(ROOT, "Packages", "ORIXFeature*"))]:63        files += glob.glob(os.path.join(ROOT, "Packages", pkg, "Sources", pkg, "**", "*.swift"), recursive=True)64    for f in files:65        text = open(f, encoding="utf-8").read()66        for i, pattern in enumerate(PATTERNS):67            for m in pattern.finditer(text):68                lit = m.group(1)69                if i == 4 and not re.search(r'[a-z] [a-z]', lit):  # `return "…"`: sentences only70                    continue71                key = to_key(lit)72                if len(key) < 2 or not re.search(r'[A-Za-z]{2}', key):73                    continue74                if re.fullmatch(r'[a-z0-9_.\-/#:]+', key) or key.startswith(("http", "x-apple", "ai.spboucher")):75                    continue  # identifiers, symbols, paths76                found.setdefault(key, os.path.relpath(f, ROOT))77    return found787980def translations():81    merged = {}82    for path in sorted(glob.glob(os.path.join(ROOT, "Packages", "*", "Localization", "fr.json")) + glob.glob(os.path.join(ROOT, "App", "Localization", "fr.json"))):83        for k, v in json.load(open(path, encoding="utf-8")).items():84            if isinstance(v, str) and v:85                merged.setdefault(k, v)86    return merged878889def main():90    fr = translations()91    if "--missing" in sys.argv:92        missing = {k: f for k, f in source_strings().items() if k not in fr}93        for k, f in sorted(missing.items(), key=lambda kv: kv[1]):94            print(f"{f}\t{json.dumps(k, ensure_ascii=False)}")95        print(f"{len(missing)} string(s) without a French translation; {len(fr)} translated", file=sys.stderr)96        return 1 if missing else 097    strings = {}98    for key, value in sorted(fr.items()):99        strings[key] = {"localizations": {"fr-CA": {"stringUnit": {"state": "translated", "value": value}}}}100    os.makedirs(os.path.dirname(CATALOG), exist_ok=True)101    with open(CATALOG, "w", encoding="utf-8") as out:102        json.dump({"sourceLanguage": "en", "strings": strings, "version": "1.0"}, out, ensure_ascii=False, indent=2, sort_keys=True)103        out.write("\n")104    print(f"wrote {os.path.relpath(CATALOG, ROOT)} with {len(strings)} French strings")105    return 0106107108if __name__ == "__main__":109    sys.exit(main())110
Files main
Menu

Theme