i18n.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Script to generate the template file and update the translation files.
  5. # Copy the script into the mod or modpack root folder and run it there.
  6. #
  7. # Copyright (C) 2019 Joachim Stolberg, 2020 FaceDeer, 2020 Louis Royer
  8. # LGPLv2.1+
  9. #
  10. # See https://github.com/minetest-tools/update_translations for
  11. # potential future updates to this script.
  12. from __future__ import print_function
  13. import os, fnmatch, re, shutil, errno
  14. from sys import argv as _argv
  15. # Running params
  16. params = {"recursive": False,
  17. "help": False,
  18. "mods": False,
  19. "verbose": False,
  20. "folders": []
  21. }
  22. # Available CLI options
  23. options = {"recursive": ['--recursive', '-r'],
  24. "help": ['--help', '-h'],
  25. "mods": ['--installed-mods'],
  26. "verbose": ['--verbose', '-v']
  27. }
  28. # Strings longer than this will have extra space added between
  29. # them in the translation files to make it easier to distinguish their
  30. # beginnings and endings at a glance
  31. doublespace_threshold = 60
  32. def set_params_folders(tab: list):
  33. '''Initialize params["folders"] from CLI arguments.'''
  34. # Discarding argument 0 (tool name)
  35. for param in tab[1:]:
  36. stop_param = False
  37. for option in options:
  38. if param in options[option]:
  39. stop_param = True
  40. break
  41. if not stop_param:
  42. params["folders"].append(os.path.abspath(param))
  43. def set_params(tab: list):
  44. '''Initialize params from CLI arguments.'''
  45. for option in options:
  46. for option_name in options[option]:
  47. if option_name in tab:
  48. params[option] = True
  49. break
  50. def print_help(name):
  51. '''Prints some help message.'''
  52. print(f'''SYNOPSIS
  53. {name} [OPTIONS] [PATHS...]
  54. DESCRIPTION
  55. {', '.join(options["help"])}
  56. prints this help message
  57. {', '.join(options["recursive"])}
  58. run on all subfolders of paths given
  59. {', '.join(options["mods"])}
  60. run on locally installed modules
  61. {', '.join(options["verbose"])}
  62. add output information
  63. ''')
  64. def main():
  65. '''Main function'''
  66. set_params(_argv)
  67. set_params_folders(_argv)
  68. if params["help"]:
  69. print_help(_argv[0])
  70. elif params["recursive"] and params["mods"]:
  71. print("Option --installed-mods is incompatible with --recursive")
  72. else:
  73. # Add recursivity message
  74. print("Running ", end='')
  75. if params["recursive"]:
  76. print("recursively ", end='')
  77. # Running
  78. if params["mods"]:
  79. print(f"on all locally installed modules in {os.path.abspath('~/.minetest/mods/')}")
  80. run_all_subfolders("~/.minetest/mods")
  81. elif len(params["folders"]) >= 2:
  82. print("on folder list:", params["folders"])
  83. for f in params["folders"]:
  84. if params["recursive"]:
  85. run_all_subfolders(f)
  86. else:
  87. update_folder(f)
  88. elif len(params["folders"]) == 1:
  89. print("on folder", params["folders"][0])
  90. if params["recursive"]:
  91. run_all_subfolders(params["folders"][0])
  92. else:
  93. update_folder(params["folders"][0])
  94. else:
  95. print("on folder", os.path.abspath("./"))
  96. if params["recursive"]:
  97. run_all_subfolders(os.path.abspath("./"))
  98. else:
  99. update_folder(os.path.abspath("./"))
  100. #group 2 will be the string, groups 1 and 3 will be the delimiters (" or ')
  101. #See https://stackoverflow.com/questions/46967465/regex-match-text-in-either-single-or-double-quote
  102. pattern_lua = re.compile(r'[\.=^\t,{\(\s]N?S\(\s*(["\'])((?:\\\1|(?:(?!\1)).)*)(\1)[\s,\)]', re.DOTALL)
  103. pattern_lua_bracketed = re.compile(r'[\.=^\t,{\(\s]N?S\(\s*\[\[(.*?)\]\][\s,\)]', re.DOTALL)
  104. # Handles "concatenation" .. " of strings"
  105. pattern_concat = re.compile(r'["\'][\s]*\.\.[\s]*["\']', re.DOTALL)
  106. pattern_tr = re.compile(r'(.+?[^@])=(.*)')
  107. pattern_name = re.compile(r'^name[ ]*=[ ]*([^ \n]*)')
  108. pattern_tr_filename = re.compile(r'\.tr$')
  109. pattern_po_language_code = re.compile(r'(.*)\.po$')
  110. #attempt to read the mod's name from the mod.conf file. Returns None on failure
  111. def get_modname(folder):
  112. try:
  113. with open(os.path.join(folder, "mod.conf"), "r", encoding='utf-8') as mod_conf:
  114. for line in mod_conf:
  115. match = pattern_name.match(line)
  116. if match:
  117. return match.group(1)
  118. except FileNotFoundError:
  119. pass
  120. return None
  121. #If there are already .tr files in /locale, returns a list of their names
  122. def get_existing_tr_files(folder):
  123. out = []
  124. for root, dirs, files in os.walk(os.path.join(folder, 'locale/')):
  125. for name in files:
  126. if pattern_tr_filename.search(name):
  127. out.append(name)
  128. return out
  129. # A series of search and replaces that massage a .po file's contents into
  130. # a .tr file's equivalent
  131. def process_po_file(text):
  132. # The first three items are for unused matches
  133. text = re.sub(r'#~ msgid "', "", text)
  134. text = re.sub(r'"\n#~ msgstr ""\n"', "=", text)
  135. text = re.sub(r'"\n#~ msgstr "', "=", text)
  136. # comment lines
  137. text = re.sub(r'#.*\n', "", text)
  138. # converting msg pairs into "=" pairs
  139. text = re.sub(r'msgid "', "", text)
  140. text = re.sub(r'"\nmsgstr ""\n"', "=", text)
  141. text = re.sub(r'"\nmsgstr "', "=", text)
  142. # various line breaks and escape codes
  143. text = re.sub(r'"\n"', "", text)
  144. text = re.sub(r'"\n', "\n", text)
  145. text = re.sub(r'\\"', '"', text)
  146. text = re.sub(r'\\n', '@n', text)
  147. # remove header text
  148. text = re.sub(r'=Project-Id-Version:.*\n', "", text)
  149. # remove double-spaced lines
  150. text = re.sub(r'\n\n', '\n', text)
  151. return text
  152. # Go through existing .po files and, if a .tr file for that language
  153. # *doesn't* exist, convert it and create it.
  154. # The .tr file that results will subsequently be reprocessed so
  155. # any "no longer used" strings will be preserved.
  156. # Note that "fuzzy" tags will be lost in this process.
  157. def process_po_files(folder, modname):
  158. for root, dirs, files in os.walk(os.path.join(folder, 'locale/')):
  159. for name in files:
  160. code_match = pattern_po_language_code.match(name)
  161. if code_match == None:
  162. continue
  163. language_code = code_match.group(1)
  164. tr_name = modname + "." + language_code + ".tr"
  165. tr_file = os.path.join(root, tr_name)
  166. if os.path.exists(tr_file):
  167. if params["verbose"]:
  168. print(f"{tr_name} already exists, ignoring {name}")
  169. continue
  170. fname = os.path.join(root, name)
  171. with open(fname, "r", encoding='utf-8') as po_file:
  172. if params["verbose"]:
  173. print(f"Importing translations from {name}")
  174. text = process_po_file(po_file.read())
  175. with open(tr_file, "wt", encoding='utf-8') as tr_out:
  176. tr_out.write(text)
  177. # from https://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python/600612#600612
  178. # Creates a directory if it doesn't exist, silently does
  179. # nothing if it already exists
  180. def mkdir_p(path):
  181. try:
  182. os.makedirs(path)
  183. except OSError as exc: # Python >2.5
  184. if exc.errno == errno.EEXIST and os.path.isdir(path):
  185. pass
  186. else: raise
  187. # Converts the template dictionary to a text to be written as a file
  188. # dKeyStrings is a dictionary of localized string to source file sets
  189. # dOld is a dictionary of existing translations and comments from
  190. # the previous version of this text
  191. def strings_to_text(dkeyStrings, dOld, mod_name):
  192. lOut = [f"# textdomain: {mod_name}\n"]
  193. dGroupedBySource = {}
  194. for key in dkeyStrings:
  195. sourceList = list(dkeyStrings[key])
  196. sourceList.sort()
  197. sourceString = "\n".join(sourceList)
  198. listForSource = dGroupedBySource.get(sourceString, [])
  199. listForSource.append(key)
  200. dGroupedBySource[sourceString] = listForSource
  201. lSourceKeys = list(dGroupedBySource.keys())
  202. lSourceKeys.sort()
  203. for source in lSourceKeys:
  204. localizedStrings = dGroupedBySource[source]
  205. localizedStrings.sort()
  206. lOut.append("")
  207. lOut.append(source)
  208. lOut.append("")
  209. for localizedString in localizedStrings:
  210. val = dOld.get(localizedString, {})
  211. translation = val.get("translation", "")
  212. comment = val.get("comment")
  213. if len(localizedString) > doublespace_threshold and not lOut[-1] == "":
  214. lOut.append("")
  215. if comment != None:
  216. lOut.append(comment)
  217. lOut.append(f"{localizedString}={translation}")
  218. if len(localizedString) > doublespace_threshold:
  219. lOut.append("")
  220. unusedExist = False
  221. for key in dOld:
  222. if key not in dkeyStrings:
  223. val = dOld[key]
  224. translation = val.get("translation")
  225. comment = val.get("comment")
  226. # only keep an unused translation if there was translated
  227. # text or a comment associated with it
  228. if translation != None and (translation != "" or comment):
  229. if not unusedExist:
  230. unusedExist = True
  231. lOut.append("\n\n##### not used anymore #####\n")
  232. if len(key) > doublespace_threshold and not lOut[-1] == "":
  233. lOut.append("")
  234. if comment != None:
  235. lOut.append(comment)
  236. lOut.append(f"{key}={translation}")
  237. if len(key) > doublespace_threshold:
  238. lOut.append("")
  239. return "\n".join(lOut) + '\n'
  240. # Writes a template.txt file
  241. # dkeyStrings is the dictionary returned by generate_template
  242. def write_template(templ_file, dkeyStrings, mod_name):
  243. # read existing template file to preserve comments
  244. existing_template = import_tr_file(templ_file)
  245. text = strings_to_text(dkeyStrings, existing_template[0], mod_name)
  246. mkdir_p(os.path.dirname(templ_file))
  247. with open(templ_file, "wt", encoding='utf-8') as template_file:
  248. template_file.write(text)
  249. # Gets all translatable strings from a lua file
  250. def read_lua_file_strings(lua_file):
  251. lOut = []
  252. with open(lua_file, encoding='utf-8') as text_file:
  253. text = text_file.read()
  254. #TODO remove comments here
  255. text = re.sub(pattern_concat, "", text)
  256. strings = []
  257. for s in pattern_lua.findall(text):
  258. strings.append(s[1])
  259. for s in pattern_lua_bracketed.findall(text):
  260. strings.append(s)
  261. for s in strings:
  262. s = re.sub(r'"\.\.\s+"', "", s)
  263. s = re.sub("@[^@=0-9]", "@@", s)
  264. s = s.replace('\\"', '"')
  265. s = s.replace("\\'", "'")
  266. s = s.replace("\n", "@n")
  267. s = s.replace("\\n", "@n")
  268. s = s.replace("=", "@=")
  269. lOut.append(s)
  270. return lOut
  271. # Gets strings from an existing translation file
  272. # returns both a dictionary of translations
  273. # and the full original source text so that the new text
  274. # can be compared to it for changes.
  275. def import_tr_file(tr_file):
  276. dOut = {}
  277. text = None
  278. if os.path.exists(tr_file):
  279. with open(tr_file, "r", encoding='utf-8') as existing_file :
  280. # save the full text to allow for comparison
  281. # of the old version with the new output
  282. text = existing_file.read()
  283. existing_file.seek(0)
  284. # a running record of the current comment block
  285. # we're inside, to allow preceeding multi-line comments
  286. # to be retained for a translation line
  287. latest_comment_block = None
  288. for line in existing_file.readlines():
  289. line = line.rstrip('\n')
  290. if line[:3] == "###":
  291. # Reset comment block if we hit a header
  292. latest_comment_block = None
  293. continue
  294. if line[:1] == "#":
  295. # Save the comment we're inside
  296. if not latest_comment_block:
  297. latest_comment_block = line
  298. else:
  299. latest_comment_block = latest_comment_block + "\n" + line
  300. continue
  301. match = pattern_tr.match(line)
  302. if match:
  303. # this line is a translated line
  304. outval = {}
  305. outval["translation"] = match.group(2)
  306. if latest_comment_block:
  307. # if there was a comment, record that.
  308. outval["comment"] = latest_comment_block
  309. latest_comment_block = None
  310. dOut[match.group(1)] = outval
  311. return (dOut, text)
  312. # Walks all lua files in the mod folder, collects translatable strings,
  313. # and writes it to a template.txt file
  314. # Returns a dictionary of localized strings to source file sets
  315. # that can be used with the strings_to_text function.
  316. def generate_template(folder, mod_name):
  317. dOut = {}
  318. for root, dirs, files in os.walk(folder):
  319. for name in files:
  320. if fnmatch.fnmatch(name, "*.lua"):
  321. fname = os.path.join(root, name)
  322. found = read_lua_file_strings(fname)
  323. if params["verbose"]:
  324. print(f"{fname}: {str(len(found))} translatable strings")
  325. for s in found:
  326. sources = dOut.get(s, set())
  327. sources.add(f"### {os.path.basename(fname)} ###")
  328. dOut[s] = sources
  329. if len(dOut) == 0:
  330. return None
  331. templ_file = os.path.join(folder, "locale/template.txt")
  332. write_template(templ_file, dOut, mod_name)
  333. return dOut
  334. # Updates an existing .tr file, copying the old one to a ".old" file
  335. # if any changes have happened
  336. # dNew is the data used to generate the template, it has all the
  337. # currently-existing localized strings
  338. def update_tr_file(dNew, mod_name, tr_file):
  339. if params["verbose"]:
  340. print(f"updating {tr_file}")
  341. tr_import = import_tr_file(tr_file)
  342. dOld = tr_import[0]
  343. textOld = tr_import[1]
  344. textNew = strings_to_text(dNew, dOld, mod_name)
  345. if textOld and textOld != textNew:
  346. print(f"{tr_file} has changed.")
  347. shutil.copyfile(tr_file, f"{tr_file}.old")
  348. with open(tr_file, "w", encoding='utf-8') as new_tr_file:
  349. new_tr_file.write(textNew)
  350. # Updates translation files for the mod in the given folder
  351. def update_mod(folder):
  352. modname = get_modname(folder)
  353. if modname is not None:
  354. process_po_files(folder, modname)
  355. print(f"Updating translations for {modname}")
  356. data = generate_template(folder, modname)
  357. if data == None:
  358. print(f"No translatable strings found in {modname}")
  359. else:
  360. for tr_file in get_existing_tr_files(folder):
  361. update_tr_file(data, modname, os.path.join(folder, "locale/", tr_file))
  362. else:
  363. print("Unable to find modname in folder " + folder)
  364. # Determines if the folder being pointed to is a mod or a mod pack
  365. # and then runs update_mod accordingly
  366. def update_folder(folder):
  367. is_modpack = os.path.exists(os.path.join(folder, "modpack.txt")) or os.path.exists(os.path.join(folder, "modpack.conf"))
  368. if is_modpack:
  369. subfolders = [f.path for f in os.scandir(folder) if f.is_dir()]
  370. for subfolder in subfolders:
  371. update_mod(subfolder + "/")
  372. else:
  373. update_mod(folder)
  374. print("Done.")
  375. def run_all_subfolders(folder):
  376. for modfolder in [f.path for f in os.scandir(folder) if f.is_dir()]:
  377. update_folder(modfolder + "/")
  378. main()