lib/github/commands/rest2html (view raw)
1#!/usr/bin/env python
2
3"""A small wrapper file for parsing ReST files at GitHub."""
4
5__author__ = "Jannis Leidel"
6__copyright__ = "Copyright (C) 2008 Jannis Leidel"
7__license__ = "Public Domain"
8__version__ = "0.1"
9
10try:
11 import locale
12 locale.setlocale(locale.LC_ALL, '')
13except:
14 pass
15
16import sys
17import codecs
18
19from docutils.core import publish_parts
20from docutils.writers.html4css1 import Writer, HTMLTranslator
21
22SETTINGS = {
23 'cloak_email_addresses': True,
24 'file_insertion_enabled': False,
25 'raw_enabled': False,
26 'strip_comments': True,
27 'doctitle_xform': False,
28 'report_level': 5,
29 'syntax_highlight' : 'none',
30 'math_output' : 'latex'
31}
32
33class GitHubHTMLTranslator(HTMLTranslator):
34 def visit_literal_block(self, node):
35 classes = node.attributes['classes']
36 if len(classes) >= 2 and classes[0] == 'code':
37 language = classes[1]
38 del classes[:]
39 self.body.append(self.starttag(node, 'pre', lang=language))
40 else:
41 self.body.append(self.starttag(node, 'pre'))
42
43def main():
44 """
45 Parses the given ReST file or the redirected string input and returns the
46 HTML body.
47
48 Usage: rest2html < README.rst
49 rest2html README.rst
50 """
51 try:
52 text = codecs.open(sys.argv[1], 'r', 'utf-8').read()
53 except IOError: # given filename could not be found
54 return ''
55 except IndexError: # no filename given
56 text = sys.stdin.read()
57
58 writer = Writer()
59 writer.translator_class = GitHubHTMLTranslator
60
61 parts = publish_parts(text, writer=writer, settings_overrides=SETTINGS)
62 if 'html_body' in parts:
63 html = parts['html_body']
64
65 # publish_parts() in python 2.x return dict values as Unicode type
66 # in py3k Unicode is unavailable and values are of str type
67 if isinstance(html, str):
68 return html
69 else:
70 return html.encode('utf-8')
71 return ''
72
73if __name__ == '__main__':
74 sys.stdout.write("%s%s" % (main(), "\n"))
75 sys.stdout.flush()