[py-svn] r35836 - in py/dist/py: bin misc rest rest/testing

cfbolz at codespeak.net cfbolz at codespeak.net
Sat Dec 16 21:30:14 CET 2006


Author: cfbolz
Date: Sat Dec 16 21:30:10 2006
New Revision: 35836

Modified:
   py/dist/py/bin/py.rest
   py/dist/py/misc/rest.py
   py/dist/py/rest/directive.py
   py/dist/py/rest/testing/test_directive.py
Log:
refactor the graphviz directive to make it useable with docutils versions > 4.0.
Slightly messy code :-(


Modified: py/dist/py/bin/py.rest
==============================================================================
--- py/dist/py/bin/py.rest	(original)
+++ py/dist/py/bin/py.rest	Sat Dec 16 21:30:10 2006
@@ -47,7 +47,7 @@
         filenames = [py.path.svnwc(x) for x in args]
     
     if options.topdf:
-        directive.BackendStore("latex")
+        directive.set_backend_and_register_directives("latex")
         
     for p in filenames:
         if not p.check():
@@ -62,7 +62,7 @@
                 rest.process(x)
         elif p.check(file=1):
             if p.ext == ".rst2pdfconfig":
-                directive.BackendStore("latex")
+                directive.set_backend_and_register_directives("latex")
                 process_configfile(p, options.debug)
             else:
                 if options.topdf:

Modified: py/dist/py/misc/rest.py
==============================================================================
--- py/dist/py/misc/rest.py	(original)
+++ py/dist/py/misc/rest.py	Sat Dec 16 21:30:10 2006
@@ -17,7 +17,7 @@
         stylesheet path (to be used if any)
     """
     from docutils.core import publish_string
-    directive.BackendStore("html")
+    directive.set_backend_and_register_directives("html")
     kwargs = {
         'stylesheet' : stylesheet, 
         'stylesheet_path': None,

Modified: py/dist/py/rest/directive.py
==============================================================================
--- py/dist/py/rest/directive.py	(original)
+++ py/dist/py/rest/directive.py	Sat Dec 16 21:30:10 2006
@@ -1,8 +1,10 @@
+# XXX this file is messy since it tries to deal with several docutils versions
 import py
 
 from py.__.rest.convert import convert_dot, latexformula2png
 
 import sys
+import docutils
 from docutils import nodes
 from docutils.parsers.rst import directives, states, roles
 from docutils.parsers.rst.directives import images
@@ -12,63 +14,87 @@
 except ImportError:
     from docutils.parsers.rst.states import unescape # docutils 0.3.5
 
-backend_to_image_format = {"html": "png", "latex": "pdf"}
+if docutils.__version__ >= '0.5':
+    ImageClass = images.Image
+
+else:
+    class ImageClass(object):
+        option_spec = images.image.options
+        def run(self):
+            return images.image(u'image',
+                                self.arguments,
+                                self.options,
+                                self.content,
+                                self.lineno,
+                                self.content_offset,
+                                self.block_text,
+                                self.state,
+                                self.state_machine)
 
-class BackendStore(object):
-    #XXX this whole class should not be there:
-    #XXX it is only used to work around the inflexibility of docutils:
-    # a directive does not know the path of the file it looks at, nor the
-    # format
-    def __init__(self, backend):
-        self.backend = backend
-        self.convert_to_format = backend_to_image_format[backend]
-        directives.register_directive("graphviz", self.graphviz_directive)
-        roles.register_canonical_role("latexformula", self.latexformula_role)
 
+backend_to_image_format = {"html": "png", "latex": "pdf"}
+
+class GraphvizDirective(ImageClass):
     def convert(self, fn, path):
         path = py.path.local(path).dirpath()
         dot = path.join(fn)
-        result = convert_dot(dot, self.convert_to_format)
+        result = convert_dot(dot, backend_to_image_format[_backend])
         return result.relto(path)
 
-    def graphviz_directive(self, name, arguments, options, content,
-                           lineno, content_offset, block_text, state,
-                           state_machine):
-        newname = self.convert(arguments[0], state.document.settings._source)
-        text = block_text.replace("graphviz", "image", 1)
-        text = text.replace(arguments[0], newname, 1)
-        return images.image(u'image', [newname], options, content, lineno,
-                            content_offset, text, state, state_machine)
-    graphviz_directive.arguments = (1, 0, 1)
-    graphviz_directive.options = {'alt': directives.unchanged,
-                                  'height': directives.nonnegative_int,
-                                  'width': directives.nonnegative_int,
-                                  'scale': directives.nonnegative_int,
-                                  'align': images.align,
-                                  'target': directives.unchanged_required,
-                                  'class': directives.class_option}
-
-    def latexformula_role(self, name, rawtext, text, lineno, inliner,
-                          options={}, content=[]):
-        if self.backend == 'latex':
-            options['format'] = 'latex'
-            return roles.raw_role(name, rawtext, text, lineno, inliner,
-                                  options, content)
-        else:
-            # XXX: make the place of the image directory configurable
-            sourcedir = py.path.local(inliner.document.settings._source).dirpath()
-            imagedir = sourcedir.join("img")
-            if not imagedir.check():
-                imagedir.mkdir()
-            # create halfway senseful imagename:
-            # use hash of formula + alphanumeric characters of it
-            # could
-            imagename = "%s_%s.png" % (
-                hash(text), "".join([c for c in text if c.isalnum()]))
-            image = imagedir.join(imagename)
-            latexformula2png(unescape(text, True), image)
-            imagenode = nodes.image(image.relto(sourcedir), uri=image.relto(sourcedir))
-            return [imagenode], []
-    latexformula_role.content = True
-    latexformula_role.options = {}
-
+    def run(self):
+        newname = self.convert(self.arguments[0],
+                               self.state.document.settings._source)
+        text = self.block_text.replace("graphviz", "image", 1)
+        self.block_text = text.replace(self.arguments[0], newname, 1)
+        self.name = u'image'
+        self.arguments = [newname]
+        return ImageClass.run(self)
+    
+    def old_interface(self):
+        def f(name, arguments, options, content, lineno,
+              content_offset, block_text, state, state_machine):
+            for arg in "name arguments options content lineno " \
+                       "content_offset block_text state state_machine".split():
+                setattr(self, arg, locals()[arg])
+            return self.run()
+        f.arguments = (1, 0, 1)
+        f.options = self.option_spec
+        return f
+
+
+_backend = None
+def set_backend_and_register_directives(backend):
+    #XXX this is only used to work around the inflexibility of docutils:
+    # a directive does not know the target format
+    global _backend
+    _backend = backend
+    if docutils.__version__ >= "0.5":
+        directives.register_directive("graphviz", GraphvizDirective)
+    else:
+        directives.register_directive("graphviz",
+                                      GraphvizDirective().old_interface())
+    roles.register_canonical_role("latexformula", latexformula_role)
+
+def latexformula_role(name, rawtext, text, lineno, inliner,
+                      options={}, content=[]):
+    if _backend == 'latex':
+        options['format'] = 'latex'
+        return roles.raw_role(name, rawtext, text, lineno, inliner,
+                              options, content)
+    else:
+        # XXX: make the place of the image directory configurable
+        sourcedir = py.path.local(inliner.document.settings._source).dirpath()
+        imagedir = sourcedir.join("img")
+        if not imagedir.check():
+            imagedir.mkdir()
+        # create halfway senseful imagename:
+        # use hash of formula + alphanumeric characters of it
+        # could
+        imagename = "%s_%s.png" % (
+            hash(text), "".join([c for c in text if c.isalnum()]))
+        image = imagedir.join(imagename)
+        latexformula2png(unescape(text, True), image)
+        imagenode = nodes.image(image.relto(sourcedir), uri=image.relto(sourcedir))
+        return [imagenode], []
+latexformula_role.content = True
+latexformula_role.options = {}

Modified: py/dist/py/rest/testing/test_directive.py
==============================================================================
--- py/dist/py/rest/testing/test_directive.py	(original)
+++ py/dist/py/rest/testing/test_directive.py	Sat Dec 16 21:30:10 2006
@@ -12,7 +12,7 @@
 def test_graphviz_html():
     if not is_on_path("dot"):
         py.test.skip("graphviz needed")
-    directive.BackendStore("html")
+    directive.set_backend_and_register_directives("html")
     #for reasons that elude me rest.process expects svnwcs???
     if not is_on_path("svn"):
         py.test.skip("svn needed")
@@ -28,10 +28,10 @@
     png.remove()
 
 def test_graphviz_pdf():
-    if is_on_path("dot") or not is_on_path("latex"):
+    if not is_on_path("dot") or not is_on_path("latex"):
         py.test.skip("graphviz and latex needed")
 
-    directive.BackendStore("latex")
+    directive.set_backend_and_register_directives("latex")
     txt = py.path.local(datadir.join("graphviz.txt"))
     pdf = txt.new(ext="pdf")
     dotpdf = datadir.join("example1.pdf")



More information about the pytest-commit mailing list