123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451 |
- from __future__ import print_function
- import os, fnmatch, re, shutil, errno
- from sys import argv as _argv
- from sys import stderr as _stderr
- params = {"recursive": False,
- "help": False,
- "mods": False,
- "verbose": False,
- "folders": [],
- "no-old-file": False
- }
- options = {"recursive": ['--recursive', '-r'],
- "help": ['--help', '-h'],
- "mods": ['--installed-mods'],
- "verbose": ['--verbose', '-v'],
- "no-old-file": ['--no-old-file']
- }
- doublespace_threshold = 60
- def set_params_folders(tab: list):
- '''Initialize params["folders"] from CLI arguments.'''
-
- for param in tab[1:]:
- stop_param = False
- for option in options:
- if param in options[option]:
- stop_param = True
- break
- if not stop_param:
- params["folders"].append(os.path.abspath(param))
- def set_params(tab: list):
- '''Initialize params from CLI arguments.'''
- for option in options:
- for option_name in options[option]:
- if option_name in tab:
- params[option] = True
- break
- def print_help(name):
- '''Prints some help message.'''
- print(f'''SYNOPSIS
- {name} [OPTIONS] [PATHS...]
- DESCRIPTION
- {', '.join(options["help"])}
- prints this help message
- {', '.join(options["recursive"])}
- run on all subfolders of paths given
- {', '.join(options["mods"])}
- run on locally installed modules
- {', '.join(options["no-old-file"])}
- do not create *.old files
- {', '.join(options["verbose"])}
- add output information
- ''')
- def main():
- '''Main function'''
- set_params(_argv)
- set_params_folders(_argv)
- if params["help"]:
- print_help(_argv[0])
- elif params["recursive"] and params["mods"]:
- print("Option --installed-mods is incompatible with --recursive")
- else:
-
- print("Running ", end='')
- if params["recursive"]:
- print("recursively ", end='')
-
- if params["mods"]:
- print(f"on all locally installed modules in {os.path.abspath('~/.minetest/mods/')}")
- run_all_subfolders("~/.minetest/mods")
- elif len(params["folders"]) >= 2:
- print("on folder list:", params["folders"])
- for f in params["folders"]:
- if params["recursive"]:
- run_all_subfolders(f)
- else:
- update_folder(f)
- elif len(params["folders"]) == 1:
- print("on folder", params["folders"][0])
- if params["recursive"]:
- run_all_subfolders(params["folders"][0])
- else:
- update_folder(params["folders"][0])
- else:
- print("on folder", os.path.abspath("./"))
- if params["recursive"]:
- run_all_subfolders(os.path.abspath("./"))
- else:
- update_folder(os.path.abspath("./"))
- pattern_lua_s = re.compile(r'[\.=^\t,{\(\s]N?S\(\s*(["\'])((?:\\\1|(?:(?!\1)).)*)(\1)[\s,\)]', re.DOTALL)
- pattern_lua_fs = re.compile(r'[\.=^\t,{\(\s]N?FS\(\s*(["\'])((?:\\\1|(?:(?!\1)).)*)(\1)[\s,\)]', re.DOTALL)
- pattern_lua_bracketed_s = re.compile(r'[\.=^\t,{\(\s]N?S\(\s*\[\[(.*?)\]\][\s,\)]', re.DOTALL)
- pattern_lua_bracketed_fs = re.compile(r'[\.=^\t,{\(\s]N?FS\(\s*\[\[(.*?)\]\][\s,\)]', re.DOTALL)
- pattern_concat = re.compile(r'["\'][\s]*\.\.[\s]*["\']', re.DOTALL)
- pattern_tr = re.compile(r'(.*?[^@])=(.*)')
- pattern_name = re.compile(r'^name[ ]*=[ ]*([^ \n]*)')
- pattern_tr_filename = re.compile(r'\.tr$')
- pattern_po_language_code = re.compile(r'(.*)\.po$')
- def get_modname(folder):
- try:
- with open(os.path.join(folder, "mod.conf"), "r", encoding='utf-8') as mod_conf:
- for line in mod_conf:
- match = pattern_name.match(line)
- if match:
- return match.group(1)
- except FileNotFoundError:
- pass
- return None
- def get_existing_tr_files(folder):
- out = []
- for root, dirs, files in os.walk(os.path.join(folder, 'locale/')):
- for name in files:
- if pattern_tr_filename.search(name):
- out.append(name)
- return out
- def process_po_file(text):
-
- text = re.sub(r'#~ msgid "', "", text)
- text = re.sub(r'"\n#~ msgstr ""\n"', "=", text)
- text = re.sub(r'"\n#~ msgstr "', "=", text)
-
- text = re.sub(r'#.*\n', "", text)
-
- text = re.sub(r'msgid "', "", text)
- text = re.sub(r'"\nmsgstr ""\n"', "=", text)
- text = re.sub(r'"\nmsgstr "', "=", text)
-
- text = re.sub(r'"\n"', "", text)
- text = re.sub(r'"\n', "\n", text)
- text = re.sub(r'\\"', '"', text)
- text = re.sub(r'\\n', '@n', text)
-
- text = re.sub(r'=Project-Id-Version:.*\n', "", text)
-
- text = re.sub(r'\n\n', '\n', text)
- return text
- def process_po_files(folder, modname):
- for root, dirs, files in os.walk(os.path.join(folder, 'locale/')):
- for name in files:
- code_match = pattern_po_language_code.match(name)
- if code_match == None:
- continue
- language_code = code_match.group(1)
- tr_name = modname + "." + language_code + ".tr"
- tr_file = os.path.join(root, tr_name)
- if os.path.exists(tr_file):
- if params["verbose"]:
- print(f"{tr_name} already exists, ignoring {name}")
- continue
- fname = os.path.join(root, name)
- with open(fname, "r", encoding='utf-8') as po_file:
- if params["verbose"]:
- print(f"Importing translations from {name}")
- text = process_po_file(po_file.read())
- with open(tr_file, "wt", encoding='utf-8') as tr_out:
- tr_out.write(text)
- def mkdir_p(path):
- try:
- os.makedirs(path)
- except OSError as exc:
- if exc.errno == errno.EEXIST and os.path.isdir(path):
- pass
- else: raise
- def strings_to_text(dkeyStrings, dOld, mod_name, header_comments):
- lOut = [f"# textdomain: {mod_name}\n"]
- if header_comments is not None:
- lOut.append(header_comments)
-
- dGroupedBySource = {}
- for key in dkeyStrings:
- sourceList = list(dkeyStrings[key])
- sourceList.sort()
- sourceString = "\n".join(sourceList)
- listForSource = dGroupedBySource.get(sourceString, [])
- listForSource.append(key)
- dGroupedBySource[sourceString] = listForSource
-
- lSourceKeys = list(dGroupedBySource.keys())
- lSourceKeys.sort()
- for source in lSourceKeys:
- localizedStrings = dGroupedBySource[source]
- localizedStrings.sort()
- lOut.append("")
- lOut.append(source)
- lOut.append("")
- for localizedString in localizedStrings:
- val = dOld.get(localizedString, {})
- translation = val.get("translation", "")
- comment = val.get("comment")
- if len(localizedString) > doublespace_threshold and not lOut[-1] == "":
- lOut.append("")
- if comment != None:
- lOut.append(comment)
- lOut.append(f"{localizedString}={translation}")
- if len(localizedString) > doublespace_threshold:
- lOut.append("")
- unusedExist = False
- for key in dOld:
- if key not in dkeyStrings:
- val = dOld[key]
- translation = val.get("translation")
- comment = val.get("comment")
-
-
- if translation != None and (translation != "" or comment):
- if not unusedExist:
- unusedExist = True
- lOut.append("\n\n##### not used anymore #####\n")
- if len(key) > doublespace_threshold and not lOut[-1] == "":
- lOut.append("")
- if comment != None:
- lOut.append(comment)
- lOut.append(f"{key}={translation}")
- if len(key) > doublespace_threshold:
- lOut.append("")
- return "\n".join(lOut) + '\n'
- def write_template(templ_file, dkeyStrings, mod_name):
-
- existing_template = import_tr_file(templ_file)
-
- text = strings_to_text(dkeyStrings, existing_template[0], mod_name, existing_template[2])
- mkdir_p(os.path.dirname(templ_file))
- with open(templ_file, "wt", encoding='utf-8') as template_file:
- template_file.write(text)
- def read_lua_file_strings(lua_file):
- lOut = []
- with open(lua_file, encoding='utf-8') as text_file:
- text = text_file.read()
-
- text = re.sub(pattern_concat, "", text)
- strings = []
- for s in pattern_lua_s.findall(text):
- strings.append(s[1])
- for s in pattern_lua_bracketed_s.findall(text):
- strings.append(s)
- for s in pattern_lua_fs.findall(text):
- strings.append(s[1])
- for s in pattern_lua_bracketed_fs.findall(text):
- strings.append(s)
-
- for s in strings:
- s = re.sub(r'"\.\.\s+"', "", s)
- s = re.sub("@[^@=0-9]", "@@", s)
- s = s.replace('\\"', '"')
- s = s.replace("\\'", "'")
- s = s.replace("\n", "@n")
- s = s.replace("\\n", "@n")
- s = s.replace("=", "@=")
- lOut.append(s)
- return lOut
- def import_tr_file(tr_file):
- dOut = {}
- text = None
- header_comment = None
- if os.path.exists(tr_file):
- with open(tr_file, "r", encoding='utf-8') as existing_file :
-
-
- text = existing_file.read()
- existing_file.seek(0)
-
-
-
- latest_comment_block = None
- for line in existing_file.readlines():
- line = line.rstrip('\n')
- if line[:3] == "###":
- if header_comment is None:
-
- header_comment = latest_comment_block
-
- tmp_h_c = ""
- for l in header_comment.split('\n'):
- if not l.startswith("# textdomain:"):
- tmp_h_c += l + '\n'
- header_comment = tmp_h_c
-
- latest_comment_block = None
- continue
- if line[:1] == "#":
-
- if not latest_comment_block:
- latest_comment_block = line
- else:
- latest_comment_block = latest_comment_block + "\n" + line
- continue
- match = pattern_tr.match(line)
- if match:
-
- outval = {}
- outval["translation"] = match.group(2)
- if latest_comment_block:
-
- outval["comment"] = latest_comment_block
- latest_comment_block = None
- dOut[match.group(1)] = outval
- return (dOut, text, header_comment)
- def generate_template(folder, mod_name):
- dOut = {}
- for root, dirs, files in os.walk(folder):
- for name in files:
- if fnmatch.fnmatch(name, "*.lua"):
- fname = os.path.join(root, name)
- found = read_lua_file_strings(fname)
- if params["verbose"]:
- print(f"{fname}: {str(len(found))} translatable strings")
- for s in found:
- sources = dOut.get(s, set())
- sources.add(f"### {os.path.basename(fname)} ###")
- dOut[s] = sources
-
- if len(dOut) == 0:
- return None
- templ_file = os.path.join(folder, "locale/template.txt")
- write_template(templ_file, dOut, mod_name)
- return dOut
- def update_tr_file(dNew, mod_name, tr_file):
- if params["verbose"]:
- print(f"updating {tr_file}")
- tr_import = import_tr_file(tr_file)
- dOld = tr_import[0]
- textOld = tr_import[1]
- textNew = strings_to_text(dNew, dOld, mod_name, tr_import[2])
- if textOld and textOld != textNew:
- print(f"{tr_file} has changed.")
- if not params["no-old-file"]:
- shutil.copyfile(tr_file, f"{tr_file}.old")
- with open(tr_file, "w", encoding='utf-8') as new_tr_file:
- new_tr_file.write(textNew)
- def update_mod(folder):
- print(folder)
- modname = get_modname(folder)
- if modname is not None:
- process_po_files(folder, modname)
- print(f"Updating translations for {modname}")
- data = generate_template(folder, modname)
- if data == None:
- print(f"No translatable strings found in {modname}")
- else:
- for tr_file in get_existing_tr_files(folder):
- update_tr_file(data, modname, os.path.join(folder, "locale/", tr_file))
- else:
- print(f"\033[31mUnable to find modname in folder {folder}.\033[0m", file=_stderr)
-
- def update_folder(folder):
- is_modpack = os.path.exists(os.path.join(folder, "modpack.txt")) or os.path.exists(os.path.join(folder, "modpack.conf"))
- if is_modpack:
- subfolders = [f.path for f in os.scandir(folder) if f.is_dir()]
- for subfolder in subfolders:
- update_mod(subfolder + "/")
- else:
- update_mod(folder)
- print("Done.")
- def run_all_subfolders(folder):
- for modfolder in [f.path for f in os.scandir(folder) if f.is_dir()]:
- update_folder(modfolder + "/")
- main()
|