Files
StarterNG/tools/sync_lang.py
T
maj00r 9fe767cf9f fix(lang): the Chinese translation has every key of en.xml again, and a script keeps languages in line
zh.xml (#45) was translated from an older en.xml: 73 keys the tests require were
missing and 97 keys en.xml no longer has were still there. The localization test
failed on main, so no package and no release were made after the merge.

tools/sync_lang.py adds the missing keys with the English text, marked
<!-- TODO: translate -->, and removes the unused ones; the rest of the file stays
as it is. --check only lists the differences. The missing Chinese keys are filled
in with it, and the README says how to use it.
2026-11-29 22:23:07 +01:00

161 lines
5.6 KiB
Python

#!/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 <!-- TODO: translate -->;
- 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.")
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'<String key="(?P<key>[^"]+)">.*?</String>', re.DOTALL)
LANGUAGE_TAG = re.compile(r"<Language\b[^>]*>")
TODO = "<!-- TODO: translate -->"
def is_optional(key):
return key.endswith("Desc") or key.startswith("Cmd.")
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("<!--") and after.endswith("-->"))):
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} {TODO}{newline}"
def sync(path, en_text, en_strings, add_optional, check):
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))]
name = path.name
if not obsolete and not missing:
print(f"{name}: in line with en.xml")
return False
print(f"{name}: {len(missing)} to add in English, {len(obsolete)} no longer in en.xml")
if check:
for key in missing:
print(f" missing {key}")
for key in obsolete:
print(f" obsolete {key}")
return True
edits = [] # (start, end, replacement), all on the original text
for key in obsolete:
start, end = removal_span(text, own[key])
edits.append((start, end, ""))
tag = LANGUAGE_TAG.search(text)
if tag is None:
sys.exit(f"{name}: no <Language> element")
after_tag = line_end(text, tag.end())
en_keys = list(en_strings)
for key in missing:
# after the nearest key before it in en.xml that the file has and keeps
anchor = after_tag
for previous in reversed(en_keys[:en_keys.index(key)]):
if previous in own and previous in en_strings:
anchor = line_end(text, own[previous].end())
break
edits.append((anchor, anchor, english_line(en_text, en_strings[key], newline)))
# 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:]
write(path, text, 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.*) 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())