aboutsummaryrefslogtreecommitdiff
path: root/content/resources/rst_graphviz/rst2html.py
blob: 953ee97fa0014ff345a878d4e0898d868fb65f3f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/python

# $Id: rst2html.py 4564 2006-05-21 20:44:42Z wiemann $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.

"""
A minimal front end to the Docutils Publisher, producing HTML.
"""

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

try:
    import locale
    locale.setlocale(locale.LC_ALL, '')
except:
    pass

import subprocess
import os.path

from docutils.core import publish_cmdline, default_description
from docutils.parsers.rst import directives
from docutils.parsers.rst.directives.images import Figure


description = ('Generates (X)HTML documents from standalone reStructuredText '
               'sources.  ' + default_description)

class Graphviz(Figure):
    """ Generate a graphviz image
    """
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = True

    has_content = True

    option_spec = Figure.option_spec.copy()

    def run(self):

        if self.content.count("..") == 0:
            sep = -1 
            text = '\n'.join(self.content)
        else:
            sep = self.content.index("..")
            text = '\n'.join(self.content[:sep])
        extension = 'png'
        imageFile = "tmp/%s.%s" % (hash(text), extension)
        if not os.path.exists(imageFile):
            conversion = subprocess.Popen(['dot',
                '-T', 'png',
                "-Gcharset=utf8",
                '-o', imageFile,
                ],
                stdin=subprocess.PIPE
                )
            try:
                conversion.stdin.write("%s G { \n %s \n}" % (self.arguments[0],
                    text.encode("utf-8")))
            except:
                pass
            conversion.stdin.close()
            conversion.wait()

        self.arguments = [imageFile]
        self.options['scale'] = 50
        if sep == -1:
            self.content = None
        else:
            self.content = self.content[sep+1:]
        return Figure.run(self)

directives.register_directive('graphviz', Graphviz)

publish_cmdline(writer_name='html', description=description)