i18n.py 17 KB

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