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
|
#!/usr/bin/env python2.4
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
main(*sys.argv[1:])
|