-
Notifications
You must be signed in to change notification settings - Fork 0
/
rst_shift.py
310 lines (247 loc) · 8.23 KB
/
rst_shift.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
"""
ReStructuredText Utility for modifying ReStructuredText headings by the
specified shift offset.
"""
import re
import optparse
import logging
from collections import namedtuple, OrderedDict
from StringIO import StringIO
RGX_TITLE = re.compile(r'^([\=|\-|\~]+)\n(.*)\n^([\=|\-|\~]+)\n', re.MULTILINE)
RGX_HEADING = re.compile(r'^(?:[\=|\-|\~]?)(?:[\n]?)(.*)\n^([\=|\-|\~]+)\n',
re.MULTILINE)
RGX_TITLE = re.compile(r'^([\=|\-|\~]+)\n(.*)\n^([\=|\-|\~]+)\n', re.MULTILINE)
RGX_HEADING = re.compile(r'^(?:[\=|\-|\~]?)(?:[\n]?)(.*)\n^([\=|\-|\~]+)\n',
re.MULTILINE)
STANDARD_HEADINGS = OrderedDict((
(0, '=='),
(1, '='),
(2, '-'),
(3, '~'),
(4, "'"),
(5, '"'),
(6, '`'),
(7, '^'),
(8, '_'),
(9, '*'),
(10, '+'),
(11, '#'),
(12, '<'),
(13, '>'),
))
log = logging.getLogger()
def rst_shift(input_file, shiftby, shift_title=True):
"""
Shift the headings of a restructuredtext document
:param input_file: ReStructuredText file to read
:type input_file: str
:param shiftby: offset to shift headings by
:type shiftby: signed int
"""
f = input_file # open(input_file,'r+')
lines = f.read()
depthcount = 0
headings = OrderedDict()
log.debug("document headings: %s" % headings)
sections = []
# Special case for title
title_obj = RGX_TITLE.search(lines)
(overline, title, underline) = ('=','','=')
title = None
if title_obj:
(overline, title, underline) = title_obj.groups()
if not len(overline) == len(underline):
log.error( (overline, title, underline) )
raise Exception("is this a malformed title?")
else:
underline_char = overline[0]*2 # Because it is a header
headings[underline_char] = 0
log.debug("document headings: %s" % headings)
#print 0, title
log.debug(title)
text = title
depth = 0
log.debug("%d\t%s%s" % (depth, depth * ' ', text))
sections.append((0, underline_char, '\n'.join([overline, title, underline])))
# Extract section headings and existing section heading numbering
# for each heading in the document
for g in RGX_HEADING.finditer(lines):
(text, line) = g.groups()
if text in title and line == underline:
continue # TODO
underline_char = line[0]
# check if this heading type is already in the document
depth = headings.get(underline_char)
if not depth:
depthcount += 1
headings[underline_char] = depthcount
depth = depthcount
#log.debug(depth)
heading_level = headings[underline_char]
sections.append(
(heading_level, underline_char, '\n'.join((text, line))))
#print heading_level,
log.debug("%d\t%s%s" % (depth, heading_level * ' ', text))
log.debug("document headings: %s" % headings)
STD_HEADINGS = STANDARD_HEADINGS.values()
log.debug( ' '.join(STD_HEADINGS))
# TODO
# Expand headings with elements from STD_HEADINGS
#for char in sorted(headings.keys()):
# STD_HEADINGS.remove(char)
# TODO
headings_by_n = dict(
(x[1], x[0]) for x in headings.iteritems(),
)
for n in xrange(len(STD_HEADINGS)):
dest = depthcount + n # ((((shiftby > 0) and 1 or -1)) * n)
headings[STD_HEADINGS[n]] = dest
log.debug("document headings: %s" % headings)
log.debug("document headings: %s" % headings)
log.debug( ' '.join(STD_HEADINGS))
log.debug( ' '.join(str(x) for x in headings_by_n.values()))
# TODO
#output = copy.copy(lines)
output = lines
# Perform underline replacements
for section in sections:
(depth, char, text) = section
newdepth = depth + shiftby
newchar = headings_by_n[newdepth]
newtext = None
section, underline = text.split('\n',1)
# special case for title header
if shiftby != 0:
if depth == 0 and len(char) > 1:
char = char[0]
newchar = newchar[0]
elif depth == 1 and text.startswith('\n'):
newtext = '\n'
newtext = newtext or '\n'.join((section, underline.replace(char, newchar)))
log.error( (depth, newdepth, text, newtext) )
output = output.replace(text, newtext, 1)
return output
TestTuple = namedtuple('TestTuple', ('input','shiftkey','output',))
# (input,
_RST_TEST_INPUT_1="""
=====
Title
=====
title_content
Heading 1
=========
Heading 1.1
-----------
Heading 1.1.1
~~~~~~~~~~~~~
Heading 2
=========
"""
RST_TESTS = (
TestTuple(_RST_TEST_INPUT_1, 0, _RST_TEST_INPUT_1),
TestTuple(_RST_TEST_INPUT_1, 1,"""
Title
=====
title_content
Heading 1
---------
Heading 1.1
~~~~~~~~~~~
Heading 1.1.1
\"\"\"\"\"\"\"\"\"\"\"\"\"
Heading 2
---------
"""),
)
#RST_TEST_DICT = OrderedDict(
# ((t.input,t.shiftkey), t.output) for t in RST_TESTS
#)
import itertools
def _compare_test_output(_input, _output, expected_output):
formatstr="%-20s %-20s %-20s"
log.error("%-20s %-20s %-20s" % ("input", "output", "expected output"))
log.error("="*60)
for n in itertools.izip_longest(
_input.split('\n'),
_output.split('\n'),
expected_output.split('\n')):
log.error("%-20s %-20s %-20s" % (n))
import unittest
class Test_rst_shift(unittest.TestCase):
def test_rst_1(self):
for test_input, shift, expected_output in RST_TESTS:
input_ = StringIO(test_input)
output = rst_shift(input_, shift)
try:
self.assertEqual(expected_output, output)
except Exception, e:
log.exception(e)
log.error("# shift = %r" % shift)
_compare_test_output(test_input, output, expected_output)
pass
#raise
raise Exception()
def main():
import optparse
import logging
import sys
prs = optparse.OptionParser(
usage="./%prog : -s <int> -i <input_file> -o <output_file>",
description="Shift reStructuredText headings by -s")
prs.add_option('-s','--shiftby',
dest='shiftby',
action='store',
default=0,
help='Heading shift factor (-5, 5)')
prs.add_option('-i','--input-file',
dest='input_file',
action='store',
help='Input ReStructuredText file to shift headings')
prs.add_option('-o','--output-file',
dest='output_file',
action='store',
default=sys.stdout,
help='Output file to shift headings')
prs.add_option('-v', '--verbose',
dest='verbose',
action='store_true',
help="Show debugging output")
prs.add_option('-q', '--quiet',
dest='quiet',
action='store_true',
help="Disable logging")
prs.add_option('-t', '--test',
dest='run_tests',
action='store_true',
help="Run unit tests.")
(opts, args) = prs.parse_args()
if not opts.quiet:
logging.basicConfig()
if opts.verbose:
logging.getLogger().setLevel(logging.DEBUG)
if opts.run_tests:
import sys
sys.argv = [sys.argv[0]] + args
import unittest
exit(unittest.main())
(opts,args) = prs.parse_args()
if not (opts.input_file and opts.shiftby or opts.shiftby is 0):
raise Exception("Must specify both --input-file and --shiftby")
exit(0)
if opts.input_file == '-':
opts.input_file = sys.stdin
elif opts.input_file is not None:
opts.input_file = open(opts.input_file,'r+')
opts.output_file.write(
rst_shift(opts.input_file, int(opts.shiftby))
)
else:
if args:
log.error("Could not parse commandline arguments: %r" % args)
prs.print_help()
exit(1)
if __name__ == "__main__":
main()