Skip to content

Instantly share code, notes, and snippets.

@akaihola
Created September 9, 2009 12:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akaihola/183672 to your computer and use it in GitHub Desktop.
Save akaihola/183672 to your computer and use it in GitHub Desktop.
Trac wiki markup to HTML
#!/usr/bin/env python
"""
tracwiki2html.py v1.0 (c) 2009 Antti Kaihola <akaihol+trac@ambitone.com>
This script converts Trac wiki markup to HTML.
Usage:
tracwiki2html.py file1.txt [file2.txt ...]
HTML versions are saved together with source files while changing the
extension to `.html`.
Requirements:
Python (tested with 2.5.4 and 2.6.2)
Trac in the PYTHONPATH (tested with 0.11.1)
For more information, see:
http://trac.edgewall.org/wiki/CookBook/Scripts/StandaloneWiki2Html
This script is licensed under the BSD license. See the file COPYING
for more information:
http://trac.edgewall.org/attachment/wiki/CookBook/Scripts/StandaloneWiki2Html/COPYING
"""
import codecs
from shutil import rmtree
from os.path import join, dirname
from tempfile import mkdtemp
import trac
from trac.env import Environment
from trac.test import Mock
from trac.mimeview.api import Context
from trac.wiki.formatter import format_to_html
STYLESHEET = codecs.open(
join(dirname(trac.__file__), 'htdocs', 'css', 'trac.css'),
'r', 'UTF-8').read()
TEMPLATE = u'''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>%%s</title>
<style type="text/css" />
%s
</style>
</head>
<body>
<div id="main">
<div id="content" class="browser">
<div id="preview" class="searchable">
%%s
</div>
</div>
</div>
</body>
</html>''' % STYLESHEET.replace('%', '%%')
def convert(filepath):
markup = codecs.open(filepath, 'r', 'UTF-8').read()
trac_directory = mkdtemp()
env = Environment(trac_directory, create=True)
req = Mock(href=Mock(wiki=lambda pagename, version: ''),
perm=lambda x: lambda *args: ['WIKI_VIEW'],
abs_href=Mock(base=''))
context = Context.from_request(req)
html_content = format_to_html(env, context, markup)
rmtree(trac_directory)
return TEMPLATE % (filepath, html_content)
if __name__ == '__main__':
import sys
for filepath in sys.argv[1:]:
html = convert(filepath)
htmlpath = '%s.html' % filepath.rsplit('.', 1)[0]
codecs.open(htmlpath, 'w', 'UTF-8').write(html)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment