doc_status.py 15 KB

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