makerst.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import codecs
  4. import sys
  5. import os
  6. import re
  7. import xml.etree.ElementTree as ET
  8. input_list = []
  9. cur_file = ""
  10. # http(s)://docs.godotengine.org/<langcode>/<tag>/path/to/page.html(#fragment-tag)
  11. godot_docs_pattern = re.compile('^http(?:s)?:\/\/docs\.godotengine\.org\/(?:[a-zA-Z0-9\.\-_]*)\/(?:[a-zA-Z0-9\.\-_]*)\/(.*)\.html(#.*)?$')
  12. for arg in sys.argv[1:]:
  13. if arg.endswith(os.sep):
  14. arg = arg[:-1]
  15. input_list.append(arg)
  16. if len(input_list) < 1:
  17. print('usage: makerst.py <path to folders> and/or <path to .xml files> (order of arguments irrelevant)')
  18. print('example: makerst.py "../../modules/" "../classes" path_to/some_class.xml')
  19. sys.exit(0)
  20. def validate_tag(elem, tag):
  21. if elem.tag != tag:
  22. print("Tag mismatch, expected '" + tag + "', got " + elem.tag)
  23. sys.exit(255)
  24. class_names = []
  25. classes = {}
  26. def ul_string(str, ul):
  27. str += "\n"
  28. for i in range(len(str) - 1):
  29. str += ul
  30. str += "\n"
  31. return str
  32. def make_class_list(class_list, columns):
  33. f = codecs.open('class_list.rst', 'wb', 'utf-8')
  34. prev = 0
  35. col_max = len(class_list) / columns + 1
  36. print(('col max is ', col_max))
  37. col_count = 0
  38. row_count = 0
  39. last_initial = ''
  40. fit_columns = []
  41. for n in range(0, columns):
  42. fit_columns += [[]]
  43. indexers = []
  44. last_initial = ''
  45. idx = 0
  46. for n in class_list:
  47. col = idx / col_max
  48. if col >= columns:
  49. col = columns - 1
  50. fit_columns[col] += [n]
  51. idx += 1
  52. if n[:1] != last_initial:
  53. indexers += [n]
  54. last_initial = n[:1]
  55. row_max = 0
  56. f.write("\n")
  57. for n in range(0, columns):
  58. if len(fit_columns[n]) > row_max:
  59. row_max = len(fit_columns[n])
  60. f.write("| ")
  61. for n in range(0, columns):
  62. f.write(" | |")
  63. f.write("\n")
  64. f.write("+")
  65. for n in range(0, columns):
  66. f.write("--+-------+")
  67. f.write("\n")
  68. for r in range(0, row_max):
  69. s = '+ '
  70. for c in range(0, columns):
  71. if r >= len(fit_columns[c]):
  72. continue
  73. classname = fit_columns[c][r]
  74. initial = classname[0]
  75. if classname in indexers:
  76. s += '**' + initial + '** | '
  77. else:
  78. s += ' | '
  79. s += '[' + classname + '](class_' + classname.lower() + ') | '
  80. s += '\n'
  81. f.write(s)
  82. for n in range(0, columns):
  83. f.write("--+-------+")
  84. f.write("\n")
  85. f.close()
  86. def rstize_text(text, cclass):
  87. # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock"
  88. pos = 0
  89. while True:
  90. pos = text.find('\n', pos)
  91. if pos == -1:
  92. break
  93. pre_text = text[:pos]
  94. while text[pos + 1] == '\t':
  95. pos += 1
  96. post_text = text[pos + 1:]
  97. # Handle codeblocks
  98. if post_text.startswith("[codeblock]"):
  99. end_pos = post_text.find("[/codeblock]")
  100. if end_pos == -1:
  101. sys.exit("ERROR! [codeblock] without a closing tag!")
  102. code_text = post_text[len("[codeblock]"):end_pos]
  103. post_text = post_text[end_pos:]
  104. # Remove extraneous tabs
  105. code_pos = 0
  106. while True:
  107. code_pos = code_text.find('\n', code_pos)
  108. if code_pos == -1:
  109. break
  110. to_skip = 0
  111. while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == '\t':
  112. to_skip += 1
  113. if len(code_text[code_pos + to_skip + 1:]) == 0:
  114. code_text = code_text[:code_pos] + "\n"
  115. code_pos += 1
  116. else:
  117. code_text = code_text[:code_pos] + "\n " + code_text[code_pos + to_skip + 1:]
  118. code_pos += 5 - to_skip
  119. text = pre_text + "\n[codeblock]" + code_text + post_text
  120. pos += len("\n[codeblock]" + code_text)
  121. # Handle normal text
  122. else:
  123. text = pre_text + "\n\n" + post_text
  124. pos += 2
  125. next_brac_pos = text.find('[')
  126. # Escape \ character, otherwise it ends up as an escape character in rst
  127. pos = 0
  128. while True:
  129. pos = text.find('\\', pos, next_brac_pos)
  130. if pos == -1:
  131. break
  132. text = text[:pos] + "\\\\" + text[pos + 1:]
  133. pos += 2
  134. # Escape * character to avoid interpreting it as emphasis
  135. pos = 0
  136. while True:
  137. pos = text.find('*', pos, next_brac_pos)
  138. if pos == -1:
  139. break
  140. text = text[:pos] + "\*" + text[pos + 1:]
  141. pos += 2
  142. # Escape _ character at the end of a word to avoid interpreting it as an inline hyperlink
  143. pos = 0
  144. while True:
  145. pos = text.find('_', pos, next_brac_pos)
  146. if pos == -1:
  147. break
  148. if not text[pos + 1].isalnum(): # don't escape within a snake_case word
  149. text = text[:pos] + "\_" + text[pos + 1:]
  150. pos += 2
  151. else:
  152. pos += 1
  153. # Handle [tags]
  154. inside_code = False
  155. pos = 0
  156. while True:
  157. pos = text.find('[', pos)
  158. if pos == -1:
  159. break
  160. endq_pos = text.find(']', pos + 1)
  161. if endq_pos == -1:
  162. break
  163. pre_text = text[:pos]
  164. post_text = text[endq_pos + 1:]
  165. tag_text = text[pos + 1:endq_pos]
  166. escape_post = False
  167. if tag_text in class_names:
  168. tag_text = make_type(tag_text)
  169. escape_post = True
  170. else: # command
  171. cmd = tag_text
  172. space_pos = tag_text.find(' ')
  173. if cmd == '/codeblock':
  174. tag_text = ''
  175. inside_code = False
  176. # Strip newline if the tag was alone on one
  177. if pre_text[-1] == '\n':
  178. pre_text = pre_text[:-1]
  179. elif cmd == '/code':
  180. tag_text = '``'
  181. inside_code = False
  182. escape_post = True
  183. elif inside_code:
  184. tag_text = '[' + tag_text + ']'
  185. elif cmd.find('html') == 0:
  186. cmd = tag_text[:space_pos]
  187. param = tag_text[space_pos + 1:]
  188. tag_text = param
  189. elif cmd.find('method') == 0 or cmd.find('member') == 0 or cmd.find('signal') == 0:
  190. cmd = tag_text[:space_pos]
  191. param = tag_text[space_pos + 1:]
  192. if param.find('.') != -1:
  193. ss = param.split('.')
  194. if len(ss) > 2:
  195. sys.exit("Bad reference: '" + param + "' in file: " + cur_file)
  196. (class_param, method_param) = ss
  197. tag_text = ':ref:`' + class_param + '.' + method_param + '<class_' + class_param + '_' + method_param + '>`'
  198. else:
  199. tag_text = ':ref:`' + param + '<class_' + cclass + "_" + param + '>`'
  200. escape_post = True
  201. elif cmd.find('image=') == 0:
  202. tag_text = "" # '![](' + cmd[6:] + ')'
  203. elif cmd.find('url=') == 0:
  204. tag_text = ':ref:`' + cmd[4:] + '<' + cmd[4:] + ">`"
  205. elif cmd == '/url':
  206. tag_text = ''
  207. escape_post = True
  208. elif cmd == 'center':
  209. tag_text = ''
  210. elif cmd == '/center':
  211. tag_text = ''
  212. elif cmd == 'codeblock':
  213. tag_text = '\n::\n'
  214. inside_code = True
  215. elif cmd == 'br':
  216. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  217. tag_text = '\n\n'
  218. # Strip potential leading spaces
  219. while post_text[0] == ' ':
  220. post_text = post_text[1:]
  221. elif cmd == 'i' or cmd == '/i':
  222. tag_text = '*'
  223. elif cmd == 'b' or cmd == '/b':
  224. tag_text = '**'
  225. elif cmd == 'u' or cmd == '/u':
  226. tag_text = ''
  227. elif cmd == 'code':
  228. tag_text = '``'
  229. inside_code = True
  230. elif cmd.startswith('enum '):
  231. tag_text = make_enum(cmd[5:])
  232. else:
  233. tag_text = make_type(tag_text)
  234. escape_post = True
  235. # Properly escape things like `[Node]s`
  236. if escape_post and post_text and post_text[0].isalnum(): # not punctuation, escape
  237. post_text = '\ ' + post_text
  238. next_brac_pos = post_text.find('[', 0)
  239. iter_pos = 0
  240. while not inside_code:
  241. iter_pos = post_text.find('*', iter_pos, next_brac_pos)
  242. if iter_pos == -1:
  243. break
  244. post_text = post_text[:iter_pos] + "\*" + post_text[iter_pos + 1:]
  245. iter_pos += 2
  246. iter_pos = 0
  247. while not inside_code:
  248. iter_pos = post_text.find('_', iter_pos, next_brac_pos)
  249. if iter_pos == -1:
  250. break
  251. if not post_text[iter_pos + 1].isalnum(): # don't escape within a snake_case word
  252. post_text = post_text[:iter_pos] + "\_" + post_text[iter_pos + 1:]
  253. iter_pos += 2
  254. else:
  255. iter_pos += 1
  256. text = pre_text + tag_text + post_text
  257. pos = len(pre_text) + len(tag_text)
  258. return text
  259. def make_type(t):
  260. global class_names
  261. if t in class_names:
  262. return ':ref:`' + t + '<class_' + t.lower() + '>`'
  263. return t
  264. def make_enum(t):
  265. global class_names
  266. p = t.find(".")
  267. # Global enums such as Error are relative to @GlobalScope.
  268. if p >= 0:
  269. c = t[0:p]
  270. e = t[p + 1:]
  271. # Variant enums live in GlobalScope but still use periods.
  272. if c == "Variant":
  273. c = "@GlobalScope"
  274. e = "Variant." + e
  275. else:
  276. # Things in GlobalScope don't have a period.
  277. c = "@GlobalScope"
  278. e = t
  279. if c in class_names:
  280. return ':ref:`' + e + '<enum_' + c.lower() + '_' + e.lower() + '>`'
  281. return t
  282. def make_method(
  283. f,
  284. name,
  285. m,
  286. declare,
  287. cname,
  288. event=False,
  289. pp=None
  290. ):
  291. if (declare or pp == None):
  292. t = '- '
  293. else:
  294. t = ""
  295. ret_type = 'void'
  296. args = list(m)
  297. mdata = {}
  298. mdata['argidx'] = []
  299. for a in args:
  300. if a.tag == 'return':
  301. idx = -1
  302. elif a.tag == 'argument':
  303. idx = int(a.attrib['index'])
  304. else:
  305. continue
  306. mdata['argidx'].append(idx)
  307. mdata[idx] = a
  308. if not event:
  309. if -1 in mdata['argidx']:
  310. if 'enum' in mdata[-1].attrib:
  311. t += make_enum(mdata[-1].attrib['enum'])
  312. else:
  313. t += make_type(mdata[-1].attrib['type'])
  314. else:
  315. t += 'void'
  316. t += ' '
  317. if declare or pp == None:
  318. s = '**' + m.attrib['name'] + '** '
  319. else:
  320. s = ':ref:`' + m.attrib['name'] + '<class_' + cname + "_" + m.attrib['name'] + '>` '
  321. s += '**(**'
  322. argfound = False
  323. for a in mdata['argidx']:
  324. arg = mdata[a]
  325. if a < 0:
  326. continue
  327. if a > 0:
  328. s += ', '
  329. else:
  330. s += ' '
  331. if 'enum' in arg.attrib:
  332. s += make_enum(arg.attrib['enum'])
  333. else:
  334. s += make_type(arg.attrib['type'])
  335. if 'name' in arg.attrib:
  336. s += ' ' + arg.attrib['name']
  337. else:
  338. s += ' arg' + str(a)
  339. if 'default' in arg.attrib:
  340. s += '=' + arg.attrib['default']
  341. s += ' **)**'
  342. if 'qualifiers' in m.attrib:
  343. s += ' ' + m.attrib['qualifiers']
  344. if (not declare):
  345. if (pp != None):
  346. pp.append((t, s))
  347. else:
  348. f.write("- " + t + " " + s + "\n")
  349. else:
  350. f.write(t + s + "\n")
  351. def make_heading(title, underline):
  352. return title + '\n' + underline * len(title) + "\n\n"
  353. def make_rst_class(node):
  354. name = node.attrib['name']
  355. f = codecs.open("class_" + name.lower() + '.rst', 'wb', 'utf-8')
  356. # Warn contributors not to edit this file directly
  357. f.write(".. Generated automatically by doc/tools/makerst.py in Godot's source tree.\n")
  358. f.write(".. DO NOT EDIT THIS FILE, but the " + name + ".xml source instead.\n")
  359. f.write(".. The source is found in doc/classes or modules/<name>/doc_classes.\n\n")
  360. f.write(".. _class_" + name + ":\n\n")
  361. f.write(make_heading(name, '='))
  362. if 'inherits' in node.attrib:
  363. inh = node.attrib['inherits'].strip()
  364. f.write('**Inherits:** ')
  365. first = True
  366. while (inh in classes):
  367. if (not first):
  368. f.write(" **<** ")
  369. else:
  370. first = False
  371. f.write(make_type(inh))
  372. inode = classes[inh]
  373. if ('inherits' in inode.attrib):
  374. inh = inode.attrib['inherits'].strip()
  375. else:
  376. inh = None
  377. f.write("\n\n")
  378. inherited = []
  379. for cn in classes:
  380. c = classes[cn]
  381. if 'inherits' in c.attrib:
  382. if (c.attrib['inherits'].strip() == name):
  383. inherited.append(c.attrib['name'])
  384. if (len(inherited)):
  385. f.write('**Inherited By:** ')
  386. for i in range(len(inherited)):
  387. if (i > 0):
  388. f.write(", ")
  389. f.write(make_type(inherited[i]))
  390. f.write("\n\n")
  391. if 'category' in node.attrib:
  392. f.write('**Category:** ' + node.attrib['category'].strip() + "\n\n")
  393. f.write(make_heading('Brief Description', '-'))
  394. briefd = node.find('brief_description')
  395. if briefd != None:
  396. f.write(rstize_text(briefd.text.strip(), name) + "\n\n")
  397. methods = node.find('methods')
  398. if methods != None and len(list(methods)) > 0:
  399. f.write(make_heading('Member Functions', '-'))
  400. ml = []
  401. for m in list(methods):
  402. make_method(f, node.attrib['name'], m, False, name, False, ml)
  403. longest_t = 0
  404. longest_s = 0
  405. for s in ml:
  406. sl = len(s[0])
  407. if (sl > longest_s):
  408. longest_s = sl
  409. tl = len(s[1])
  410. if (tl > longest_t):
  411. longest_t = tl
  412. sep = "+"
  413. for i in range(longest_s + 2):
  414. sep += "-"
  415. sep += "+"
  416. for i in range(longest_t + 2):
  417. sep += "-"
  418. sep += "+\n"
  419. f.write(sep)
  420. for s in ml:
  421. rt = s[0]
  422. while (len(rt) < longest_s):
  423. rt += " "
  424. st = s[1]
  425. while (len(st) < longest_t):
  426. st += " "
  427. f.write("| " + rt + " | " + st + " |\n")
  428. f.write(sep)
  429. f.write('\n')
  430. events = node.find('signals')
  431. if events != None and len(list(events)) > 0:
  432. f.write(make_heading('Signals', '-'))
  433. for m in list(events):
  434. f.write(".. _class_" + name + "_" + m.attrib['name'] + ":\n\n")
  435. make_method(f, node.attrib['name'], m, True, name, True)
  436. f.write('\n')
  437. d = m.find('description')
  438. if d == None or d.text.strip() == '':
  439. continue
  440. f.write(rstize_text(d.text.strip(), name))
  441. f.write("\n\n")
  442. f.write('\n')
  443. members = node.find('members')
  444. if members != None and len(list(members)) > 0:
  445. f.write(make_heading('Member Variables', '-'))
  446. for c in list(members):
  447. # Leading two spaces necessary to prevent breaking the <ul>
  448. f.write(" .. _class_" + name + "_" + c.attrib['name'] + ":\n\n")
  449. s = '- '
  450. if 'enum' in c.attrib:
  451. s += make_enum(c.attrib['enum']) + ' '
  452. else:
  453. s += make_type(c.attrib['type']) + ' '
  454. s += '**' + c.attrib['name'] + '**'
  455. if c.text.strip() != '':
  456. s += ' - ' + rstize_text(c.text.strip(), name)
  457. f.write(s + '\n\n')
  458. f.write('\n')
  459. constants = node.find('constants')
  460. consts = []
  461. enum_names = set()
  462. enums = []
  463. if constants != None and len(list(constants)) > 0:
  464. for c in list(constants):
  465. if 'enum' in c.attrib:
  466. enum_names.add(c.attrib['enum'])
  467. enums.append(c)
  468. else:
  469. consts.append(c)
  470. if len(consts) > 0:
  471. f.write(make_heading('Numeric Constants', '-'))
  472. for c in list(consts):
  473. s = '- '
  474. s += '**' + c.attrib['name'] + '**'
  475. if 'value' in c.attrib:
  476. s += ' = **' + c.attrib['value'] + '**'
  477. if c.text.strip() != '':
  478. s += ' --- ' + rstize_text(c.text.strip(), name)
  479. f.write(s + '\n')
  480. f.write('\n')
  481. if len(enum_names) > 0:
  482. f.write(make_heading('Enums', '-'))
  483. for e in enum_names:
  484. f.write(" .. _enum_" + name + "_" + e + ":\n\n")
  485. f.write("enum **" + e + "**\n\n")
  486. for c in enums:
  487. if c.attrib['enum'] != e:
  488. continue
  489. s = '- '
  490. s += '**' + c.attrib['name'] + '**'
  491. if 'value' in c.attrib:
  492. s += ' = **' + c.attrib['value'] + '**'
  493. if c.text.strip() != '':
  494. s += ' --- ' + rstize_text(c.text.strip(), name)
  495. f.write(s + '\n')
  496. f.write('\n')
  497. f.write('\n')
  498. descr = node.find('description')
  499. if descr != None and descr.text.strip() != '':
  500. f.write(make_heading('Description', '-'))
  501. f.write(rstize_text(descr.text.strip(), name) + "\n\n")
  502. global godot_docs_pattern
  503. tutorials = node.find('tutorials')
  504. if tutorials != None and len(tutorials) > 0:
  505. f.write(make_heading('Tutorials', '-'))
  506. for t in tutorials:
  507. link = t.text.strip()
  508. match = godot_docs_pattern.search(link);
  509. if match:
  510. groups = match.groups()
  511. if match.lastindex == 2:
  512. # Doc reference with fragment identifier: emit direct link to section with reference to page, for example:
  513. # `#calling-javascript-from-script in Exporting For Web`
  514. f.write("- `" + groups[1] + " <../" + groups[0] + ".html" + groups[1] + ">`_ in :doc:`../" + groups[0] + "`\n")
  515. # Commented out alternative: Instead just emit:
  516. # `Subsection in Exporting For Web`
  517. # f.write("- `Subsection <../" + groups[0] + ".html" + groups[1] + ">`_ in :doc:`../" + groups[0] + "`\n")
  518. elif match.lastindex == 1:
  519. # Doc reference, for example:
  520. # `Math`
  521. f.write("- :doc:`../" + groups[0] + "`\n")
  522. else:
  523. # External link, for example:
  524. # `http://enet.bespin.org/usergroup0.html`
  525. f.write("- `" + link + " <" + link + ">`_\n")
  526. f.write("\n")
  527. methods = node.find('methods')
  528. if methods != None and len(list(methods)) > 0:
  529. f.write(make_heading('Member Function Description', '-'))
  530. for m in list(methods):
  531. f.write(".. _class_" + name + "_" + m.attrib['name'] + ":\n\n")
  532. make_method(f, node.attrib['name'], m, True, name)
  533. f.write('\n')
  534. d = m.find('description')
  535. if d == None or d.text.strip() == '':
  536. continue
  537. f.write(rstize_text(d.text.strip(), name))
  538. f.write("\n\n")
  539. f.write('\n')
  540. f.close()
  541. file_list = []
  542. for path in input_list:
  543. if os.path.basename(path) == 'modules':
  544. for subdir, dirs, _ in os.walk(path):
  545. if 'doc_classes' in dirs:
  546. doc_dir = os.path.join(subdir, 'doc_classes')
  547. class_file_names = [f for f in os.listdir(doc_dir) if f.endswith('.xml')]
  548. file_list += [os.path.join(doc_dir, f) for f in class_file_names]
  549. elif not os.path.isfile(path):
  550. file_list += [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.xml')]
  551. elif os.path.isfile(path) and path.endswith('.xml'):
  552. file_list.append(path)
  553. for cur_file in file_list:
  554. tree = ET.parse(cur_file)
  555. doc = tree.getroot()
  556. if 'version' not in doc.attrib:
  557. print("Version missing from 'doc'")
  558. sys.exit(255)
  559. version = doc.attrib['version']
  560. if doc.attrib['name'] in class_names:
  561. continue
  562. class_names.append(doc.attrib['name'])
  563. classes[doc.attrib['name']] = doc
  564. class_names.sort()
  565. # Don't make class list for Sphinx, :toctree: handles it
  566. # make_class_list(class_names, 2)
  567. for cn in class_names:
  568. c = classes[cn]
  569. make_rst_class(c)