#!/usr/bin/env python

“”“A small wrapper file for parsing ReST files at GitHub.”“”

__author__ = “Jannis Leidel” __copyright__ = “Copyright (C) 2008 Jannis Leidel” __license__ = “Public Domain” __version__ = “0.1”

try:

import locale
locale.setlocale(locale.LC_ALL, '')

except:

pass

import sys import codecs

from docutils.core import publish_parts from docutils.writers.html4css1 import Writer, HTMLTranslator

SETTINGS = {

'cloak_email_addresses': True,
'file_insertion_enabled': False,
'raw_enabled': False,
'strip_comments': True,
'doctitle_xform': False,
'report_level': 5,
'syntax_highlight' : 'none',
'math_output' : 'latex'

}

class GitHubHTMLTranslator(HTMLTranslator):

def visit_literal_block(self, node):
    classes = node.attributes['classes']
    if len(classes) >= 2 and classes[0] == 'code':
        language = classes[1]
        del classes[:]
        self.body.append(self.starttag(node, 'pre', lang=language))
    else:
        self.body.append(self.starttag(node, 'pre'))

def main():

"""
Parses the given ReST file or the redirected string input and returns the
HTML body.

Usage: rest2html < README.rst
       rest2html README.rst
"""
try:
    text = codecs.open(sys.argv[1], 'r', 'utf-8').read()
except IOError: # given filename could not be found
    return ''
except IndexError: # no filename given
    text = sys.stdin.read()

writer = Writer()
writer.translator_class = GitHubHTMLTranslator

parts = publish_parts(text, writer=writer, settings_overrides=SETTINGS)
if 'html_body' in parts:
    html = parts['html_body']

    # publish_parts() in python 2.x return dict values as Unicode type
    # in py3k Unicode is unavailable and values are of str type
    if isinstance(html, str):
        return html
    else:
        return html.encode('utf-8')
return ''

if __name__ == '__main__':

sys.stdout.write("%s%s" % (main(), "\n"))
sys.stdout.flush()