plantuml_rst.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/env python
  2. """Custom reST_ directive for plantuml_ integration.
  3. Adapted from ditaa_rst plugin.
  4. .. _reST: http://docutils.sourceforge.net/rst.html
  5. .. _plantuml: http://plantuml.sourceforge.net/
  6. """
  7. import sys
  8. import os
  9. from docutils.nodes import image, literal_block
  10. from docutils.parsers.rst import Directive, directives
  11. from pelican import signals, logger
  12. from .generateUmlDiagram import generate_uml_image
  13. global_siteurl = "" # URL of the site, filled on plugin initialization
  14. class PlantUML_rst(Directive):
  15. """ reST directive for PlantUML """
  16. required_arguments = 0
  17. optional_arguments = 0
  18. has_content = True
  19. global global_siteurl
  20. option_spec = {
  21. 'class' : directives.class_option,
  22. 'alt' : directives.unchanged,
  23. 'format': directives.unchanged,
  24. }
  25. def run(self):
  26. path = os.path.abspath(os.path.join('output', 'images'))
  27. if not os.path.exists(path):
  28. os.makedirs(path)
  29. nodes = []
  30. body = '\n'.join(self.content)
  31. try:
  32. url = global_siteurl+'/'+generate_uml_image(path, body, "png")
  33. except Exception as exc:
  34. error = self.state_machine.reporter.error(
  35. 'Failed to run plantuml: %s' % exc,
  36. literal_block(self.block_text, self.block_text),
  37. line=self.lineno)
  38. nodes.append(error)
  39. else:
  40. alt = self.options.get('alt', 'uml diagram')
  41. classes = self.options.pop('class', ['uml'])
  42. imgnode = image(uri=url, classes=classes, alt=alt)
  43. nodes.append(imgnode)
  44. return nodes
  45. def pelican_init(pelicanobj):
  46. global global_siteurl
  47. global_siteurl = pelicanobj.settings['SITEURL']
  48. """ Prepare configurations for the MD plugin """
  49. try:
  50. import markdown
  51. from .plantuml_md import PlantUMLMarkdownExtension
  52. except:
  53. # Markdown not available
  54. logger.debug("[plantuml] Markdown support not available")
  55. return
  56. # Register the Markdown plugin
  57. config = { 'siteurl': pelicanobj.settings['SITEURL'] }
  58. try:
  59. if 'MD_EXTENSIONS' in pelicanobj.settings.keys(): # pre pelican 3.7.0
  60. pelicanobj.settings['MD_EXTENSIONS'].append(PlantUMLMarkdownExtension(config))
  61. elif 'MARKDOWN' in pelicanobj.settings.keys() and \
  62. not ('extension_configs' in pelicanobj.settings['MARKDOWN']['extension_configs']): # from pelican 3.7.0
  63. pelicanobj.settings['MARKDOWN']['extension_configs']['plantuml.plantuml_md'] = {}
  64. except:
  65. logger.error("[plantuml] Unable to configure plantuml markdown extension")
  66. def register():
  67. """Plugin registration."""
  68. signals.initialized.connect(pelican_init)
  69. directives.register_directive('uml', PlantUML_rst)