i18n.py 17 KB

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