doc_status.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import re
  5. import math
  6. import platform
  7. import xml.etree.ElementTree as ET
  8. ################################################################################
  9. # Config #
  10. ################################################################################
  11. flags = {
  12. 'c': platform.platform() != 'Windows', # Disable by default on windows, since we use ANSI escape codes
  13. 'b': False,
  14. 'g': False,
  15. 's': False,
  16. 'u': False,
  17. 'h': False,
  18. 'p': False,
  19. 'o': True,
  20. 'i': False,
  21. 'a': True,
  22. }
  23. flag_descriptions = {
  24. 'c': 'Toggle colors when outputting.',
  25. 'b': 'Toggle showing only not fully described classes.',
  26. 'g': 'Toggle showing only completed classes.',
  27. 's': 'Toggle showing comments about the status.',
  28. 'u': 'Toggle URLs to docs.',
  29. 'h': 'Show help and exit.',
  30. 'p': 'Toggle showing percentage as well as counts.',
  31. 'o': 'Toggle overall column.',
  32. 'i': 'Toggle collapse of class items columns.',
  33. 'a': 'Toggle showing all items.',
  34. }
  35. long_flags = {
  36. 'colors': 'c',
  37. 'use-colors': 'c',
  38. 'bad': 'b',
  39. 'only-bad': 'b',
  40. 'good': 'g',
  41. 'only-good': 'g',
  42. 'comments': 's',
  43. 'status': 's',
  44. 'urls': 'u',
  45. 'gen-url': 'u',
  46. 'help': 'h',
  47. 'percent': 'p',
  48. 'use-percentages': 'p',
  49. 'overall': 'o',
  50. 'use-overall': 'o',
  51. 'items': 'i',
  52. 'collapse': 'i',
  53. 'all': 'a',
  54. }
  55. table_columns = ['name', 'brief_description', 'description', 'methods', 'constants', 'members', 'signals']
  56. table_column_names = ['Name', 'Brief Desc.', 'Desc.', 'Methods', 'Constants', 'Members', 'Signals']
  57. colors = {
  58. 'name': [36], # cyan
  59. 'part_big_problem': [4, 31], # underline, red
  60. 'part_problem': [31], # red
  61. 'part_mostly_good': [33], # yellow
  62. 'part_good': [32], # green
  63. 'url': [4, 34], # underline, blue
  64. 'section': [1, 4], # bold, underline
  65. 'state_off': [36], # cyan
  66. 'state_on': [1, 35], # bold, magenta/plum
  67. }
  68. overall_progress_description_weigth = 10
  69. ################################################################################
  70. # Utils #
  71. ################################################################################
  72. def validate_tag(elem, tag):
  73. if elem.tag != tag:
  74. print('Tag mismatch, expected "' + tag + '", got ' + elem.tag)
  75. sys.exit(255)
  76. def color(color, string):
  77. if flags['c']:
  78. color_format = ''
  79. for code in colors[color]:
  80. color_format += '\033[' + str(code) + 'm'
  81. return color_format + string + '\033[0m'
  82. else:
  83. return string
  84. ansi_escape = re.compile(r'\x1b[^m]*m')
  85. def nonescape_len(s):
  86. return len(ansi_escape.sub('', s))
  87. ################################################################################
  88. # Classes #
  89. ################################################################################
  90. class ClassStatusProgress:
  91. def __init__(self, described=0, total=0):
  92. self.described = described
  93. self.total = total
  94. def __add__(self, other):
  95. return ClassStatusProgress(self.described + other.described, self.total + other.total)
  96. def increment(self, described):
  97. if described:
  98. self.described += 1
  99. self.total += 1
  100. def is_ok(self):
  101. return self.described >= self.total
  102. def to_configured_colored_string(self):
  103. if flags['p']:
  104. return self.to_colored_string('{percent}% ({has}/{total})', '{pad_percent}{pad_described}{s}{pad_total}')
  105. else:
  106. return self.to_colored_string()
  107. def to_colored_string(self, format='{has}/{total}', pad_format='{pad_described}{s}{pad_total}'):
  108. ratio = self.described / self.total if self.total != 0 else 1
  109. percent = round(100 * ratio)
  110. s = format.format(has=str(self.described), total=str(self.total), percent=str(percent))
  111. if self.described >= self.total:
  112. s = color('part_good', s)
  113. elif self.described >= self.total / 4 * 3:
  114. s = color('part_mostly_good', s)
  115. elif self.described > 0:
  116. s = color('part_problem', s)
  117. else:
  118. s = color('part_big_problem', s)
  119. pad_size = max(len(str(self.described)), len(str(self.total)))
  120. pad_described = ''.ljust(pad_size - len(str(self.described)))
  121. pad_percent = ''.ljust(3 - len(str(percent)))
  122. pad_total = ''.ljust(pad_size - len(str(self.total)))
  123. return pad_format.format(pad_described=pad_described, pad_total=pad_total, pad_percent=pad_percent, s=s)
  124. class ClassStatus:
  125. def __init__(self, name=''):
  126. self.name = name
  127. self.has_brief_description = True
  128. self.has_description = True
  129. self.progresses = {
  130. 'methods': ClassStatusProgress(),
  131. 'constants': ClassStatusProgress(),
  132. 'members': ClassStatusProgress(),
  133. 'signals': ClassStatusProgress()
  134. }
  135. def __add__(self, other):
  136. new_status = ClassStatus()
  137. new_status.name = self.name
  138. new_status.has_brief_description = self.has_brief_description and other.has_brief_description
  139. new_status.has_description = self.has_description and other.has_description
  140. for k in self.progresses:
  141. new_status.progresses[k] = self.progresses[k] + other.progresses[k]
  142. return new_status
  143. def is_ok(self):
  144. ok = True
  145. ok = ok and self.has_brief_description
  146. ok = ok and self.has_description
  147. for k in self.progresses:
  148. ok = ok and self.progresses[k].is_ok()
  149. return ok
  150. def make_output(self):
  151. output = {}
  152. output['name'] = color('name', self.name)
  153. ok_string = color('part_good', 'OK')
  154. missing_string = color('part_big_problem', 'MISSING')
  155. output['brief_description'] = ok_string if self.has_brief_description else missing_string
  156. output['description'] = ok_string if self.has_description else missing_string
  157. description_progress = ClassStatusProgress(
  158. (self.has_brief_description + self.has_description) * overall_progress_description_weigth,
  159. 2 * overall_progress_description_weigth
  160. )
  161. items_progress = ClassStatusProgress()
  162. for k in ['methods', 'constants', 'members', 'signals']:
  163. items_progress += self.progresses[k]
  164. output[k] = self.progresses[k].to_configured_colored_string()
  165. output['items'] = items_progress.to_configured_colored_string()
  166. output['overall'] = (description_progress + items_progress).to_colored_string('{percent}%', '{pad_percent}{s}')
  167. if self.name.startswith('Total'):
  168. output['url'] = color('url', 'http://docs.godotengine.org/en/latest/classes/')
  169. if flags['s']:
  170. output['comment'] = color('part_good', 'ALL OK')
  171. else:
  172. output['url'] = color('url', 'http://docs.godotengine.org/en/latest/classes/class_{name}.html'.format(name=self.name.lower()))
  173. if flags['s'] and not flags['g'] and self.is_ok():
  174. output['comment'] = color('part_good', 'ALL OK')
  175. return output
  176. def generate_for_class(c):
  177. status = ClassStatus()
  178. status.name = c.attrib['name']
  179. # setgets do not count
  180. methods = []
  181. for tag in list(c):
  182. if tag.tag in ['methods']:
  183. for sub_tag in list(tag):
  184. methods.append(sub_tag.find('name'))
  185. if tag.tag in ['members']:
  186. for sub_tag in list(tag):
  187. try:
  188. methods.remove(sub_tag.find('setter'))
  189. methods.remove(sub_tag.find('getter'))
  190. except:
  191. pass
  192. for tag in list(c):
  193. if tag.tag == 'brief_description':
  194. status.has_brief_description = len(tag.text.strip()) > 0
  195. elif tag.tag == 'description':
  196. status.has_description = len(tag.text.strip()) > 0
  197. elif tag.tag in ['methods', 'signals']:
  198. for sub_tag in list(tag):
  199. if sub_tag.find('name') in methods or tag.tag == 'signals':
  200. descr = sub_tag.find('description')
  201. status.progresses[tag.tag].increment(len(descr.text.strip()) > 0)
  202. elif tag.tag in ['constants', 'members']:
  203. for sub_tag in list(tag):
  204. status.progresses[tag.tag].increment(len(sub_tag.text.strip()) > 0)
  205. elif tag.tag in ['theme_items']:
  206. pass # Ignore those tags, since they seem to lack description at all
  207. else:
  208. print(tag.tag, tag.attrib)
  209. return status
  210. ################################################################################
  211. # Arguments #
  212. ################################################################################
  213. input_file_list = []
  214. input_class_list = []
  215. merged_file = ""
  216. for arg in sys.argv[1:]:
  217. if arg.startswith('--'):
  218. flags[long_flags[arg[2:]]] = not flags[long_flags[arg[2:]]]
  219. elif arg.startswith('-'):
  220. for f in arg[1:]:
  221. flags[f] = not flags[f]
  222. elif os.path.isdir(arg):
  223. for f in os.listdir(arg):
  224. if f.endswith('.xml'):
  225. input_file_list.append(os.path.join(arg, f));
  226. else:
  227. input_class_list.append(arg)
  228. if flags['i']:
  229. for r in ['methods', 'constants', 'members', 'signals']:
  230. index = table_columns.index(r)
  231. del table_column_names[index]
  232. del table_columns[index]
  233. table_column_names.append('Items')
  234. table_columns.append('items')
  235. if flags['o'] == (not flags['i']):
  236. table_column_names.append('Overall')
  237. table_columns.append('overall')
  238. if flags['u']:
  239. table_column_names.append('Docs URL')
  240. table_columns.append('url')
  241. ################################################################################
  242. # Help #
  243. ################################################################################
  244. if len(input_file_list) < 1 or flags['h']:
  245. if not flags['h']:
  246. print(color('section', 'Invalid usage') + ': Please specify a classes directory')
  247. print(color('section', 'Usage') + ': doc_status.py [flags] <classes_dir> [class names]')
  248. print('\t< and > signify required parameters, while [ and ] signify optional parameters.')
  249. print(color('section', 'Available flags') + ':')
  250. possible_synonym_list = list(long_flags)
  251. possible_synonym_list.sort()
  252. flag_list = list(flags)
  253. flag_list.sort()
  254. for flag in flag_list:
  255. synonyms = [color('name', '-' + flag)]
  256. for synonym in possible_synonym_list:
  257. if long_flags[synonym] == flag:
  258. synonyms.append(color('name', '--' + synonym))
  259. print(('{synonyms} (Currently ' + color('state_' + ('on' if flags[flag] else 'off'), '{value}') + ')\n\t{description}').format(
  260. synonyms=', '.join(synonyms),
  261. value=('on' if flags[flag] else 'off'),
  262. description=flag_descriptions[flag]
  263. ))
  264. sys.exit(0)
  265. ################################################################################
  266. # Parse class list #
  267. ################################################################################
  268. class_names = []
  269. classes = {}
  270. for file in input_file_list:
  271. tree = ET.parse(file)
  272. doc = tree.getroot()
  273. if 'version' not in doc.attrib:
  274. print('Version missing from "doc"')
  275. sys.exit(255)
  276. version = doc.attrib['version']
  277. if doc.attrib['name'] in class_names:
  278. continue
  279. class_names.append(doc.attrib['name'])
  280. classes[doc.attrib['name']] = doc
  281. class_names.sort()
  282. if len(input_class_list) < 1:
  283. input_class_list = class_names
  284. ################################################################################
  285. # Make output table #
  286. ################################################################################
  287. table = [table_column_names]
  288. table_row_chars = '+- '
  289. table_column_chars = '|'
  290. total_status = ClassStatus('Total')
  291. for cn in input_class_list:
  292. if not cn in classes:
  293. print('Cannot find class ' + cn + '!')
  294. sys.exit(255)
  295. c = classes[cn]
  296. validate_tag(c, 'class')
  297. status = ClassStatus.generate_for_class(c)
  298. total_status = total_status + status
  299. if (flags['b'] and status.is_ok()) or (flags['g'] and not status.is_ok()) or (not flags['a']):
  300. continue
  301. out = status.make_output()
  302. row = []
  303. for column in table_columns:
  304. if column in out:
  305. row.append(out[column])
  306. else:
  307. row.append('')
  308. if 'comment' in out and out['comment'] != '':
  309. row.append(out['comment'])
  310. table.append(row)
  311. ################################################################################
  312. # Print output table #
  313. ################################################################################
  314. if len(table) == 1 and flags['a']:
  315. print(color('part_big_problem', 'No classes suitable for printing!'))
  316. sys.exit(0)
  317. if len(table) > 2 or not flags['a']:
  318. total_status.name = 'Total = {0}'.format(len(table) - 1)
  319. out = total_status.make_output()
  320. row = []
  321. for column in table_columns:
  322. if column in out:
  323. row.append(out[column])
  324. else:
  325. row.append('')
  326. table.append(row)
  327. table_column_sizes = []
  328. for row in table:
  329. for cell_i, cell in enumerate(row):
  330. if cell_i >= len(table_column_sizes):
  331. table_column_sizes.append(0)
  332. table_column_sizes[cell_i] = max(nonescape_len(cell), table_column_sizes[cell_i])
  333. divider_string = table_row_chars[0]
  334. for cell_i in range(len(table[0])):
  335. divider_string += table_row_chars[1] * (table_column_sizes[cell_i] + 2) + table_row_chars[0]
  336. print(divider_string)
  337. for row_i, row in enumerate(table):
  338. row_string = table_column_chars
  339. for cell_i, cell in enumerate(row):
  340. padding_needed = table_column_sizes[cell_i] - nonescape_len(cell) + 2
  341. if cell_i == 0:
  342. row_string += table_row_chars[2] + cell + table_row_chars[2] * (padding_needed - 1)
  343. else:
  344. row_string += table_row_chars[2] * math.floor(padding_needed / 2) + cell + table_row_chars[2] * math.ceil((padding_needed / 2))
  345. row_string += table_column_chars
  346. print(row_string)
  347. if row_i == 0 or row_i == len(table) - 2:
  348. print(divider_string)
  349. print(divider_string)
  350. if total_status.is_ok() and not flags['g']:
  351. print('All listed classes are ' + color('part_good', 'OK') + '!')