gen_docs.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import re
  2. from dataclasses import dataclass
  3. NEWLINE = '\n'
  4. @dataclass
  5. class Function:
  6. name: str
  7. args: str
  8. ret: str
  9. comment: str
  10. is_py_raise: bool
  11. is_py_return: bool
  12. def signature(self):
  13. tmp = f"PK_EXPORT {self.ret} {self.name}{self.args}"
  14. return tmp + ';'
  15. def badges(self):
  16. res = []
  17. if self.is_py_raise:
  18. res.append('[!badge text="raise" variant="danger"](../introduction/#py_raise-macro)')
  19. if self.is_py_return:
  20. res.append('[!badge text="return"](../introduction/#py_return-macro)')
  21. return ' '.join(res)
  22. def markdown(self):
  23. lines = [
  24. f"### {self.name}" + f" {self.badges()}",
  25. f"```c",
  26. self.comment,
  27. f"{self.signature()}",
  28. f"```",
  29. ]
  30. return '\n'.join(lines)
  31. with open('include/pocketpy/pocketpy.h') as f:
  32. header = f.read()
  33. matches = re.finditer(r"((?:/// [^\n]+[\n])*?)PK_EXPORT\s+(\w+\*?)\s+(\w+)(\(.*?\))\s*(PY_RAISE)?\s*(PY_RETURN)?\s*;", header, re.DOTALL)
  34. # ^1 comment ^2 ret ^3 n ^4 args ^5 py_raise? ^6 py_return?
  35. functions: list[Function] = []
  36. for match in matches:
  37. functions.append(Function(
  38. name=match[3],
  39. args=match[4],
  40. ret=match[2],
  41. comment=match[1].strip(),
  42. is_py_raise=bool(match[5]),
  43. is_py_return=bool(match[6])
  44. ))
  45. # print(functions[-1])
  46. # generate markdown
  47. with open('docs/C-API/functions.md', 'w', newline='\n') as f:
  48. f.write('\n'.join([
  49. '---',
  50. 'title: Functions',
  51. 'icon: dot',
  52. 'order: 0',
  53. '---',
  54. '\n\n',
  55. ]))
  56. for function in functions:
  57. f.write(function.markdown())
  58. f.write('\n\n')