plantuml_rst.py 2.6 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 custom_url(generator, metadata):
  46. """ Saves globally the value of SITEURL configuration parameter """
  47. global global_siteurl
  48. global_siteurl = generator.settings['SITEURL']
  49. def pelican_init(pelicanobj):
  50. """ Prepare configurations for the MD plugin """
  51. try:
  52. import markdown
  53. from plantuml_md import PlantUMLMarkdownExtension
  54. except:
  55. # Markdown not available
  56. logger.debug("[plantuml] Markdown support not available")
  57. return
  58. # Register the Markdown plugin
  59. config = { 'siteurl': pelicanobj.settings['SITEURL'] }
  60. try:
  61. pelicanobj.settings['MD_EXTENSIONS'].append(PlantUMLMarkdownExtension(config))
  62. except:
  63. logger.error("[plantuml] Unable to configure plantuml markdown extension")
  64. def register():
  65. """Plugin registration."""
  66. signals.initialized.connect(pelican_init)
  67. signals.article_generator_context.connect(custom_url)
  68. directives.register_directive('uml', PlantUML_rst)