SPB Git

Repository Public

strings.py 4.4 KB 86 lines python

1#!/usr/bin/env python32"""Localization catalog tool of FeatureAnalysis.34    Scripts/strings.py <Target> [--stub]      e.g.  Scripts/strings.py StatsBasic5    Scripts/strings.py --all67Source of truth of the translations: Strings/<Target>.fr.tsv  (one line per key:  English key <TAB> Canadian French).8The tool extracts every literal L("…") key from Sources/<Target>, checks that each one has a non-empty fr-CA9translation with the same format specifiers, and regenerates Sources/<Target>/Resources/Localizable.xcstrings.10`--stub` appends the missing keys to the TSV (empty translation) so they can be filled in.11Exit status 1 when a key is missing, untranslated, or a specifier mismatch is found.12Keys must be string literals without interpolation (use %@ / %d arguments).13"""14import json, os, re, sys1516ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))17TARGETS = ["AnalysisKit", "StatsBasic", "StatsModels", "FinanceStudio", "WhatIfTools", "FeatureAnalysis"]18KEY = re.compile(r'(?<![A-Za-z0-9_.])L\(\s*"((?:[^"\\]|\\.)*)"')19SPEC = re.compile(r'%(?:\d+\$)?(?:@|d|ld|lld|f|\.\d+f|g|%)')2021def unescape(s):22    out, i = [], 023    while i < len(s):24        c = s[i]25        if c == "\\" and i + 1 < len(s):26            n = s[i + 1]27            if n == "(": raise ValueError("interpolation in key: " + s)28            if n == "u":29                j = s.index("}", i); out.append(chr(int(s[i + 3:j], 16))); i = j + 1; continue30            out.append({"n": "\n", "t": "\t", '"': '"', "\\": "\\", "'": "'"}.get(n, n)); i += 231        else:32            out.append(c); i += 133    return "".join(out)3435def keys_of(target):36    keys = {}37    base = os.path.join(ROOT, "Sources", target)38    for d, _, files in os.walk(base):39        for f in sorted(files):40            if not f.endswith(".swift"): continue41            text = open(os.path.join(d, f), encoding="utf-8").read()42            for m in KEY.finditer(text):43                keys.setdefault(unescape(m.group(1)), os.path.relpath(os.path.join(d, f), ROOT))44    return keys4546def enc(s): return s.replace("\\", "\\\\").replace("\n", "\\n").replace("\t", "\\t")47def dec(s): return s.replace("\\n", "\n").replace("\\t", "\t").replace("\\\\", "\\")4849def run(target, stub):50    tsv = os.path.join(ROOT, "Strings", target + ".fr.tsv")51    table = {}52    if os.path.exists(tsv):53        for n, line in enumerate(open(tsv, encoding="utf-8").read().split("\n"), 1):54            if not line.strip() or line.startswith("#"): continue55            parts = line.split("\t")56            if len(parts) != 2: print(f"{tsv}:{n}: expected 'key<TAB>translation'"); return 157            table[dec(parts[0])] = dec(parts[1])58    keys = keys_of(target)59    problems = 060    missing = [k for k in keys if not table.get(k)]61    if missing and stub:62        with open(tsv, "a", encoding="utf-8") as f:63            for k in missing:64                if k not in table: f.write(enc(k) + "\t\n")65        print(f"{target}: {len(missing)} keys appended to {os.path.relpath(tsv, ROOT)} — fill in the translations")66        return 167    for k in missing: print(f"{target}: missing fr-CA translation for {k!r}  ({keys[k]})"); problems += 168    for k in keys:69        if table.get(k) and sorted(SPEC.findall(k)) != sorted(s.replace("1$", "").replace("2$", "").replace("3$", "") for s in SPEC.findall(table[k])):70            print(f"{target}: format specifiers differ for {k!r} → {table[k]!r}"); problems += 171    unused = [k for k in table if k not in keys]72    if unused: print(f"{target}: {len(unused)} unused TSV entries (kept out of the catalog): " + "; ".join(repr(k) for k in unused[:5]) + (" …" if len(unused) > 5 else ""))73    strings = {k: {"localizations": {"fr-CA": {"stringUnit": {"state": "translated", "value": table[k]}}}} for k in sorted(keys) if table.get(k)}74    out = os.path.join(ROOT, "Sources", target, "Resources", "Localizable.xcstrings")75    with open(out, "w", encoding="utf-8") as f:76        json.dump({"sourceLanguage": "en", "strings": strings, "version": "1.0"}, f, ensure_ascii=False, indent=2, sort_keys=True)77        f.write("\n")78    print(f"{target}: {len(strings)}/{len(keys)} keys in catalog" + ("" if not problems else f", {problems} problem(s)"))79    return 1 if problems else 08081if __name__ == "__main__":82    args = [a for a in sys.argv[1:] if not a.startswith("--")]83    targets = TARGETS if "--all" in sys.argv else args84    if not targets: print(__doc__); sys.exit(2)85    sys.exit(max(run(t, "--stub" in sys.argv) for t in targets))86
Files main
Menu

Theme