Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

root/trunk/sphinx/util/convert-trac.py

Revision 2602 (checked in by jaraco, 7 months ago)

Added replacements for code blocks and inline code

  • Property svn:keywords set to Id Rev Author Date
Line 
1 #!python
2 from __future__ import print_function
3 import sys
4 import re
5 import inspect
6 import optparse
7 import shutil
8 from StringIO import StringIO
9
10 def get_options():
11         parser = optparse.OptionParser()
12         options, args = parser.parse_args()
13         try:
14                 options.filename = args.pop()
15         except IndexError:
16                 parser.error("Filename required")
17         return options
18
19 # each of the replacement functions should have a docstring
20 #  which is a regular expression to be matched.
21
22 def replace_external_link(matcher):
23         r"\[(?P<href>(?P<scheme>\w+)\://.+?) (?P<name>.+?)\]"
24         return '`{name} <{href}>`_'.format(**matcher.groupdict())
25
26 def replace_wiki_link(matcher):
27         r"\[wiki\:(?P<ref>.+?) (?P<name>.+?)\]"
28         return '`{name} <TODO-fix wiki target {ref}>`_'.format(**matcher.groupdict())
29
30 # character array indexed by level for characters
31 heading_characters = [None, '*', '=', '-', '^']
32
33 def replace_headings(matcher):
34         r"^(?P<level>=+) (?P<name>.*) (?P=level)$"
35         level = len(matcher.groupdict()['level'])
36         char = heading_characters[level]
37         name = matcher.groupdict()['name']
38         return '\n'.join([name, char*len(name)])
39
40 def indent(block):
41         add_indent = lambda s: '    ' + s
42         lines = StringIO(block)
43         i_lines = map(add_indent, lines)
44         return ''.join(i_lines)
45
46 def replace_inline_code(matcher):
47         r"\{\{\{(?P<code>[^\n]*?)\}\}\}"
48         return '``{code}``'.format(**matcher.groupdict())
49
50 def replace_code_block(matcher):
51         r"\{\{\{\n(?P<code>(.|\n)*?)^\}\}\}"
52         return '::\n' + indent(matcher.groupdict()['code'])
53
54 replacements = [func for name, func in globals().items() if name.startswith('replace_')]
55
56 def convert_file(filename):
57         shutil.copy(filename, filename+'.bak')
58         text = open(filename).read()
59         new_text = text
60         for repl in replacements:
61                 pattern = re.compile(inspect.getdoc(repl), re.MULTILINE)
62                 new_text = pattern.sub(repl, new_text)
63
64         open(filename, 'w').write(new_text)
65         print("done")
66
67
68 def handle_command_line():
69         options = get_options()
70         convert_file(options.filename)
71
72 if __name__ == '__main__':
73         handle_command_line()
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets