Skip to content

Instantly share code, notes, and snippets.

@cou929
Created June 26, 2011 09:10
Show Gist options
  • Save cou929/1047427 to your computer and use it in GitHub Desktop.
Save cou929/1047427 to your computer and use it in GitHub Desktop.
convert bitbucket style wiki notation to ReStructured Text (ReST)
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
wiki2rst.py
convert bitbucket style wiki notation to ReStructured Text (ReST)
Kosei Moriyama <[email protected]>
TODO:
- add feature for other notation (now only supports heading (section structure) notation!)
'''
import re
import sys
from optparse import OptionParser
re_heading = re.compile('^(=+) (.*?) (=+)$')
def parse_heading(matched, line):
kinds = ['=', '-', '=', '-', '*', '#']
has_top = [True, True, False, False, False, False]
ret = ''
head, chars, null = matched.groups()
level = len(head)
line_len = len(chars)
if level < 1 or 6 < level:
raise Exception('invalid range of heading level: ' + level)
if has_top[level-1]:
ret += kinds[level-1] * line_len + '\n'
ret += chars + '\n'
ret += kinds[level-1] * line_len
ret += '\n'
return ret
rules = [
{'re': re_heading, 'fn': parse_heading}
]
def parse(line):
'''
parse a line of wiki notation string
and conver it to ReST.
>>> parse('= head1 =')
'=====\\nhead1\\n=====\\n'
>>> parse('== head2 ==')
'-----\\nhead2\\n-----\\n'
'''
ret = line
for rule in rules:
res = rule['re'].match(line)
if res:
ret = rule['fn'](res, line)
return ret
def wiki2rst(args):
if len(args) > 0:
for arg in args:
for line in open(arg, 'r'):
print parse(line),
else:
for line in sys.stdin:
print parse(line),
if __name__ == "__main__":
parser = OptionParser(usage='%prog FILENAME')
parser.add_option("-t", "--test", action="store_true",
dest="run_doctest", default=False, help="run doctest")
options, args = parser.parse_args()
if options.run_doctest:
import doctest
doctest.testmod()
else:
wiki2rst(args)
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment