Debian Codegraph @

tools/ex2rst

raw
1 #!/usr/bin/env python
2 #
3 # Note: this file is copied (possibly with minor modifications) from the
4 # sources of the PyMVPA project - http://pymvpa.org. It remains licensed as
5 # the rest of PyMVPA (MIT license as of October 2010).
6 #
7 ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
8 #
9 # See COPYING file distributed along with the PyMVPA package for the
10 # copyright and license terms.
11 #
12 ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
13 """Helper to automagically generate ReST versions of examples"""
14 import os
15 import sys
16 import re
17 import glob
18 from optparse import OptionParser
19
20 __docformat__ = 'restructuredtext'
21
22
23 def auto_image(line):
24 """Automatically replace generic image markers with ones that have full
25 size (width/height) info, plus a :target: link to the original png, to be
26 used in the html docs.
27 """
28 img_re = re.compile(r'(\s*)\.\. image::\s*(.*)$')
29 m = img_re.match(line)
30 if m is None:
31 # Not an image declaration, leave the line alone and return unmodified
32 return line
33
34 # Match means it's an image spec, we rewrite it with extra tags
35 ini_space = m.group(1)
36 lines = [
37 line,
38 ini_space + ' :width: 500\n',
39 #ini_space + ' :height: 350\n'
40 ]
41 fspec = m.group(2)
42 if fspec.endswith('.*'):
43 fspec = fspec.replace('.*', '.png')
44 fspec = fspec.replace('fig/', '../_images/')
45 lines.append(ini_space + (' :target: %s\n' % fspec))
46 lines.append('\n')
47 return ''.join(lines)
48
49
50 def exfile2rst(filename):
51 """Open a Python script and convert it into an ReST string.
52 """
53 # output string
54 s = ''
55
56 # open source file
57 xfile = open(filename)
58
59 # parser status vars
60 inheader = True
61 indocs = False
62 doc2code = False
63 code2doc = False
64 # an empty line found in the example enables the check for a potentially
65 # indented docstring starting on the next line (as an attempt to exclude
66 # function or class docstrings)
67 last_line_empty = False
68 # indentation of indented docstring, which is removed from the RsT output
69 # since we typically do not want an indentation there.
70 indent_level = 0
71
72 for line in xfile:
73 # skip header
74 if inheader and \
75 not (line.startswith('"""') or line.startswith("'''")):
76 continue
77 # determine end of header
78 if inheader and (line.startswith('"""') or line.startswith("'''")):
79 inheader = False
80
81 # strip comments and remove trailing whitespace
82 if not indocs and last_line_empty:
83 # first remove leading whitespace and store indent level
84 cleanline = line[:line.find('#')].lstrip()
85 indent_level = len(line) - len(cleanline) - 1
86 cleanline = cleanline.rstrip()
87 else:
88 cleanline = line[:line.find('#')].rstrip()
89
90 if not indocs and line == '\n':
91 last_line_empty = True
92 else:
93 last_line_empty = False
94
95 # if we have something that should go into the text
96 if indocs \
97 or (cleanline.startswith('"""') or cleanline.startswith("'''")):
98 proc_line = None
99 # handle doc start
100 if not indocs:
101 # guaranteed to start with """
102 if len(cleanline) > 3 \
103 and (cleanline.endswith('"""') \
104 or cleanline.endswith("'''")):
105 # single line doc
106 code2doc = True
107 doc2code = True
108 proc_line = cleanline[3:-3]
109 else:
110 # must be start of multiline block
111 indocs = True
112 code2doc = True
113 # rescue what is left on the line
114 proc_line = cleanline[3:] # strip """
115 else:
116 # we are already in the docs
117 # handle doc end
118 if cleanline.endswith('"""') or cleanline.endswith("'''"):
119 indocs = False
120 doc2code = True
121 # rescue what is left on the line
122 proc_line = cleanline[:-3]
123 # reset the indentation
124 indent_level = 0
125 else:
126 # has to be documentation
127 # if the indentation is whitespace remove it, other wise
128 # keep it (accounts for some variation in docstring
129 # styles
130 real_indent = \
131 indent_level - len(line[:indent_level].lstrip())
132 proc_line = line[real_indent:]
133
134 if code2doc:
135 code2doc = False
136 s += '\n'
137
138 proc_line = auto_image(proc_line)
139
140 if proc_line:
141 s += proc_line.rstrip() + '\n'
142
143 else:
144 if doc2code:
145 doc2code = False
146 s += '\n\n.. code-block :: python\n'
147
148 # has to be code
149 s += ' %s' % line
150
151 xfile.close()
152
153 return s
154
155
156 def exfile2rstfile(filename, opts):
157 """
158 """
159 # doc filename
160 dfilename = os.path.basename(filename[:-3]) + '.rst'
161 dfilepath = os.path.join(opts.outdir, os.path.basename(dfilename))
162 print("Creating file %s." % os.path.abspath(dfilepath))
163
164 # open dest file
165 dfile = open(dfilepath, 'w')
166
167 # place header
168 dfile.write('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n')
169
170 # place cross-ref target
171 dfile.write('.. _example_' + dfilename[:-4] + ':\n\n')
172
173 # write converted ReST
174 dfile.write(exfile2rst(filename))
175
176 links = """
177
178 .. include:: ../../links_names.txt
179
180 """
181 dfile.write(links)
182
183 if opts.sourceref:
184 # write post example see also box
185 msg = """
186
187 .. admonition:: Example source code
188
189 You can download :download:`the full source code of this example <%s>`.
190 This same script is also included in `%s <%s>`__ under the :file:`%s`
191 directory.
192
193 """ % (os.path.relpath(filename, opts.outdir),
194 "Nipype1 Examples Niflow",
195 "https://github.com/niflows/nipype1-examples",
196 "package/niflow/nipype1/examples")
197
198 dfile.write(msg)
199
200 dfile.close()
201
202
203 def main():
204 parser = OptionParser(
205 usage="%prog [options] <filename|directory> [...]",
206 version="%prog 0.1", description="""\
207 %prog converts Python scripts into restructered text (ReST) format suitable for
208 integration into the Sphinx documentation framework. Its key feature is that it
209 extracts stand-alone (unassigned) single, or multiline triple-quote docstrings
210 and moves them out of the code listing so that they are rendered as regular
211 ReST, while at the same time maintaining their position relative to the
212 listing.
213
214 The detection of such docstrings is exclusively done by parsing the raw code so
215 it is never actually imported into a running Python session. Docstrings have to
216 be written using triple quotes (both forms " and ' are possible).
217
218 It is recommend that such docstrings are preceded and followed by an empty line.
219 Intended docstring can make use of the full linewidth from the second docstring
220 line on. If the indentation of multiline docstring is maintained for all lines,
221 the respective indentation is removed in the ReST output.
222
223 The parser algorithm automatically excludes file headers and starts with the
224 first (module-level) docstring instead.
225 """)
226
227 # define options
228 parser.add_option(
229 '--verbose',
230 action='store_true',
231 dest='verbose',
232 default=False,
233 help='print status messages')
234 parser.add_option(
235 '-x',
236 '--exclude',
237 action='append',
238 dest='excluded',
239 help="""\
240 Use this option to exclude single files from the to be parsed files. This is
241 especially useful to exclude files when parsing complete directories. This
242 option can be specified multiple times.
243 """)
244 parser.add_option(
245 '-o',
246 '--outdir',
247 action='store',
248 dest='outdir',
249 type='string',
250 default=None,
251 help="""\
252 Target directory to write the ReST output to. This is a required option.
253 """)
254 parser.add_option(
255 '--no-sourceref',
256 action='store_false',
257 default=True,
258 dest='sourceref',
259 help="""\
260 If specified, the source reference section will be suppressed.
261 """)
262 parser.add_option(
263 '--project',
264 type='string',
265 action='store',
266 default='',
267 dest='project',
268 help="""\
269 Name of the project that contains the examples. This name is used in the
270 'seealso' source references. Default: ''
271 """)
272
273 # parse options
274 (opts, args) = parser.parse_args() # read sys.argv[1:] by default
275
276 # check for required options
277 if opts.outdir is None:
278 print('Required option -o, --outdir not specified.')
279 sys.exit(1)
280
281 # build up list of things to parse
282 toparse = []
283 for t in args:
284 # expand dirs
285 if os.path.isdir(t):
286 # add all python files in that dir
287 toparse += glob.glob(os.path.join(t, '*.py'))
288 else:
289 toparse.append(t)
290
291 # filter parse list
292 if opts.excluded is not None:
293 toparse = [t for t in toparse if t not in opts.excluded]
294
295 toparse_list = toparse
296 toparse = set(toparse)
297
298 if len(toparse) != len(toparse_list):
299 print('Ignoring duplicate parse targets.')
300
301 os.makedirs(opts.outdir, exist_ok=True)
302
303 # finally process all examples
304 for t in toparse:
305 exfile2rstfile(t, opts)
306
307
308 if __name__ == '__main__':
309 main()