refactored some variables + added comments

This commit is contained in:
Moritz Reinel 2024-10-26 13:09:30 +02:00
parent 0dea19c8db
commit b6726a76c6
1 changed files with 32 additions and 23 deletions

View File

@ -4,37 +4,46 @@ from pathlib import Path
from sys import stderr from sys import stderr
def process_lang_file(path: str) -> None: def process_lang_file(path: Path, lang_keys: list[str]) -> None:
values = {} # read key-value-pairs from lang file into dict
existing_entries = {}
with open(path, "r", encoding="UTF-8") as fh: with open(path, "r", encoding="UTF-8") as fh:
while line := fh.readline(): while line := fh.readline():
vals = line.split("=") try:
if len(vals) != 2: key, value = line.split("=", 1)
existing_entries[key.strip()] = value.strip()
except ValueError: # line does not contain '='
continue continue
key = vals[0].strip() # re-write current lang file with entries in order of occurence in `lang_keys`
values[key] = vals[1].strip() # and with empty lines for missing translations
with open(path, "w", encoding="UTF-8") as fh: with open(path, "w", encoding="UTF-8") as fh:
for item in lang_strings: for item in lang_keys:
v = values.get(item) try:
if v is not None: fh.write(f"{item} = {existing_entries[item]}\n")
fh.write(f"{item} = {v}\n") except KeyError: # no translation for `item` yet
else:
fh.write("\n") fh.write("\n")
def main() -> None:
zig_lang_file = Path(__file__).parent.joinpath("../../src/config/Lang.zig").resolve() zig_lang_file = Path(__file__).parent.joinpath("../../src/config/Lang.zig").resolve()
if not zig_lang_file.exists(): if not zig_lang_file.exists():
print(f"ERROR: File '{zig_lang_file.as_posix()}' does not exist. Exiting.", file=stderr) print(f"ERROR: File '{zig_lang_file.as_posix()}' does not exist. Exiting.", file=stderr)
exit(1) exit(1)
lang_strings = [] # read "language keys" from `zig_lang_file` into list
lang_keys = []
with open(zig_lang_file, "r", encoding="UTF-8") as fh: with open(zig_lang_file, "r", encoding="UTF-8") as fh:
while line := fh.readline(): while line := fh.readline():
lang_strings.append(line.split(":")[0]) # only process lines that are not empty or no comments
if not (line.strip() == "" or line.startswith("//")):
lang_keys.append(line.split(":")[0].strip())
lang_files = [f for f in Path.iterdir(Path(__file__).parent) if f.name.endswith(".ini") and f.is_file()] lang_files = [f for f in Path.iterdir(Path(__file__).parent) if f.name.endswith(".ini") and f.is_file()]
for file in lang_files: for file in lang_files:
process_lang_file(file.as_posix()) process_lang_file(file, lang_keys)
if __name__ == "__main__":
main()