extract.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. #!/usr/bin/env python3
  2. import argparse
  3. import os
  4. import shutil
  5. from collections import OrderedDict
  6. EXTRACT_TAGS = ["description", "brief_description", "member", "constant", "theme_item", "link"]
  7. HEADER = """\
  8. # LANGUAGE translation of the Godot Engine class reference.
  9. # Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md).
  10. # Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur.
  11. # This file is distributed under the same license as the Godot source code.
  12. #
  13. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
  14. #
  15. #, fuzzy
  16. msgid ""
  17. msgstr ""
  18. "Project-Id-Version: Godot Engine class reference\\n"
  19. "Report-Msgid-Bugs-To: https://github.com/godotengine/godot\\n"
  20. "MIME-Version: 1.0\\n"
  21. "Content-Type: text/plain; charset=UTF-8\\n"
  22. "Content-Transfer-Encoding: 8-bit\\n"
  23. """
  24. # Some strings used by make_rst.py are normally part of the editor translations,
  25. # so we need to include them manually here for the online docs.
  26. BASE_STRINGS = [
  27. "Description",
  28. "Tutorials",
  29. "Properties",
  30. "Methods",
  31. "Theme Properties",
  32. "Signals",
  33. "Enumerations",
  34. "Constants",
  35. "Property Descriptions",
  36. "Method Descriptions",
  37. "Theme Property Descriptions",
  38. "Inherits:",
  39. "Inherited By:",
  40. "(overrides %s)",
  41. "Default",
  42. "Setter",
  43. "value",
  44. "Getter",
  45. "This method should typically be overridden by the user to have any effect.",
  46. "This method has no side effects. It doesn't modify any of the instance's member variables.",
  47. "This method accepts any number of arguments after the ones described here.",
  48. "This method is used to construct a type.",
  49. "This method doesn't need an instance to be called, so it can be called directly using the class name.",
  50. "This method describes a valid operator to use with this type as left-hand operand.",
  51. ]
  52. ## <xml-line-number-hack from="https://stackoverflow.com/a/36430270/10846399">
  53. import sys
  54. sys.modules["_elementtree"] = None
  55. import xml.etree.ElementTree as ET
  56. ## override the parser to get the line number
  57. class LineNumberingParser(ET.XMLParser):
  58. def _start(self, *args, **kwargs):
  59. ## Here we assume the default XML parser which is expat
  60. ## and copy its element position attributes into output Elements
  61. element = super(self.__class__, self)._start(*args, **kwargs)
  62. element._start_line_number = self.parser.CurrentLineNumber
  63. element._start_column_number = self.parser.CurrentColumnNumber
  64. element._start_byte_index = self.parser.CurrentByteIndex
  65. return element
  66. def _end(self, *args, **kwargs):
  67. element = super(self.__class__, self)._end(*args, **kwargs)
  68. element._end_line_number = self.parser.CurrentLineNumber
  69. element._end_column_number = self.parser.CurrentColumnNumber
  70. element._end_byte_index = self.parser.CurrentByteIndex
  71. return element
  72. ## </xml-line-number-hack>
  73. class Desc:
  74. def __init__(self, line_no, msg, desc_list=None):
  75. ## line_no : the line number where the desc is
  76. ## msg : the description string
  77. ## desc_list : the DescList it belongs to
  78. self.line_no = line_no
  79. self.msg = msg
  80. self.desc_list = desc_list
  81. class DescList:
  82. def __init__(self, doc, path):
  83. ## doc : root xml element of the document
  84. ## path : file path of the xml document
  85. ## list : list of Desc objects for this document
  86. self.doc = doc
  87. self.path = path
  88. self.list = []
  89. def print_error(error):
  90. print("ERROR: {}".format(error))
  91. ## build classes with xml elements recursively
  92. def _collect_classes_dir(path, classes):
  93. if not os.path.isdir(path):
  94. print_error("Invalid directory path: {}".format(path))
  95. exit(1)
  96. for _dir in map(lambda dir: os.path.join(path, dir), os.listdir(path)):
  97. if os.path.isdir(_dir):
  98. _collect_classes_dir(_dir, classes)
  99. elif os.path.isfile(_dir):
  100. if not _dir.endswith(".xml"):
  101. # print("Got non-.xml file '{}', skipping.".format(path))
  102. continue
  103. _collect_classes_file(_dir, classes)
  104. ## opens a file and parse xml add to classes
  105. def _collect_classes_file(path, classes):
  106. if not os.path.isfile(path) or not path.endswith(".xml"):
  107. print_error("Invalid xml file path: {}".format(path))
  108. exit(1)
  109. print("Collecting file: {}".format(os.path.basename(path)))
  110. try:
  111. tree = ET.parse(path, parser=LineNumberingParser())
  112. except ET.ParseError as e:
  113. print_error("Parse error reading file '{}': {}".format(path, e))
  114. exit(1)
  115. doc = tree.getroot()
  116. if "name" in doc.attrib:
  117. if "version" not in doc.attrib:
  118. print_error("Version missing from 'doc', file: {}".format(path))
  119. name = doc.attrib["name"]
  120. if name in classes:
  121. print_error("Duplicate class {} at path {}".format(name, path))
  122. exit(1)
  123. classes[name] = DescList(doc, path)
  124. else:
  125. print_error("Unknown XML file {}, skipping".format(path))
  126. ## regions are list of tuples with size 3 (start_index, end_index, indent)
  127. ## indication in string where the codeblock starts, ends, and it's indent
  128. ## if i inside the region returns the indent, else returns -1
  129. def _get_xml_indent(i, regions):
  130. for region in regions:
  131. if region[0] < i < region[1]:
  132. return region[2]
  133. return -1
  134. ## find and build all regions of codeblock which we need later
  135. def _make_codeblock_regions(desc, path=""):
  136. code_block_end = False
  137. code_block_index = 0
  138. code_block_regions = []
  139. while not code_block_end:
  140. code_block_index = desc.find("[codeblock]", code_block_index)
  141. if code_block_index < 0:
  142. break
  143. xml_indent = 0
  144. while True:
  145. ## [codeblock] always have a trailing new line and some tabs
  146. ## those tabs are belongs to xml indentations not code indent
  147. if desc[code_block_index + len("[codeblock]\n") + xml_indent] == "\t":
  148. xml_indent += 1
  149. else:
  150. break
  151. end_index = desc.find("[/codeblock]", code_block_index)
  152. if end_index < 0:
  153. print_error("Non terminating codeblock: {}".format(path))
  154. exit(1)
  155. code_block_regions.append((code_block_index, end_index, xml_indent))
  156. code_block_index += 1
  157. return code_block_regions
  158. def _strip_and_split_desc(desc, code_block_regions):
  159. desc_strip = "" ## a stripped desc msg
  160. total_indent = 0 ## code indent = total indent - xml indent
  161. for i in range(len(desc)):
  162. c = desc[i]
  163. if c == "\n":
  164. c = "\\n"
  165. if c == '"':
  166. c = '\\"'
  167. if c == "\\":
  168. c = "\\\\" ## <element \> is invalid for msgmerge
  169. if c == "\t":
  170. xml_indent = _get_xml_indent(i, code_block_regions)
  171. if xml_indent >= 0:
  172. total_indent += 1
  173. if xml_indent < total_indent:
  174. c = "\\t"
  175. else:
  176. continue
  177. else:
  178. continue
  179. desc_strip += c
  180. if c == "\\n":
  181. total_indent = 0
  182. return desc_strip
  183. ## make catalog strings from xml elements
  184. def _make_translation_catalog(classes):
  185. unique_msgs = OrderedDict()
  186. for class_name in classes:
  187. desc_list = classes[class_name]
  188. for elem in desc_list.doc.iter():
  189. if elem.tag in EXTRACT_TAGS:
  190. elem_text = elem.text
  191. if elem.tag == "link":
  192. elem_text = elem.attrib["title"] if "title" in elem.attrib else ""
  193. if not elem_text or len(elem_text) == 0:
  194. continue
  195. line_no = elem._start_line_number if elem_text[0] != "\n" else elem._start_line_number + 1
  196. desc_str = elem_text.strip()
  197. code_block_regions = _make_codeblock_regions(desc_str, desc_list.path)
  198. desc_msg = _strip_and_split_desc(desc_str, code_block_regions)
  199. desc_obj = Desc(line_no, desc_msg, desc_list)
  200. desc_list.list.append(desc_obj)
  201. if desc_msg not in unique_msgs:
  202. unique_msgs[desc_msg] = [desc_obj]
  203. else:
  204. unique_msgs[desc_msg].append(desc_obj)
  205. return unique_msgs
  206. ## generate the catalog file
  207. def _generate_translation_catalog_file(unique_msgs, output, location_line=False):
  208. with open(output, "w", encoding="utf8") as f:
  209. f.write(HEADER)
  210. for msg in BASE_STRINGS:
  211. f.write("#: doc/tools/make_rst.py\n")
  212. f.write('msgid "{}"\n'.format(msg))
  213. f.write('msgstr ""\n\n')
  214. for msg in unique_msgs:
  215. if len(msg) == 0 or msg in BASE_STRINGS:
  216. continue
  217. f.write("#:")
  218. desc_list = unique_msgs[msg]
  219. for desc in desc_list:
  220. path = desc.desc_list.path.replace("\\", "/")
  221. if path.startswith("./"):
  222. path = path[2:]
  223. if location_line: # Can be skipped as diffs on line numbers are spammy.
  224. f.write(" {}:{}".format(path, desc.line_no))
  225. else:
  226. f.write(" {}".format(path))
  227. f.write("\n")
  228. f.write('msgid "{}"\n'.format(msg))
  229. f.write('msgstr ""\n\n')
  230. ## TODO: what if 'nt'?
  231. if os.name == "posix":
  232. print("Wrapping template at 79 characters for compatibility with Weblate.")
  233. os.system("msgmerge -w79 {0} {0} > {0}.wrap".format(output))
  234. shutil.move("{}.wrap".format(output), output)
  235. def main():
  236. parser = argparse.ArgumentParser()
  237. parser.add_argument(
  238. "--path", "-p", nargs="+", default=".", help="The directory or directories containing XML files to collect."
  239. )
  240. parser.add_argument("--output", "-o", default="translation_catalog.pot", help="The path to the output file.")
  241. args = parser.parse_args()
  242. output = os.path.abspath(args.output)
  243. if not os.path.isdir(os.path.dirname(output)) or not output.endswith(".pot"):
  244. print_error("Invalid output path: {}".format(output))
  245. exit(1)
  246. classes = OrderedDict()
  247. for path in args.path:
  248. if not os.path.isdir(path):
  249. print_error("Invalid working directory path: {}".format(path))
  250. exit(1)
  251. print("\nCurrent working dir: {}".format(path))
  252. path_classes = OrderedDict() ## dictionary of key=class_name, value=DescList objects
  253. _collect_classes_dir(path, path_classes)
  254. classes.update(path_classes)
  255. classes = OrderedDict(sorted(classes.items(), key=lambda kv: kv[0].lower()))
  256. unique_msgs = _make_translation_catalog(classes)
  257. _generate_translation_catalog_file(unique_msgs, output)
  258. if __name__ == "__main__":
  259. main()