makerst.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. import xml.etree.ElementTree as ET
  5. input_list = []
  6. for arg in sys.argv[1:]:
  7. input_list.append(arg)
  8. if len(input_list) < 1:
  9. print 'usage: makerst.py <classes.xml>'
  10. sys.exit(0)
  11. def validate_tag(elem, tag):
  12. if elem.tag != tag:
  13. print "Tag mismatch, expected '" + tag + "', got " + elem.tag
  14. sys.exit(255)
  15. class_names = []
  16. classes = {}
  17. def ul_string(str,ul):
  18. str+="\n"
  19. for i in range(len(str)-1):
  20. str+=ul
  21. str+="\n"
  22. return str
  23. def make_class_list(class_list, columns):
  24. f = open('class_list.rst', 'wb')
  25. prev = 0
  26. col_max = len(class_list) / columns + 1
  27. print ('col max is ', col_max)
  28. col_count = 0
  29. row_count = 0
  30. last_initial = ''
  31. fit_columns = []
  32. for n in range(0, columns):
  33. fit_columns += [[]]
  34. indexers = []
  35. last_initial = ''
  36. idx = 0
  37. for n in class_list:
  38. col = idx / col_max
  39. if col >= columns:
  40. col = columns - 1
  41. fit_columns[col] += [n]
  42. idx += 1
  43. if n[:1] != last_initial:
  44. indexers += [n]
  45. last_initial = n[:1]
  46. row_max = 0
  47. f.write("\n")
  48. for n in range(0, columns):
  49. if len(fit_columns[n]) > row_max:
  50. row_max = len(fit_columns[n])
  51. f.write("| ")
  52. for n in range(0, columns):
  53. f.write(" | |")
  54. f.write("\n")
  55. f.write("+")
  56. for n in range(0, columns):
  57. f.write("--+-------+")
  58. f.write("\n")
  59. for r in range(0, row_max):
  60. s = '+ '
  61. for c in range(0, columns):
  62. if r >= len(fit_columns[c]):
  63. continue
  64. classname = fit_columns[c][r]
  65. initial = classname[0]
  66. if classname in indexers:
  67. s += '**' + initial + '** | '
  68. else:
  69. s += ' | '
  70. s += '[' + classname + '](class_'+ classname.lower()+') | '
  71. s += '\n'
  72. f.write(s)
  73. for n in range(0, columns):
  74. f.write("--+-------+")
  75. f.write("\n")
  76. def rstize_text(text,cclass):
  77. # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock"
  78. pos = 0
  79. while True:
  80. pos = text.find('\n', pos)
  81. if pos == -1:
  82. break
  83. pre_text = text[:pos]
  84. while text[pos+1] == '\t':
  85. pos += 1
  86. post_text = text[pos+1:]
  87. # Handle codeblocks
  88. if post_text.startswith("[codeblock]"):
  89. end_pos = post_text.find("[/codeblock]")
  90. if end_pos == -1:
  91. sys.exit("ERROR! [codeblock] without a closing tag!")
  92. code_text = post_text[len("[codeblock]"):end_pos]
  93. post_text = post_text[end_pos:]
  94. # Remove extraneous tabs
  95. code_pos = 0
  96. while True:
  97. code_pos = code_text.find('\n', code_pos)
  98. if code_pos == -1:
  99. break
  100. to_skip = 0
  101. while code_pos+to_skip+1 < len(code_text) and code_text[code_pos+to_skip+1] == '\t':
  102. to_skip += 1
  103. if len(code_text[code_pos+to_skip+1:])==0:
  104. code_text = code_text[:code_pos] + "\n"
  105. code_pos += 1
  106. else:
  107. code_text = code_text[:code_pos] + "\n " + code_text[code_pos+to_skip+1:]
  108. code_pos += 5 - to_skip
  109. text = pre_text + "\n[codeblock]" + code_text + post_text
  110. pos += len("\n[codeblock]" + code_text)
  111. # Handle normal text
  112. else:
  113. text = pre_text + "\n\n" + post_text
  114. pos += 2
  115. # Escape * character to avoid interpreting it as emphasis
  116. pos = 0
  117. while True:
  118. pos = text.find('*', pos)
  119. if pos == -1:
  120. break
  121. text = text[:pos] + "\*" + text[pos + 1:]
  122. pos += 2
  123. # Escape _ character at the end of a word to avoid interpreting it as an inline hyperlink
  124. pos = 0
  125. while True:
  126. pos = text.find('_', pos)
  127. if pos == -1:
  128. break
  129. if not text[pos + 1].isalnum(): # don't escape within a snake_case word
  130. text = text[:pos] + "\_" + text[pos + 1:]
  131. pos += 2
  132. else:
  133. pos += 1
  134. # Handle [tags]
  135. pos = 0
  136. while True:
  137. pos = text.find('[', pos)
  138. if pos == -1:
  139. break
  140. endq_pos = text.find(']', pos + 1)
  141. if endq_pos == -1:
  142. break
  143. pre_text = text[:pos]
  144. post_text = text[endq_pos + 1:]
  145. tag_text = text[pos + 1:endq_pos]
  146. if tag_text in class_names:
  147. tag_text = make_type(tag_text)
  148. else: # command
  149. cmd = tag_text
  150. space_pos = tag_text.find(' ')
  151. if cmd.find('html') == 0:
  152. cmd = tag_text[:space_pos]
  153. param = tag_text[space_pos + 1:]
  154. tag_text = param
  155. elif cmd.find('method') == 0:
  156. cmd = tag_text[:space_pos]
  157. param = tag_text[space_pos + 1:]
  158. if param.find('.') != -1:
  159. (class_param, method_param) = param.split('.')
  160. tag_text = ':ref:`'+class_param+'.'+method_param+'<class_' + class_param + '_' + method_param + '>`'
  161. else:
  162. tag_text = ':ref:`' + param + '<class_' + cclass +"_"+ param + '>`'
  163. elif cmd.find('image=') == 0:
  164. tag_text = "" #'![](' + cmd[6:] + ')'
  165. elif cmd.find('url=') == 0:
  166. tag_text = ':ref:`' + cmd[4:] + '<'+cmd[4:]+">`"
  167. elif cmd == '/url':
  168. tag_text = ')'
  169. elif cmd == 'center':
  170. tag_text = ''
  171. elif cmd == '/center':
  172. tag_text = ''
  173. elif cmd == 'codeblock':
  174. tag_text = '\n::\n'
  175. elif cmd == '/codeblock':
  176. tag_text = ''
  177. # Strip newline if the tag was alone on one
  178. if pre_text[-1] == '\n':
  179. pre_text = pre_text[:-1]
  180. elif cmd == 'br':
  181. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  182. tag_text = '\n\n'
  183. # Strip potential leading spaces
  184. while post_text[0] == ' ':
  185. post_text = post_text[1:]
  186. elif cmd == 'i' or cmd == '/i':
  187. tag_text = '*'
  188. elif cmd == 'b' or cmd == '/b':
  189. tag_text = '**'
  190. elif cmd == 'u' or cmd == '/u':
  191. tag_text = ''
  192. elif cmd == 'code' or cmd == '/code':
  193. tag_text = '``'
  194. else:
  195. tag_text = ':ref:`' + tag_text + '<class_'+tag_text.lower()+'>`'
  196. text = pre_text + tag_text + post_text
  197. pos = len(pre_text) + len(tag_text)
  198. # tnode = ET.SubElement(parent,"div")
  199. # tnode.text=text
  200. return text
  201. def make_type(t):
  202. global class_names
  203. if t in class_names:
  204. return ':ref:`'+t+'<class_' + t.lower()+'>`'
  205. return t
  206. def make_method(
  207. f,
  208. name,
  209. m,
  210. declare,
  211. cname,
  212. event=False,
  213. pp=None
  214. ):
  215. if (declare or pp==None):
  216. t = '- '
  217. else:
  218. t = ""
  219. ret_type = 'void'
  220. args = list(m)
  221. mdata = {}
  222. mdata['argidx'] = []
  223. for a in args:
  224. if a.tag == 'return':
  225. idx = -1
  226. elif a.tag == 'argument':
  227. idx = int(a.attrib['index'])
  228. else:
  229. continue
  230. mdata['argidx'].append(idx)
  231. mdata[idx] = a
  232. if not event:
  233. if -1 in mdata['argidx']:
  234. t += make_type(mdata[-1].attrib['type'])
  235. else:
  236. t += 'void'
  237. t += ' '
  238. if declare or pp==None:
  239. # span.attrib["class"]="funcdecl"
  240. # a=ET.SubElement(span,"a")
  241. # a.attrib["name"]=name+"_"+m.attrib["name"]
  242. # a.text=name+"::"+m.attrib["name"]
  243. s = ' **'+m.attrib['name']+'** '
  244. else:
  245. s = ':ref:`'+ m.attrib['name']+'<class_' + cname+"_"+m.attrib['name'] + '>` '
  246. s += ' **(**'
  247. argfound = False
  248. for a in mdata['argidx']:
  249. arg = mdata[a]
  250. if a < 0:
  251. continue
  252. if a > 0:
  253. s += ', '
  254. else:
  255. s += ' '
  256. s += make_type(arg.attrib['type'])
  257. if 'name' in arg.attrib:
  258. s += ' ' + arg.attrib['name']
  259. else:
  260. s += ' arg' + str(a)
  261. if 'default' in arg.attrib:
  262. s += '=' + arg.attrib['default']
  263. argfound = True
  264. if argfound:
  265. s += ' '
  266. s += ' **)**'
  267. if 'qualifiers' in m.attrib:
  268. s += ' ' + m.attrib['qualifiers']
  269. # f.write(s)
  270. if (not declare):
  271. if (pp!=None):
  272. pp.append( (t,s) )
  273. else:
  274. f.write("- "+t+" "+s+"\n")
  275. else:
  276. f.write(t+s+"\n")
  277. def make_heading(title, underline):
  278. return title + '\n' + underline*len(title) + "\n\n"
  279. def make_rst_class(node):
  280. name = node.attrib['name']
  281. f = open("class_"+name.lower() + '.rst', 'wb')
  282. # Warn contributors not to edit this file directly
  283. f.write(".. Generated automatically by doc/tools/makerst.py in Godot's source tree.\n")
  284. f.write(".. DO NOT EDIT THIS FILE, but the doc/base/classes.xml source instead.\n\n")
  285. f.write(".. _class_"+name+":\n\n")
  286. f.write(make_heading(name, '='))
  287. if 'inherits' in node.attrib:
  288. inh = node.attrib['inherits'].strip()
  289. # whle inh in classes[cn]
  290. f.write('**Inherits:** ')
  291. first=True
  292. while(inh in classes):
  293. if (not first):
  294. f.write(" **<** ")
  295. else:
  296. first=False
  297. f.write(make_type(inh))
  298. inode = classes[inh]
  299. if ('inherits' in inode.attrib):
  300. inh=inode.attrib['inherits'].strip()
  301. else:
  302. inh=None
  303. f.write("\n\n")
  304. inherited=[]
  305. for cn in classes:
  306. c=classes[cn]
  307. if 'inherits' in c.attrib:
  308. if (c.attrib['inherits'].strip()==name):
  309. inherited.append(c.attrib['name'])
  310. if (len(inherited)):
  311. f.write('**Inherited By:** ')
  312. for i in range(len(inherited)):
  313. if (i>0):
  314. f.write(", ")
  315. f.write(make_type(inherited[i]))
  316. f.write("\n\n")
  317. if 'category' in node.attrib:
  318. f.write('**Category:** ' + node.attrib['category'].strip() + "\n\n")
  319. f.write(make_heading('Brief Description', '-'))
  320. briefd = node.find('brief_description')
  321. if briefd != None:
  322. f.write(rstize_text(briefd.text.strip(),name) + "\n\n")
  323. methods = node.find('methods')
  324. if methods != None and len(list(methods)) > 0:
  325. f.write(make_heading('Member Functions', '-'))
  326. ml=[]
  327. for m in list(methods):
  328. make_method(f, node.attrib['name'], m, False,name,False,ml)
  329. longest_t = 0
  330. longest_s = 0
  331. for s in ml:
  332. sl = len(s[0])
  333. if (sl>longest_s):
  334. longest_s=sl
  335. tl = len(s[1])
  336. if (tl>longest_t):
  337. longest_t=tl
  338. sep="+"
  339. for i in range(longest_s+2):
  340. sep+="-"
  341. sep+="+"
  342. for i in range(longest_t+2):
  343. sep+="-"
  344. sep+="+\n"
  345. f.write(sep)
  346. for s in ml:
  347. rt = s[0]
  348. while( len(rt) < longest_s ):
  349. rt+=" "
  350. st = s[1]
  351. while( len(st) < longest_t ):
  352. st+=" "
  353. f.write("| "+rt+" | "+st+" |\n")
  354. f.write(sep)
  355. f.write('\n')
  356. events = node.find('signals')
  357. if events != None and len(list(events)) > 0:
  358. f.write(make_heading('Signals', '-'))
  359. for m in list(events):
  360. make_method(f, node.attrib['name'], m, True,name, True)
  361. f.write('\n')
  362. members = node.find('members')
  363. if members != None and len(list(members)) > 0:
  364. f.write(make_heading('Member Variables', '-'))
  365. for c in list(members):
  366. s = '- '
  367. s += make_type(c.attrib['type']) + ' '
  368. s += '**' + c.attrib['name'] + '**'
  369. if c.text.strip() != '':
  370. s += ' - ' + c.text.strip()
  371. f.write(s + '\n')
  372. f.write('\n')
  373. constants = node.find('constants')
  374. if constants != None and len(list(constants)) > 0:
  375. f.write(make_heading('Numeric Constants', '-'))
  376. for c in list(constants):
  377. s = '- '
  378. s += '**' + c.attrib['name'] + '**'
  379. if 'value' in c.attrib:
  380. s += ' = **' + c.attrib['value'] + '**'
  381. if c.text.strip() != '':
  382. s += ' --- ' + rstize_text(c.text.strip(),name)
  383. f.write(s + '\n')
  384. f.write('\n')
  385. descr = node.find('description')
  386. if descr != None and descr.text.strip() != '':
  387. f.write(make_heading('Description', '-'))
  388. f.write(rstize_text(descr.text.strip(),name) + "\n\n")
  389. methods = node.find('methods')
  390. if methods != None and len(list(methods)) > 0:
  391. f.write(make_heading('Member Function Description', '-'))
  392. for m in list(methods):
  393. f.write(".. _class_"+name+"_"+m.attrib['name']+":\n\n")
  394. # f.write(ul_string(m.attrib['name'],"^"))
  395. #f.write('\n<a name="'+m.attrib['name']+'">' + m.attrib['name'] + '</a>\n------\n')
  396. make_method(f, node.attrib['name'], m, True,name)
  397. f.write('\n')
  398. d = m.find('description')
  399. if d == None or d.text.strip() == '':
  400. continue
  401. f.write(rstize_text(d.text.strip(),name))
  402. f.write("\n\n")
  403. f.write('\n')
  404. for file in input_list:
  405. tree = ET.parse(file)
  406. doc = tree.getroot()
  407. if 'version' not in doc.attrib:
  408. print "Version missing from 'doc'"
  409. sys.exit(255)
  410. version = doc.attrib['version']
  411. for c in list(doc):
  412. if c.attrib['name'] in class_names:
  413. continue
  414. class_names.append(c.attrib['name'])
  415. classes[c.attrib['name']] = c
  416. class_names.sort()
  417. #Don't make class list for Sphinx, :toctree: handles it
  418. #make_class_list(class_names, 2)
  419. for cn in class_names:
  420. c = classes[cn]
  421. make_rst_class(c)