1
0

codeblock.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import os
  2. from docutils.parsers.rst import directives
  3. from sphinx.directives.code import CodeBlock
  4. class ExportableCodeBlock(CodeBlock):
  5. option_spec = {
  6. 'summary': directives.unchanged,
  7. 'name': directives.unchanged,
  8. }
  9. def run(self):
  10. code_save_path = os.environ.get('CODE_EXPORT_PATH')
  11. caption = self.options.get('summary', '')
  12. if code_save_path and not os.path.exists(code_save_path):
  13. os.mkdir(code_save_path)
  14. if self.options.get('name', None) is None:
  15. # 设置name属性,从而让生成的代码html块具有id属性
  16. self.options.update({'name': 'demo'})
  17. classes = self.options.get('class', [])
  18. classes.append('demo-cb')
  19. self.options.update({'class': classes})
  20. content_text = '\n'.join(self.content)
  21. content, self.content = self.content, []
  22. for c in content:
  23. if not c.startswith('## ') and c != '##':
  24. self.content.append(c)
  25. nodes = super().run()
  26. try:
  27. elem_id = nodes[0]['ids'][0]
  28. except IndexError:
  29. elem_id = None
  30. if code_save_path and elem_id:
  31. fpath = os.path.join(code_save_path, elem_id)
  32. open(fpath, 'w').write(caption + '\n\n' + content_text)
  33. return nodes
  34. def setup(app):
  35. app.add_directive("exportable-codeblock", ExportableCodeBlock)
  36. app.add_js_file('pywebio.js')
  37. return {
  38. 'version': '0.1',
  39. 'parallel_read_safe': True,
  40. 'parallel_write_safe': True,
  41. }