Repository Public
1#!/usr/bin/env python32"""Localization catalog tool of FeatureCharts.34 Scripts/strings.py [--stub]56Source of truth of the translations: Strings/*.fr.tsv (one line per key: English key <TAB> Canadian French).7The tool extracts every literal key from Sources/FeatureCharts — L("…"), Text(c: "…") and the undo labels passed to8ChartEditor (`.apply("…"`, `.applyValue("…"`, `.live("…"`) — checks that each has a non-empty fr-CA translation with9the same format specifiers, and regenerates Sources/FeatureCharts/Resources/Localizable.xcstrings.10`--stub` appends the missing keys to Strings/_missing.fr.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 glob, json, os, re, sys1516ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))17KEY = re.compile(r'(?:(?<![A-Za-z0-9_.])L\(|Text\(c:|\.apply\(|\.applyValue\(|\.live\()\s*"((?:[^"\\]|\\.)*)"')18SPEC = re.compile(r'%(?:\d+\$)?(?:@|d|ld|lld|f|\.\d+f|g|%)')1920def unescape(s):21 out, i = [], 022 while i < len(s):23 c = s[i]24 if c == "\\" and i + 1 < len(s):25 n = s[i + 1]26 if n == "(": raise ValueError("interpolation in key: " + s)27 if n == "u":28 j = s.index("}", i); out.append(chr(int(s[i + 3:j], 16))); i = j + 1; continue29 out.append({"n": "\n", "t": "\t", '"': '"', "\\": "\\", "'": "'"}.get(n, n)); i += 230 else:31 out.append(c); i += 132 return "".join(out)3334def keys_of():35 keys = {}36 for d, _, files in os.walk(os.path.join(ROOT, "Sources", "FeatureCharts")):37 for f in sorted(files):38 if not f.endswith(".swift"): continue39 text = open(os.path.join(d, f), encoding="utf-8").read()40 for m in KEY.finditer(text):41 keys.setdefault(unescape(m.group(1)), os.path.relpath(os.path.join(d, f), ROOT))42 return keys4344def enc(s): return s.replace("\\", "\\\\").replace("\n", "\\n").replace("\t", "\\t")45def dec(s): return s.replace("\\n", "\n").replace("\\t", "\t").replace("\\\\", "\\")4647def run(stub):48 table = {}49 for tsv in sorted(glob.glob(os.path.join(ROOT, "Strings", "*.fr.tsv"))):50 for n, line in enumerate(open(tsv, encoding="utf-8").read().split("\n"), 1):51 if not line.strip() or line.startswith("#"): continue52 parts = line.split("\t")53 if len(parts) != 2: print(f"{tsv}:{n}: expected 'key<TAB>translation'"); return 154 if parts[1].strip(): table[dec(parts[0])] = dec(parts[1])55 keys = keys_of()56 problems = 057 missing = [k for k in keys if not table.get(k)]58 if missing and stub:59 with open(os.path.join(ROOT, "Strings", "_missing.fr.tsv"), "a", encoding="utf-8") as f:60 for k in missing: f.write(enc(k) + "\t\n")61 print(f"{len(missing)} keys appended to Strings/_missing.fr.tsv — fill in the translations")62 return 163 for k in missing: print(f"missing fr-CA translation for {k!r} ({keys[k]})"); problems += 164 for k in keys:65 if table.get(k) and sorted(SPEC.findall(k)) != sorted(re.sub(r'\d\$', '', s) for s in SPEC.findall(table[k])):66 print(f"format specifiers differ for {k!r} → {table[k]!r}"); problems += 167 unused = [k for k in table if k not in keys]68 if unused: print(f"{len(unused)} unused TSV entries (kept out of the catalog): " + "; ".join(repr(k) for k in unused[:8]) + (" …" if len(unused) > 8 else ""))69 strings = {k: {"localizations": {"fr-CA": {"stringUnit": {"state": "translated", "value": table[k]}}}} for k in sorted(keys) if table.get(k)}70 out = os.path.join(ROOT, "Sources", "FeatureCharts", "Resources", "Localizable.xcstrings")71 with open(out, "w", encoding="utf-8") as f:72 json.dump({"sourceLanguage": "en", "strings": strings, "version": "1.0"}, f, ensure_ascii=False, indent=2, sort_keys=True)73 f.write("\n")74 print(f"{len(strings)}/{len(keys)} keys in catalog" + ("" if not problems else f", {problems} problem(s)"))75 return 1 if problems else 07677if __name__ == "__main__":78 sys.exit(run("--stub" in sys.argv))79