#!/usr/bin/env python3 """Brings the language files of the starter in line with en.xml. For every language file in StarterNG/startercfg/lang (or the codes given): - a key en.xml has and the language lacks is added with the English text, right after the key it follows in en.xml, and marked ; - a key en.xml no longer has is removed. Keys the starter falls back to English for by itself (ending in "Desc", starting with "Cmd.", and the developer tab's "Ini." rows and "Choice." words, see SimulatorKeyRows) are only added with --all. Everything else in the file - comments, order, line endings - stays as it is. python tools/sync_lang.py # every language python tools/sync_lang.py zh cz # only these python tools/sync_lang.py --check # only report; exit code 1 when a file is out of line """ import argparse import re import sys from pathlib import Path LANG_DIR = Path(__file__).resolve().parent.parent / "StarterNG" / "startercfg" / "lang" STRING = re.compile(r'.*?', re.DOTALL) LANGUAGE_TAG = re.compile(r"]*>") UNTRANSLATED = "" def is_optional(key): # As LocalizationTests.Every_language_has_every_key_but_the_optional_ones has them. return key.endswith("Desc") or key.startswith(("Cmd.", "Ini.", "Choice.")) def read(path): raw = path.read_bytes() bom = raw.startswith(b"\xef\xbb\xbf") text = raw[3 if bom else 0:].decode("utf-8") newline = "\r\n" if "\r\n" in text else "\n" return text, bom, newline def write(path, text, bom): path.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8")) def strings(text): """key -> match, in the order of the file; a key given twice keeps its first.""" found = {} for match in STRING.finditer(text): found.setdefault(match.group("key"), match) return found def line_start(text, pos): return text.rfind("\n", 0, pos) + 1 def line_end(text, pos): """Just past the newline ending the line that pos is on.""" end = text.find("\n", pos) return len(text) if end < 0 else end + 1 def removal_span(text, match): """The element with its whole lines when nothing but blanks and a comment share them.""" start, end = match.span() first = line_start(text, start) last = line_end(text, end) before = text[first:start] after = text[end:last].strip() if before.strip() == "" and (after == "" or (after.startswith(""))): return first, last return start, end def english_line(en_text, match, newline): indent = en_text[line_start(en_text, match.start()):match.start()] if indent.strip(): indent = " " element = match.group(0).replace("\r\n", "\n").replace("\n", newline) return f"{indent}{element} {UNTRANSLATED}{newline}" def insert_position(text, own, en_keys, key, after_tag): """Just after the nearest key before this one in en.xml that the file has and keeps.""" for previous in reversed(en_keys[:en_keys.index(key)]): if previous in own: return line_end(text, own[previous].end()) return after_tag def apply_edits(text, edits): """edits: (start, end, replacement) on the original text. Applied from the end so the offsets stay valid. Where a removal starts at the place of an insert, the removal goes first, or it would take away the inserted line instead of its own. Inserts at one place keep the order of en.xml. """ def order(edit): index, (start, end, _) = edit return start, 1 if end > start else 0, index for _, (start, end, replacement) in sorted(enumerate(edits), key=order, reverse=True): text = text[:start] + replacement + text[end:] return text def synced_text(path, text, newline, own, missing, obsolete, en_text, en_strings): edits = [(*removal_span(text, own[key]), "") for key in obsolete] tag = LANGUAGE_TAG.search(text) if tag is None: sys.exit(f"{path.name}: no element") after_tag = line_end(text, tag.end()) en_keys = list(en_strings) for key in missing: anchor = insert_position(text, own, en_keys, key, after_tag) edits.append((anchor, anchor, english_line(en_text, en_strings[key], newline))) return apply_edits(text, edits) def report(name, missing, obsolete, detailed): print(f"{name}: {len(missing)} to add in English, {len(obsolete)} no longer in en.xml") if detailed: for key in missing: print(f" missing {key}") for key in obsolete: print(f" obsolete {key}") def sync(path, en_text, en_strings, add_optional, check): """True when the file was out of line with en.xml (and, without check, is now brought in line).""" text, bom, newline = read(path) own = strings(text) obsolete = [key for key in own if key not in en_strings] missing = [key for key in en_strings if key not in own and (add_optional or not is_optional(key))] if not obsolete and not missing: print(f"{path.name}: in line with en.xml") return False report(path.name, missing, obsolete, check) if not check: write(path, synced_text(path, text, newline, own, missing, obsolete, en_text, en_strings), bom) return True def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("codes", nargs="*", help="language codes, e.g. zh cz; every language when none") parser.add_argument("--all", action="store_true", help="add the optional keys (*Desc, Cmd.*, Ini.*, Choice.*) too") parser.add_argument("--check", action="store_true", help="only report, change nothing") args = parser.parse_args() en_text, _, _ = read(LANG_DIR / "en.xml") en_strings = strings(en_text) if args.codes: paths = [LANG_DIR / f"{code}.xml" for code in args.codes] for path in paths: if not path.is_file(): sys.exit(f"no language file {path}") else: paths = sorted(p for p in LANG_DIR.glob("*.xml") if p.name != "en.xml") out_of_line = False for path in paths: out_of_line |= sync(path, en_text, en_strings, args.all, args.check) return 1 if args.check and out_of_line else 0 if __name__ == "__main__": sys.exit(main())