doc_status.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. #!/usr/bin/env python
  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. 'e': False,
  24. }
  25. flag_descriptions = {
  26. 'c': 'Toggle colors when outputting.',
  27. 'b': 'Toggle showing only not fully described classes.',
  28. 'g': 'Toggle showing only completed classes.',
  29. 's': 'Toggle showing comments about the status.',
  30. 'u': 'Toggle URLs to docs.',
  31. 'h': 'Show help and exit.',
  32. 'p': 'Toggle showing percentage as well as counts.',
  33. 'o': 'Toggle overall column.',
  34. 'i': 'Toggle collapse of class items columns.',
  35. 'a': 'Toggle showing all items.',
  36. 'e': 'Toggle hiding empty items.',
  37. }
  38. long_flags = {
  39. 'colors': 'c',
  40. 'use-colors': 'c',
  41. 'bad': 'b',
  42. 'only-bad': 'b',
  43. 'good': 'g',
  44. 'only-good': 'g',
  45. 'comments': 's',
  46. 'status': 's',
  47. 'urls': 'u',
  48. 'gen-url': 'u',
  49. 'help': 'h',
  50. 'percent': 'p',
  51. 'use-percentages': 'p',
  52. 'overall': 'o',
  53. 'use-overall': 'o',
  54. 'items': 'i',
  55. 'collapse': 'i',
  56. 'all': 'a',
  57. 'empty': 'e',
  58. }
  59. table_columns = ['name', 'brief_description', 'description', 'methods', 'constants', 'members', 'signals']
  60. table_column_names = ['Name', 'Brief Desc.', 'Desc.', 'Methods', 'Constants', 'Members', 'Signals']
  61. colors = {
  62. 'name': [36], # cyan
  63. 'part_big_problem': [4, 31], # underline, red
  64. 'part_problem': [31], # red
  65. 'part_mostly_good': [33], # yellow
  66. 'part_good': [32], # green
  67. 'url': [4, 34], # underline, blue
  68. 'section': [1, 4], # bold, underline
  69. 'state_off': [36], # cyan
  70. 'state_on': [1, 35], # bold, magenta/plum
  71. }
  72. overall_progress_description_weigth = 10
  73. ################################################################################
  74. # Utils #
  75. ################################################################################
  76. def validate_tag(elem, tag):
  77. if elem.tag != tag:
  78. print('Tag mismatch, expected "' + tag + '", got ' + elem.tag)
  79. sys.exit(255)
  80. def color(color, string):
  81. if flags['c'] and terminal_supports_color():
  82. color_format = ''
  83. for code in colors[color]:
  84. color_format += '\033[' + str(code) + 'm'
  85. return color_format + string + '\033[0m'
  86. else:
  87. return string
  88. ansi_escape = re.compile(r'\x1b[^m]*m')
  89. def nonescape_len(s):
  90. return len(ansi_escape.sub('', s))
  91. def terminal_supports_color():
  92. p = sys.platform
  93. supported_platform = p != 'Pocket PC' and (p != 'win32' or
  94. 'ANSICON' in os.environ)
  95. is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
  96. if not supported_platform or not is_a_tty:
  97. return False
  98. return True
  99. ################################################################################
  100. # Classes #
  101. ################################################################################
  102. class ClassStatusProgress:
  103. def __init__(self, described=0, total=0):
  104. self.described = described
  105. self.total = total
  106. def __add__(self, other):
  107. return ClassStatusProgress(self.described + other.described, self.total + other.total)
  108. def increment(self, described):
  109. if described:
  110. self.described += 1
  111. self.total += 1
  112. def is_ok(self):
  113. return self.described >= self.total
  114. def to_configured_colored_string(self):
  115. if flags['p']:
  116. return self.to_colored_string('{percent}% ({has}/{total})', '{pad_percent}{pad_described}{s}{pad_total}')
  117. else:
  118. return self.to_colored_string()
  119. def to_colored_string(self, format='{has}/{total}', pad_format='{pad_described}{s}{pad_total}'):
  120. ratio = float(self.described) / float(self.total) if self.total != 0 else 1
  121. percent = int(round(100 * ratio))
  122. s = format.format(has=str(self.described), total=str(self.total), percent=str(percent))
  123. if self.described >= self.total:
  124. s = color('part_good', s)
  125. elif self.described >= self.total / 4 * 3:
  126. s = color('part_mostly_good', s)
  127. elif self.described > 0:
  128. s = color('part_problem', s)
  129. else:
  130. s = color('part_big_problem', s)
  131. pad_size = max(len(str(self.described)), len(str(self.total)))
  132. pad_described = ''.ljust(pad_size - len(str(self.described)))
  133. pad_percent = ''.ljust(3 - len(str(percent)))
  134. pad_total = ''.ljust(pad_size - len(str(self.total)))
  135. return pad_format.format(pad_described=pad_described, pad_total=pad_total, pad_percent=pad_percent, s=s)
  136. class ClassStatus:
  137. def __init__(self, name=''):
  138. self.name = name
  139. self.has_brief_description = True
  140. self.has_description = True
  141. self.progresses = {
  142. 'methods': ClassStatusProgress(),
  143. 'constants': ClassStatusProgress(),
  144. 'members': ClassStatusProgress(),
  145. 'signals': ClassStatusProgress()
  146. }
  147. def __add__(self, other):
  148. new_status = ClassStatus()
  149. new_status.name = self.name
  150. new_status.has_brief_description = self.has_brief_description and other.has_brief_description
  151. new_status.has_description = self.has_description and other.has_description
  152. for k in self.progresses:
  153. new_status.progresses[k] = self.progresses[k] + other.progresses[k]
  154. return new_status
  155. def is_ok(self):
  156. ok = True
  157. ok = ok and self.has_brief_description
  158. ok = ok and self.has_description
  159. for k in self.progresses:
  160. ok = ok and self.progresses[k].is_ok()
  161. return ok
  162. def is_empty(self):
  163. sum = 0
  164. for k in self.progresses:
  165. if self.progresses[k].is_ok():
  166. continue
  167. sum += self.progresses[k].total
  168. return sum < 1
  169. def make_output(self):
  170. output = {}
  171. output['name'] = color('name', self.name)
  172. ok_string = color('part_good', 'OK')
  173. missing_string = color('part_big_problem', 'MISSING')
  174. output['brief_description'] = ok_string if self.has_brief_description else missing_string
  175. output['description'] = ok_string if self.has_description else missing_string
  176. description_progress = ClassStatusProgress(
  177. (self.has_brief_description + self.has_description) * overall_progress_description_weigth,
  178. 2 * overall_progress_description_weigth
  179. )
  180. items_progress = ClassStatusProgress()
  181. for k in ['methods', 'constants', 'members', 'signals']:
  182. items_progress += self.progresses[k]
  183. output[k] = self.progresses[k].to_configured_colored_string()
  184. output['items'] = items_progress.to_configured_colored_string()
  185. output['overall'] = (description_progress + items_progress).to_colored_string('{percent}%', '{pad_percent}{s}')
  186. if self.name.startswith('Total'):
  187. output['url'] = color('url', 'https://docs.godotengine.org/en/latest/classes/')
  188. if flags['s']:
  189. output['comment'] = color('part_good', 'ALL OK')
  190. else:
  191. output['url'] = color('url', 'https://docs.godotengine.org/en/latest/classes/class_{name}.html'.format(name=self.name.lower()))
  192. if flags['s'] and not flags['g'] and self.is_ok():
  193. output['comment'] = color('part_good', 'ALL OK')
  194. return output
  195. @staticmethod
  196. def generate_for_class(c):
  197. status = ClassStatus()
  198. status.name = c.attrib['name']
  199. for tag in list(c):
  200. if tag.tag == 'brief_description':
  201. status.has_brief_description = len(tag.text.strip()) > 0
  202. elif tag.tag == 'description':
  203. status.has_description = len(tag.text.strip()) > 0
  204. elif tag.tag in ['methods', 'signals']:
  205. for sub_tag in list(tag):
  206. descr = sub_tag.find('description')
  207. status.progresses[tag.tag].increment(len(descr.text.strip()) > 0)
  208. elif tag.tag in ['constants', 'members']:
  209. for sub_tag in list(tag):
  210. status.progresses[tag.tag].increment(len(sub_tag.text.strip()) > 0)
  211. elif tag.tag in ['tutorials', 'demos']:
  212. pass # Ignore those tags for now
  213. elif tag.tag in ['theme_items']:
  214. pass # Ignore those tags, since they seem to lack description at all
  215. else:
  216. print(tag.tag, tag.attrib)
  217. return status
  218. ################################################################################
  219. # Arguments #
  220. ################################################################################
  221. input_file_list = []
  222. input_class_list = []
  223. merged_file = ""
  224. for arg in sys.argv[1:]:
  225. try:
  226. if arg.startswith('--'):
  227. flags[long_flags[arg[2:]]] = not flags[long_flags[arg[2:]]]
  228. elif arg.startswith('-'):
  229. for f in arg[1:]:
  230. flags[f] = not flags[f]
  231. elif os.path.isdir(arg):
  232. for f in os.listdir(arg):
  233. if f.endswith('.xml'):
  234. input_file_list.append(os.path.join(arg, f));
  235. else:
  236. input_class_list.append(arg)
  237. except KeyError:
  238. print("Unknown command line flag: " + arg)
  239. sys.exit(1)
  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. if flags['e'] and status.is_empty():
  316. continue
  317. out = status.make_output()
  318. row = []
  319. for column in table_columns:
  320. if column in out:
  321. row.append(out[column])
  322. else:
  323. row.append('')
  324. if 'comment' in out and out['comment'] != '':
  325. row.append(out['comment'])
  326. table.append(row)
  327. ################################################################################
  328. # Print output table #
  329. ################################################################################
  330. if len(table) == 1 and flags['a']:
  331. print(color('part_big_problem', 'No classes suitable for printing!'))
  332. sys.exit(0)
  333. if len(table) > 2 or not flags['a']:
  334. total_status.name = 'Total = {0}'.format(len(table) - 1)
  335. out = total_status.make_output()
  336. row = []
  337. for column in table_columns:
  338. if column in out:
  339. row.append(out[column])
  340. else:
  341. row.append('')
  342. table.append(row)
  343. table_column_sizes = []
  344. for row in table:
  345. for cell_i, cell in enumerate(row):
  346. if cell_i >= len(table_column_sizes):
  347. table_column_sizes.append(0)
  348. table_column_sizes[cell_i] = max(nonescape_len(cell), table_column_sizes[cell_i])
  349. divider_string = table_row_chars[0]
  350. for cell_i in range(len(table[0])):
  351. divider_string += table_row_chars[1] + table_row_chars[2] * (table_column_sizes[cell_i]) + table_row_chars[1] + table_row_chars[0]
  352. print(divider_string)
  353. for row_i, row in enumerate(table):
  354. row_string = table_column_chars
  355. for cell_i, cell in enumerate(row):
  356. padding_needed = table_column_sizes[cell_i] - nonescape_len(cell) + 2
  357. if cell_i == 0:
  358. row_string += table_row_chars[3] + cell + table_row_chars[3] * (padding_needed - 1)
  359. else:
  360. 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))
  361. row_string += table_column_chars
  362. print(row_string)
  363. if row_i == 0 or row_i == len(table) - 2:
  364. print(divider_string)
  365. print(divider_string)
  366. if total_status.is_ok() and not flags['g']:
  367. print('All listed classes are ' + color('part_good', 'OK') + '!')