summaryrefslogtreecommitdiff
path: root/tools/rst2prettyhtml.py
diff options
context:
space:
mode:
authorLorry <lorry@roadtrain.codethink.co.uk>2012-08-22 15:47:16 +0100
committerLorry <lorry@roadtrain.codethink.co.uk>2012-08-22 15:47:16 +0100
commit25335618bf8755ce6b116ee14f47f5a1f2c821e9 (patch)
treed889d7ab3f9f985d0c54c534cb8052bd2e6d7163 /tools/rst2prettyhtml.py
downloadbzr-tarball-25335618bf8755ce6b116ee14f47f5a1f2c821e9.tar.gz
Tarball conversion
Diffstat (limited to 'tools/rst2prettyhtml.py')
-rwxr-xr-xtools/rst2prettyhtml.py71
1 files changed, 71 insertions, 0 deletions
diff --git a/tools/rst2prettyhtml.py b/tools/rst2prettyhtml.py
new file mode 100755
index 0000000..9b02b09
--- /dev/null
+++ b/tools/rst2prettyhtml.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+
+import errno
+import os
+from StringIO import StringIO
+import sys
+
+try:
+ from docutils.core import publish_file
+ from docutils.parsers import rst
+except ImportError:
+ print "Missing dependency. Please install docutils."
+ sys.exit(1)
+try:
+ from elementtree.ElementTree import XML
+ from elementtree import HTMLTreeBuilder
+except ImportError:
+ print "Missing dependency. Please install ElementTree."
+ sys.exit(1)
+try:
+ import kid
+except ImportError:
+ print "Missing dependency. Please install Kid."
+ sys.exit(1)
+
+
+def kidified_rest(rest_file, template_name):
+ xhtml_file = StringIO()
+ # prevent docutils from autoclosing the StringIO
+ xhtml_file.close = lambda: None
+ xhtml = publish_file(rest_file, writer_name='html', destination=xhtml_file,
+ settings_overrides={"doctitle_xform": 0}
+
+ )
+ xhtml_file.seek(0)
+ xml = HTMLTreeBuilder.parse(xhtml_file)
+ head = xml.find('head')
+ body = xml.find('body')
+ assert head is not None
+ assert body is not None
+ template=kid.Template(file=template_name,
+ head=head, body=body)
+ return (template.serialize(output="html"))
+
+
+def safe_open(filename, mode):
+ try:
+ return open(filename, mode + 'b')
+ except IOError, e:
+ if e.errno != errno.ENOENT:
+ raise
+ sys.stderr.write('file not found: %s\n' % sys.argv[2])
+ sys.exit(3)
+
+
+def main(template, source=None, target=None):
+ if source is not None:
+ rest_file = safe_open(source, 'r')
+ else:
+ rest_file = sys.stdin
+ if target is not None:
+ out_file = safe_open(target, 'w')
+ else:
+ out_file = sys.stdout
+ out_file.write(kidified_rest(rest_file, template))
+
+assert len(sys.argv) > 1
+
+# Strip options so only the arguments are passed
+args = [x for x in sys.argv[1:] if not x.startswith('-')]
+main(*args)