doc_status.py 17 KB

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