author | robin <robin@reportlab.com> |
Tue, 07 Mar 2017 10:00:34 +0000 | |
changeset 4330 | 617ffa6bbdc8 |
parent 4302 | f3ff56a22b2e |
child 4370 | 823a8c33ce43 |
permissions | -rw-r--r-- |
2963 | 1 |
#!/usr/bin/env python |
4330 | 2 |
#Copyright ReportLab Europe Ltd. 2000-2017 |
2963 | 3 |
#see license.txt for license details |
4 |
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/tools/docco/docpy.py |
|
5 |
||
6 |
"""Generate documentation from live Python objects. |
|
7 |
||
8 |
This is an evolving module that allows to generate documentation |
|
9 |
for python modules in an automated fashion. The idea is to take |
|
10 |
live Python objects and inspect them in order to use as much mean- |
|
11 |
ingful information as possible to write in some formatted way into |
|
12 |
different types of documents. |
|
13 |
||
14 |
In principle a skeleton captures the gathered information and |
|
15 |
makes it available via a certain API to formatters that use it |
|
16 |
in whatever way they like to produce something of interest. The |
|
17 |
API allows for adding behaviour in subclasses of these formatters, |
|
18 |
such that, e.g. for certain classes it is possible to trigger |
|
19 |
special actions like displaying a sample image of a class that |
|
20 |
represents some graphical widget, say. |
|
21 |
||
22 |
Type the following for usage info: |
|
23 |
||
24 |
python docpy.py -h |
|
25 |
""" |
|
26 |
||
27 |
# Much inspired by Ka-Ping Yee's htmldoc.py. |
|
28 |
# Needs the inspect module. |
|
29 |
||
30 |
# Dinu Gherman |
|
31 |
||
32 |
||
33 |
__version__ = '0.8' |
|
34 |
||
35 |
||
3794 | 36 |
import sys, os, re, types, getopt, copy, time |
3881
b3e5f1288b86
docpy.py & graphdocpy.py: eliminate walk do some fixes
robin
parents:
3794
diff
changeset
|
37 |
from reportlab import isPy3 |
2963 | 38 |
from reportlab.pdfgen import canvas |
39 |
from reportlab.lib import colors |
|
40 |
from reportlab.lib.units import inch, cm |
|
41 |
from reportlab.lib.pagesizes import A4 |
|
42 |
from reportlab.lib import enums |
|
43 |
from reportlab.lib.enums import TA_CENTER, TA_LEFT |
|
44 |
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle |
|
45 |
from reportlab.platypus.flowables import Flowable, Spacer |
|
46 |
from reportlab.platypus.paragraph import Paragraph |
|
47 |
from reportlab.platypus.flowables \ |
|
48 |
import Flowable, Preformatted,Spacer, Image, KeepTogether, PageBreak |
|
49 |
from reportlab.platypus.tableofcontents import TableOfContents |
|
50 |
from reportlab.platypus.xpreformatted import XPreformatted |
|
51 |
from reportlab.platypus.frames import Frame |
|
52 |
from reportlab.platypus.doctemplate \ |
|
53 |
import PageTemplate, BaseDocTemplate |
|
54 |
from reportlab.platypus.tables import TableStyle, Table |
|
55 |
import inspect |
|
56 |
||
57 |
#################################################################### |
|
58 |
# |
|
59 |
# Stuff needed for building PDF docs. |
|
60 |
# |
|
61 |
#################################################################### |
|
62 |
||
63 |
||
64 |
def mainPageFrame(canvas, doc): |
|
65 |
"The page frame used for all PDF documents." |
|
66 |
||
67 |
canvas.saveState() |
|
68 |
||
69 |
pageNumber = canvas.getPageNumber() |
|
70 |
canvas.line(2*cm, A4[1]-2*cm, A4[0]-2*cm, A4[1]-2*cm) |
|
71 |
canvas.line(2*cm, 2*cm, A4[0]-2*cm, 2*cm) |
|
72 |
if pageNumber > 1: |
|
73 |
canvas.setFont('Times-Roman', 12) |
|
74 |
canvas.drawString(4 * inch, cm, "%d" % pageNumber) |
|
75 |
if hasattr(canvas, 'headerLine'): # hackish |
|
3881
b3e5f1288b86
docpy.py & graphdocpy.py: eliminate walk do some fixes
robin
parents:
3794
diff
changeset
|
76 |
headerline = ' \215 '.join(canvas.headerLine) # bullet |
2963 | 77 |
canvas.drawString(2*cm, A4[1]-1.75*cm, headerline) |
78 |
||
79 |
canvas.setFont('Times-Roman', 8) |
|
80 |
msg = "Generated with reportlab.lib.docpy. See http://www.reportlab.com!" |
|
81 |
canvas.drawString(2*cm, 1.65*cm, msg) |
|
82 |
||
83 |
canvas.restoreState() |
|
84 |
||
85 |
||
86 |
class MyTemplate(BaseDocTemplate): |
|
87 |
"The document template used for all PDF documents." |
|
88 |
||
89 |
_invalidInitArgs = ('pageTemplates',) |
|
90 |
||
91 |
def __init__(self, filename, **kw): |
|
92 |
frame1 = Frame(2.5*cm, 2.5*cm, 15*cm, 25*cm, id='F1') |
|
93 |
self.allowSplitting = 0 |
|
3326 | 94 |
BaseDocTemplate.__init__(self, filename, **kw) |
2963 | 95 |
self.addPageTemplates(PageTemplate('normal', [frame1], mainPageFrame)) |
96 |
||
97 |
||
98 |
def afterFlowable(self, flowable): |
|
99 |
"Takes care of header line, TOC and outline entries." |
|
100 |
||
101 |
if flowable.__class__.__name__ == 'Paragraph': |
|
102 |
f = flowable |
|
103 |
name7 = f.style.name[:7] |
|
104 |
name8 = f.style.name[:8] |
|
105 |
||
106 |
# Build a list of heading parts. |
|
107 |
# So far, this is the *last* item on the *previous* page... |
|
108 |
if name7 == 'Heading' and not hasattr(self.canv, 'headerLine'): |
|
109 |
self.canv.headerLine = [] |
|
110 |
||
111 |
if name8 == 'Heading0': |
|
112 |
self.canv.headerLine = [f.text] # hackish |
|
113 |
elif name8 == 'Heading1': |
|
114 |
if len(self.canv.headerLine) == 2: |
|
115 |
del self.canv.headerLine[-1] |
|
116 |
elif len(self.canv.headerLine) == 3: |
|
117 |
del self.canv.headerLine[-1] |
|
118 |
del self.canv.headerLine[-1] |
|
119 |
self.canv.headerLine.append(f.text) |
|
120 |
elif name8 == 'Heading2': |
|
121 |
if len(self.canv.headerLine) == 3: |
|
122 |
del self.canv.headerLine[-1] |
|
123 |
self.canv.headerLine.append(f.text) |
|
124 |
||
125 |
if name7 == 'Heading': |
|
126 |
# Register TOC entries. |
|
127 |
headLevel = int(f.style.name[7:]) |
|
128 |
self.notify('TOCEntry', (headLevel, flowable.getPlainText(), self.page)) |
|
129 |
||
130 |
# Add PDF outline entries. |
|
131 |
c = self.canv |
|
132 |
title = f.text |
|
133 |
key = str(hash(f)) |
|
134 |
||
135 |
try: |
|
136 |
if headLevel == 0: |
|
137 |
isClosed = 0 |
|
138 |
else: |
|
139 |
isClosed = 1 |
|
140 |
||
141 |
c.bookmarkPage(key) |
|
142 |
c.addOutlineEntry(title, key, level=headLevel, |
|
143 |
closed=isClosed) |
|
144 |
except ValueError: |
|
145 |
pass |
|
146 |
||
147 |
||
148 |
#################################################################### |
|
149 |
# |
|
150 |
# Utility functions (Ka-Ping Yee). |
|
151 |
# |
|
152 |
#################################################################### |
|
153 |
||
154 |
def htmlescape(text): |
|
155 |
"Escape special HTML characters, namely &, <, >." |
|
3794 | 156 |
return text.replace('&','&').replace('<','<').replace('>','>') |
2963 | 157 |
|
158 |
def htmlrepr(object): |
|
159 |
return htmlescape(repr(object)) |
|
160 |
||
161 |
||
162 |
def defaultformat(object): |
|
163 |
return '=' + htmlrepr(object) |
|
164 |
||
165 |
||
166 |
def getdoc(object): |
|
167 |
result = inspect.getdoc(object) |
|
168 |
if not result: |
|
169 |
try: |
|
170 |
result = inspect.getcomments(object) |
|
171 |
except: |
|
172 |
pass |
|
3794 | 173 |
return result and result.rstrip() + '\n' or '' |
2963 | 174 |
|
175 |
||
176 |
def reduceDocStringLength(docStr): |
|
177 |
"Return first line of a multiline string." |
|
178 |
||
3794 | 179 |
return docStr.split('\n')[0] |
2963 | 180 |
|
181 |
||
182 |
#################################################################### |
|
183 |
# |
|
184 |
# More utility functions |
|
185 |
# |
|
186 |
#################################################################### |
|
187 |
||
188 |
def makeHtmlSection(text, bgcolor='#FFA0FF'): |
|
189 |
"""Create HTML code for a section. |
|
190 |
||
191 |
This is usually a header for all classes or functions. |
|
192 |
u """ |
|
3794 | 193 |
text = htmlescape(text.expandtabs()) |
2963 | 194 |
result = [] |
4302 | 195 |
result.append("""<TABLE WIDTH="100\\%" BORDER="0">""") |
2963 | 196 |
result.append("""<TR><TD BGCOLOR="%s" VALIGN="CENTER">""" % bgcolor) |
197 |
result.append("""<H2>%s</H2>""" % text) |
|
198 |
result.append("""</TD></TR></TABLE>""") |
|
199 |
result.append('') |
|
200 |
||
3794 | 201 |
return '\n'.join(result) |
2963 | 202 |
|
203 |
||
204 |
def makeHtmlSubSection(text, bgcolor='#AAA0FF'): |
|
205 |
"""Create HTML code for a subsection. |
|
206 |
||
207 |
This is usually a class or function name. |
|
208 |
""" |
|
3794 | 209 |
text = htmlescape(text.expandtabs()) |
2963 | 210 |
result = [] |
4302 | 211 |
result.append("""<TABLE WIDTH="100\\%" BORDER="0">""") |
2963 | 212 |
result.append("""<TR><TD BGCOLOR="%s" VALIGN="CENTER">""" % bgcolor) |
213 |
result.append("""<H3><TT><FONT SIZE="+2">%s</FONT></TT></H3>""" % text) |
|
214 |
result.append("""</TD></TR></TABLE>""") |
|
215 |
result.append('') |
|
216 |
||
3794 | 217 |
return '\n'.join(result) |
2963 | 218 |
|
219 |
||
220 |
def makeHtmlInlineImage(text): |
|
221 |
"""Create HTML code for an inline image. |
|
222 |
""" |
|
223 |
||
224 |
return """<IMG SRC="%s" ALT="%s">""" % (text, text) |
|
225 |
||
226 |
||
227 |
#################################################################### |
|
228 |
# |
|
229 |
# Core "standard" docpy classes |
|
230 |
# |
|
231 |
#################################################################### |
|
232 |
||
233 |
class PackageSkeleton0: |
|
234 |
"""A class collecting 'interesting' information about a package.""" |
|
235 |
pass # Not yet! |
|
236 |
||
237 |
||
238 |
class ModuleSkeleton0: |
|
239 |
"""A class collecting 'interesting' information about a module.""" |
|
240 |
||
241 |
def __init__(self): |
|
242 |
# This is an ad-hoc, somewhat questionable 'data structure', |
|
243 |
# but for the time being it serves its purpose and is fairly |
|
244 |
# self-contained. |
|
245 |
self.module = {} |
|
246 |
self.functions = {} |
|
247 |
self.classes = {} |
|
248 |
||
249 |
||
250 |
# Might need more like this, later. |
|
251 |
def getModuleName(self): |
|
252 |
"""Return the name of the module being treated.""" |
|
253 |
||
254 |
return self.module['name'] |
|
255 |
||
256 |
||
257 |
# These inspect methods all rely on the inspect module. |
|
258 |
def inspect(self, object): |
|
259 |
"""Collect information about a given object.""" |
|
260 |
||
261 |
self.moduleSpace = object |
|
262 |
||
263 |
# Very non-OO, left for later... |
|
264 |
if inspect.ismodule(object): |
|
265 |
self._inspectModule(object) |
|
266 |
elif inspect.isclass(object): |
|
267 |
self._inspectClass(object) |
|
268 |
elif inspect.ismethod(object): |
|
269 |
self._inspectMethod(object) |
|
270 |
elif inspect.isfunction(object): |
|
271 |
self._inspectFunction(object) |
|
272 |
elif inspect.isbuiltin(object): |
|
273 |
self._inspectBuiltin(object) |
|
274 |
else: |
|
275 |
msg = "Don't know how to document this kind of object." |
|
3721 | 276 |
raise TypeError(msg) |
2963 | 277 |
|
278 |
||
279 |
def _inspectModule(self, object): |
|
280 |
"""Collect information about a given module object.""" |
|
281 |
name = object.__name__ |
|
282 |
||
283 |
self.module['name'] = name |
|
284 |
if hasattr(object, '__version__'): |
|
285 |
self.module['version'] = object.__version__ |
|
286 |
||
287 |
cadr = lambda list: list[1] |
|
3721 | 288 |
modules = list(map(cadr, inspect.getmembers(object, inspect.ismodule))) |
2963 | 289 |
|
290 |
classes, cdict = [], {} |
|
291 |
for key, value in inspect.getmembers(object, inspect.isclass): |
|
292 |
if (inspect.getmodule(value) or object) is object: |
|
293 |
classes.append(value) |
|
294 |
cdict[key] = cdict[value] = '#' + key |
|
295 |
||
296 |
functions, fdict = [], {} |
|
297 |
for key, value in inspect.getmembers(object, inspect.isroutine): |
|
298 |
#if inspect.isbuiltin(value) or inspect.getmodule(value) is object: |
|
299 |
functions.append(value) |
|
300 |
fdict[key] = '#-' + key |
|
301 |
if inspect.isfunction(value): fdict[value] = fdict[key] |
|
302 |
||
303 |
for c in classes: |
|
304 |
for base in c.__bases__: |
|
305 |
key, modname = base.__name__, base.__module__ |
|
3326 | 306 |
if modname != name and modname in sys.modules: |
2963 | 307 |
module = sys.modules[modname] |
308 |
if hasattr(module, key) and getattr(module, key) is base: |
|
3326 | 309 |
if key not in cdict: |
2963 | 310 |
cdict[key] = cdict[base] = modname + '.txt#' + key |
311 |
||
312 |
## doc = getdoc(object) or 'No doc string.' |
|
313 |
doc = getdoc(object) |
|
314 |
self.module['doc'] = doc |
|
315 |
||
316 |
if modules: |
|
3721 | 317 |
self.module['importedModules'] = [m.__name__ for m in modules] |
2963 | 318 |
|
319 |
if classes: |
|
320 |
for item in classes: |
|
321 |
self._inspectClass(item, fdict, cdict) |
|
322 |
||
323 |
if functions: |
|
324 |
for item in functions: |
|
325 |
self._inspectFunction(item, fdict, cdict) |
|
326 |
||
327 |
||
328 |
def _inspectClass(self, object, functions={}, classes={}): |
|
329 |
"""Collect information about a given class object.""" |
|
330 |
||
331 |
name = object.__name__ |
|
332 |
bases = object.__bases__ |
|
333 |
results = [] |
|
334 |
||
335 |
if bases: |
|
336 |
parents = [] |
|
337 |
for base in bases: |
|
338 |
parents.append(base) |
|
339 |
||
340 |
self.classes[name] = {} |
|
341 |
if bases: |
|
342 |
self.classes[name]['bases'] = parents |
|
343 |
||
344 |
methods, mdict = [], {} |
|
345 |
for key, value in inspect.getmembers(object, inspect.ismethod): |
|
346 |
methods.append(value) |
|
347 |
mdict[key] = mdict[value] = '#' + name + '-' + key |
|
348 |
||
349 |
if methods: |
|
3326 | 350 |
if 'methods' not in self.classes[name]: |
2963 | 351 |
self.classes[name]['methods'] = {} |
352 |
for item in methods: |
|
353 |
self._inspectMethod(item, functions, classes, mdict, name) |
|
354 |
||
355 |
## doc = getdoc(object) or 'No doc string.' |
|
356 |
doc = getdoc(object) |
|
357 |
self.classes[name]['doc'] = doc |
|
358 |
||
359 |
||
360 |
def _inspectMethod(self, object, functions={}, classes={}, methods={}, clname=''): |
|
361 |
"""Collect information about a given method object.""" |
|
362 |
||
3721 | 363 |
self._inspectFunction(object.__func__, functions, classes, methods, clname) |
2963 | 364 |
|
365 |
||
366 |
def _inspectFunction(self, object, functions={}, classes={}, methods={}, clname=''): |
|
367 |
"""Collect information about a given function object.""" |
|
368 |
try: |
|
369 |
args, varargs, varkw, defaults = inspect.getargspec(object) |
|
370 |
argspec = inspect.formatargspec( |
|
371 |
args, varargs, varkw, defaults, |
|
372 |
defaultformat=defaultformat) |
|
373 |
except TypeError: |
|
374 |
argspec = '( ... )' |
|
375 |
||
376 |
## doc = getdoc(object) or 'No doc string.' |
|
377 |
doc = getdoc(object) |
|
378 |
||
379 |
if object.__name__ == '<lambda>': |
|
380 |
decl = [' lambda ', argspec[1:-1]] |
|
381 |
# print ' %s' % decl |
|
382 |
# Do something with lambda functions as well... |
|
383 |
# ... |
|
384 |
else: |
|
385 |
decl = object.__name__ |
|
386 |
if not clname: |
|
387 |
self.functions[object.__name__] = {'signature':argspec, 'doc':doc} |
|
388 |
else: |
|
389 |
theMethods = self.classes[clname]['methods'] |
|
3326 | 390 |
if object.__name__ not in theMethods: |
2963 | 391 |
theMethods[object.__name__] = {} |
392 |
||
393 |
theMethod = theMethods[object.__name__] |
|
394 |
theMethod['signature'] = argspec |
|
395 |
theMethod['doc'] = doc |
|
396 |
||
397 |
||
398 |
def _inspectBuiltin(self, object): |
|
399 |
"""Collect information about a given built-in.""" |
|
400 |
||
3721 | 401 |
print(object.__name__ + '( ... )') |
2963 | 402 |
|
403 |
||
404 |
def walk(self, formatter): |
|
405 |
"""Call event methods in a visiting formatter.""" |
|
406 |
||
407 |
s = self |
|
408 |
f = formatter |
|
409 |
||
410 |
# The order is fixed, but could be made flexible |
|
411 |
# with one more template method... |
|
412 |
||
413 |
# Module |
|
414 |
modName = s.module['name'] |
|
415 |
modDoc = s.module['doc'] |
|
416 |
imported = s.module.get('importedModules', []) |
|
417 |
imported.sort() |
|
418 |
# f.indentLevel = f.indentLevel + 1 |
|
419 |
f.beginModule(modName, modDoc, imported) |
|
420 |
||
421 |
# Classes |
|
422 |
f.indentLevel = f.indentLevel + 1 |
|
3721 | 423 |
f.beginClasses(list(s.classes.keys())) |
424 |
items = list(s.classes.items()) |
|
2963 | 425 |
items.sort() |
426 |
for k, v in items: |
|
427 |
cDoc = s.classes[k]['doc'] |
|
428 |
bases = s.classes[k].get('bases', []) |
|
429 |
f.indentLevel = f.indentLevel + 1 |
|
430 |
f.beginClass(k, cDoc, bases) |
|
431 |
||
432 |
# This if should move out of this method. |
|
3326 | 433 |
if 'methods' not in s.classes[k]: |
2963 | 434 |
s.classes[k]['methods'] = {} |
435 |
||
436 |
# Methods |
|
437 |
#f.indentLevel = f.indentLevel + 1 |
|
3721 | 438 |
f.beginMethods(list(s.classes[k]['methods'].keys())) |
439 |
items = list(s.classes[k]['methods'].items()) |
|
2963 | 440 |
items.sort() |
441 |
for m, v in items: |
|
442 |
mDoc = v['doc'] |
|
443 |
sig = v['signature'] |
|
444 |
f.indentLevel = f.indentLevel + 1 |
|
445 |
f.beginMethod(m, mDoc, sig) |
|
446 |
f.indentLevel = f.indentLevel - 1 |
|
447 |
f.endMethod(m, mDoc, sig) |
|
448 |
||
449 |
#f.indentLevel = f.indentLevel - 1 |
|
3721 | 450 |
f.endMethods(list(s.classes[k]['methods'].keys())) |
2963 | 451 |
|
452 |
f.indentLevel = f.indentLevel - 1 |
|
453 |
f.endClass(k, cDoc, bases) |
|
454 |
||
455 |
# And what about attributes?! |
|
456 |
||
457 |
f.indentLevel = f.indentLevel - 1 |
|
3721 | 458 |
f.endClasses(list(s.classes.keys())) |
2963 | 459 |
|
460 |
# Functions |
|
461 |
f.indentLevel = f.indentLevel + 1 |
|
3721 | 462 |
f.beginFunctions(list(s.functions.keys())) |
463 |
items = list(s.functions.items()) |
|
2963 | 464 |
items.sort() |
465 |
for k, v in items: |
|
466 |
doc = v['doc'] |
|
467 |
sig = v['signature'] |
|
468 |
f.indentLevel = f.indentLevel + 1 |
|
469 |
f.beginFunction(k, doc, sig) |
|
470 |
f.indentLevel = f.indentLevel - 1 |
|
471 |
f.endFunction(k, doc, sig) |
|
472 |
f.indentLevel = f.indentLevel - 1 |
|
3721 | 473 |
f.endFunctions(list(s.functions.keys())) |
2963 | 474 |
|
475 |
#f.indentLevel = f.indentLevel - 1 |
|
476 |
f.endModule(modName, modDoc, imported) |
|
477 |
||
478 |
# Constants?! |
|
479 |
||
480 |
||
481 |
#################################################################### |
|
482 |
# |
|
483 |
# Core "standard" docpy document builders |
|
484 |
# |
|
485 |
#################################################################### |
|
486 |
||
487 |
class DocBuilder0: |
|
488 |
"""An abstract class to document the skeleton of a Python module. |
|
489 |
||
490 |
Instances take a skeleton instance s and call their s.walk() |
|
491 |
method. The skeleton, in turn, will walk over its tree structure |
|
492 |
while generating events and calling equivalent methods from a |
|
493 |
specific interface (begin/end methods). |
|
494 |
""" |
|
495 |
||
496 |
fileSuffix = None |
|
497 |
||
498 |
def __init__(self, skeleton=None): |
|
499 |
self.skeleton = skeleton |
|
500 |
self.packageName = None |
|
501 |
self.indentLevel = 0 |
|
502 |
||
503 |
||
504 |
def write(self, skeleton=None): |
|
505 |
if skeleton: |
|
506 |
self.skeleton = skeleton |
|
507 |
self.skeleton.walk(self) |
|
508 |
||
509 |
||
510 |
# Event-method API, called by associated skeleton instances. |
|
511 |
# In fact, these should raise a NotImplementedError, but for now we |
|
512 |
# just don't do anything here. |
|
513 |
||
514 |
# The following four methods are *not* called by skeletons! |
|
515 |
def begin(self, name='', typ=''): pass |
|
516 |
def end(self): pass |
|
517 |
||
518 |
# Methods for packaging should move into a future PackageSkeleton... |
|
519 |
def beginPackage(self, name): |
|
520 |
self.packageName = name |
|
521 |
||
522 |
def endPackage(self, name): |
|
523 |
pass |
|
524 |
||
525 |
# Only this subset is really called by associated skeleton instances. |
|
526 |
||
527 |
def beginModule(self, name, doc, imported): pass |
|
528 |
def endModule(self, name, doc, imported): pass |
|
529 |
||
530 |
def beginClasses(self, names): pass |
|
531 |
def endClasses(self, names): pass |
|
532 |
||
533 |
def beginClass(self, name, doc, bases): pass |
|
534 |
def endClass(self, name, doc, bases): pass |
|
535 |
||
536 |
def beginMethods(self, names): pass |
|
537 |
def endMethods(self, names): pass |
|
538 |
||
539 |
def beginMethod(self, name, doc, sig): pass |
|
540 |
def endMethod(self, name, doc, sig): pass |
|
541 |
||
542 |
def beginFunctions(self, names): pass |
|
543 |
def endFunctions(self, names): pass |
|
544 |
||
545 |
def beginFunction(self, name, doc, sig): pass |
|
546 |
def endFunction(self, name, doc, sig): pass |
|
547 |
||
548 |
||
549 |
class AsciiDocBuilder0(DocBuilder0): |
|
550 |
"""Document the skeleton of a Python module in ASCII format. |
|
551 |
||
552 |
The output will be an ASCII file with nested lines representing |
|
553 |
the hiearchical module structure. |
|
554 |
||
555 |
Currently, no doc strings are listed. |
|
556 |
""" |
|
557 |
||
558 |
fileSuffix = '.txt' |
|
559 |
outLines = [] |
|
560 |
indentLabel = ' ' |
|
561 |
||
562 |
def end(self): |
|
563 |
# This if should move into DocBuilder0... |
|
564 |
if self.packageName: |
|
565 |
self.outPath = self.packageName + self.fileSuffix |
|
566 |
elif self.skeleton: |
|
567 |
self.outPath = self.skeleton.getModuleName() + self.fileSuffix |
|
568 |
else: |
|
569 |
self.outPath = '' |
|
570 |
||
571 |
if self.outPath: |
|
572 |
file = open(self.outPath, 'w') |
|
573 |
for line in self.outLines: |
|
574 |
file.write(line + '\n') |
|
575 |
file.close() |
|
576 |
||
577 |
||
578 |
def beginPackage(self, name): |
|
579 |
DocBuilder0.beginPackage(self, name) |
|
580 |
lev, label = self.indentLevel, self.indentLabel |
|
581 |
self.outLines.append('%sPackage: %s' % (lev*label, name)) |
|
582 |
self.outLines.append('') |
|
583 |
||
584 |
||
585 |
def beginModule(self, name, doc, imported): |
|
586 |
append = self.outLines.append |
|
587 |
lev, label = self.indentLevel, self.indentLabel |
|
588 |
self.outLines.append('%sModule: %s' % (lev*label, name)) |
|
589 |
## self.outLines.append('%s%s' % ((lev+1)*label, reduceDocStringLength(doc))) |
|
590 |
append('') |
|
591 |
||
592 |
if imported: |
|
593 |
self.outLines.append('%sImported' % ((lev+1)*label)) |
|
594 |
append('') |
|
595 |
for m in imported: |
|
596 |
self.outLines.append('%s%s' % ((lev+2)*label, m)) |
|
597 |
append('') |
|
598 |
||
599 |
||
600 |
def beginClasses(self, names): |
|
601 |
if names: |
|
602 |
lev, label = self.indentLevel, self.indentLabel |
|
603 |
self.outLines.append('%sClasses' % (lev*label)) |
|
604 |
self.outLines.append('') |
|
605 |
||
606 |
||
607 |
def beginClass(self, name, doc, bases): |
|
608 |
append = self.outLines.append |
|
609 |
lev, label = self.indentLevel, self.indentLabel |
|
610 |
||
611 |
if bases: |
|
3721 | 612 |
bases = [b.__name__ for b in bases] # hack |
3794 | 613 |
append('%s%s(%s)' % (lev*label, name, ', '.join(bases))) |
2963 | 614 |
else: |
615 |
append('%s%s' % (lev*label, name)) |
|
616 |
return |
|
617 |
||
618 |
## append('%s%s' % ((lev+1)*label, reduceDocStringLength(doc))) |
|
619 |
self.outLines.append('') |
|
620 |
||
621 |
||
622 |
def endClass(self, name, doc, bases): |
|
623 |
self.outLines.append('') |
|
624 |
||
625 |
||
626 |
def beginMethod(self, name, doc, sig): |
|
627 |
append = self.outLines.append |
|
628 |
lev, label = self.indentLevel, self.indentLabel |
|
629 |
append('%s%s%s' % (lev*label, name, sig)) |
|
630 |
## append('%s%s' % ((lev+1)*label, reduceDocStringLength(doc))) |
|
631 |
## append('') |
|
632 |
||
633 |
||
634 |
def beginFunctions(self, names): |
|
635 |
if names: |
|
636 |
lev, label = self.indentLevel, self.indentLabel |
|
637 |
self.outLines.append('%sFunctions' % (lev*label)) |
|
638 |
self.outLines.append('') |
|
639 |
||
640 |
||
641 |
def endFunctions(self, names): |
|
642 |
self.outLines.append('') |
|
643 |
||
644 |
||
645 |
def beginFunction(self, name, doc, sig): |
|
646 |
append = self.outLines.append |
|
647 |
lev, label = self.indentLevel, self.indentLabel |
|
648 |
self.outLines.append('%s%s%s' % (lev*label, name, sig)) |
|
649 |
## append('%s%s' % ((lev+1)*label, reduceDocStringLength(doc))) |
|
650 |
## append('') |
|
651 |
||
652 |
||
653 |
class HtmlDocBuilder0(DocBuilder0): |
|
654 |
"A class to write the skeleton of a Python source in HTML format." |
|
655 |
||
656 |
fileSuffix = '.html' |
|
657 |
outLines = [] |
|
658 |
||
659 |
def begin(self, name='', typ=''): |
|
660 |
self.outLines.append("""<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">""") |
|
661 |
self.outLines.append("""<html>""") |
|
662 |
||
663 |
||
664 |
def end(self): |
|
665 |
if self.packageName: |
|
666 |
self.outPath = self.packageName + self.fileSuffix |
|
667 |
elif self.skeleton: |
|
668 |
self.outPath = self.skeleton.getModuleName() + self.fileSuffix |
|
669 |
else: |
|
670 |
self.outPath = '' |
|
671 |
||
672 |
if self.outPath: |
|
673 |
file = open(self.outPath, 'w') |
|
674 |
self.outLines.append('</body></html>') |
|
675 |
for line in self.outLines: |
|
676 |
file.write(line + '\n') |
|
677 |
file.close() |
|
678 |
||
679 |
||
680 |
def beginPackage(self, name): |
|
681 |
DocBuilder0.beginPackage(self, name) |
|
682 |
||
683 |
self.outLines.append("""<title>%s</title>""" % name) |
|
684 |
self.outLines.append("""<body bgcolor="#ffffff">""") |
|
685 |
self.outLines.append("""<H1>%s</H1>""" % name) |
|
686 |
self.outLines.append('') |
|
687 |
||
688 |
||
689 |
def beginModule(self, name, doc, imported): |
|
690 |
if not self.packageName: |
|
691 |
self.outLines.append("""<title>%s</title>""" % name) |
|
692 |
self.outLines.append("""<body bgcolor="#ffffff">""") |
|
693 |
||
694 |
self.outLines.append("""<H1>%s</H1>""" % name) |
|
695 |
self.outLines.append('') |
|
3794 | 696 |
for line in doc.split('\n'): |
2963 | 697 |
self.outLines.append("""<FONT SIZE="-1">%s</FONT>""" % htmlescape(line)) |
698 |
self.outLines.append('<BR>') |
|
699 |
self.outLines.append('') |
|
700 |
||
701 |
if imported: |
|
702 |
self.outLines.append(makeHtmlSection('Imported Modules')) |
|
703 |
self.outLines.append("""<ul>""") |
|
704 |
for m in imported: |
|
705 |
self.outLines.append("""<li>%s</li>""" % m) |
|
706 |
self.outLines.append("""</ul>""") |
|
707 |
||
708 |
||
709 |
def beginClasses(self, names): |
|
710 |
self.outLines.append(makeHtmlSection('Classes')) |
|
711 |
||
712 |
||
713 |
def beginClass(self, name, doc, bases): |
|
714 |
DocBuilder0.beginClass(self, name, doc, bases) |
|
715 |
||
716 |
## # Keep an eye on the base classes. |
|
717 |
## self.currentBaseClasses = bases |
|
718 |
||
719 |
if bases: |
|
3721 | 720 |
bases = [b.__name__ for b in bases] # hack |
3794 | 721 |
self.outLines.append(makeHtmlSubSection('%s(%s)' % (name, ', '.join(bases)))) |
2963 | 722 |
else: |
723 |
self.outLines.append(makeHtmlSubSection('%s' % name)) |
|
3794 | 724 |
for line in doc.split('\n'): |
2963 | 725 |
self.outLines.append("""<FONT SIZE="-1">%s</FONT>""" % htmlescape(line)) |
726 |
self.outLines.append('<BR>') |
|
727 |
||
728 |
self.outLines.append('') |
|
729 |
||
730 |
||
731 |
def beginMethods(self, names): |
|
732 |
pass |
|
733 |
## if names: |
|
734 |
## self.outLines.append('<H3>Method Interface</H3>') |
|
735 |
## self.outLines.append('') |
|
736 |
||
737 |
||
738 |
def beginMethod(self, name, doc, sig): |
|
739 |
self.beginFunction(name, doc, sig) |
|
740 |
||
741 |
||
742 |
def beginFunctions(self, names): |
|
743 |
self.outLines.append(makeHtmlSection('Functions')) |
|
744 |
||
745 |
||
746 |
def beginFunction(self, name, doc, sig): |
|
747 |
append = self.outLines.append |
|
748 |
append("""<DL><DL><DT><TT><STRONG>%s</STRONG>%s</TT></DT>""" % (name, sig)) |
|
749 |
append('') |
|
3794 | 750 |
for line in doc.split('\n'): |
2963 | 751 |
append("""<DD><FONT SIZE="-1">%s</FONT></DD>""" % htmlescape(line)) |
752 |
append('<BR>') |
|
753 |
append('</DL></DL>') |
|
754 |
append('') |
|
755 |
||
756 |
||
757 |
class PdfDocBuilder0(DocBuilder0): |
|
758 |
"Document the skeleton of a Python module in PDF format." |
|
759 |
||
760 |
fileSuffix = '.pdf' |
|
761 |
||
762 |
def makeHeadingStyle(self, level, typ=None, doc=''): |
|
763 |
"Make a heading style for different types of module content." |
|
764 |
||
765 |
if typ in ('package', 'module', 'class'): |
|
766 |
style = ParagraphStyle(name='Heading'+str(level), |
|
767 |
fontName = 'Courier-Bold', |
|
768 |
fontSize=14, |
|
769 |
leading=18, |
|
770 |
spaceBefore=12, |
|
771 |
spaceAfter=6) |
|
772 |
elif typ in ('method', 'function'): |
|
773 |
if doc: |
|
774 |
style = ParagraphStyle(name='Heading'+str(level), |
|
775 |
fontName = 'Courier-Bold', |
|
776 |
fontSize=12, |
|
777 |
leading=18, |
|
778 |
firstLineIndent=-18, |
|
779 |
leftIndent=36, |
|
780 |
spaceBefore=0, |
|
781 |
spaceAfter=-3) |
|
782 |
else: |
|
783 |
style = ParagraphStyle(name='Heading'+str(level), |
|
784 |
fontName = 'Courier-Bold', |
|
785 |
fontSize=12, |
|
786 |
leading=18, |
|
787 |
firstLineIndent=-18, |
|
788 |
leftIndent=36, |
|
789 |
spaceBefore=0, |
|
790 |
spaceAfter=0) |
|
791 |
||
792 |
else: |
|
793 |
style = ParagraphStyle(name='Heading'+str(level), |
|
794 |
fontName = 'Times-Bold', |
|
795 |
fontSize=14, |
|
796 |
leading=18, |
|
797 |
spaceBefore=12, |
|
798 |
spaceAfter=6) |
|
799 |
||
800 |
return style |
|
801 |
||
802 |
||
803 |
def begin(self, name='', typ=''): |
|
804 |
styleSheet = getSampleStyleSheet() |
|
805 |
self.code = styleSheet['Code'] |
|
806 |
self.bt = styleSheet['BodyText'] |
|
807 |
self.story = [] |
|
808 |
||
809 |
# Cover page |
|
810 |
t = time.gmtime(time.time()) |
|
811 |
timeString = time.strftime("%Y-%m-%d %H:%M", t) |
|
812 |
self.story.append(Paragraph('<font size=18>Documentation for %s "%s"</font>' % (typ, name), self.bt)) |
|
813 |
self.story.append(Paragraph('<font size=18>Generated by: docpy.py version %s</font>' % __version__, self.bt)) |
|
814 |
self.story.append(Paragraph('<font size=18>Date generated: %s</font>' % timeString, self.bt)) |
|
815 |
self.story.append(Paragraph('<font size=18>Format: PDF</font>', self.bt)) |
|
816 |
self.story.append(PageBreak()) |
|
817 |
||
818 |
# Table of contents |
|
819 |
toc = TableOfContents() |
|
820 |
self.story.append(toc) |
|
821 |
self.story.append(PageBreak()) |
|
822 |
||
823 |
||
824 |
def end(self): |
|
825 |
if self.outPath is not None: |
|
826 |
pass |
|
827 |
elif self.packageName: |
|
828 |
self.outPath = self.packageName + self.fileSuffix |
|
829 |
elif self.skeleton: |
|
830 |
self.outPath = self.skeleton.getModuleName() + self.fileSuffix |
|
831 |
else: |
|
832 |
self.outPath = '' |
|
3721 | 833 |
print('output path is %s' % self.outPath) |
2963 | 834 |
if self.outPath: |
835 |
doc = MyTemplate(self.outPath) |
|
836 |
doc.multiBuild(self.story) |
|
837 |
||
838 |
||
839 |
def beginPackage(self, name): |
|
840 |
DocBuilder0.beginPackage(self, name) |
|
841 |
story = self.story |
|
842 |
story.append(Paragraph(name, self.makeHeadingStyle(self.indentLevel, 'package'))) |
|
843 |
||
844 |
||
845 |
def beginModule(self, name, doc, imported): |
|
846 |
story = self.story |
|
847 |
bt = self.bt |
|
848 |
story.append(Paragraph(name, self.makeHeadingStyle(self.indentLevel, 'module'))) |
|
849 |
if doc: |
|
850 |
story.append(XPreformatted(htmlescape(doc), bt)) |
|
851 |
story.append(XPreformatted('', bt)) |
|
852 |
||
853 |
if imported: |
|
854 |
story.append(Paragraph('Imported modules', self.makeHeadingStyle(self.indentLevel + 1))) |
|
855 |
for m in imported: |
|
856 |
p = Paragraph('<bullet>\201</bullet> %s' % m, bt) |
|
857 |
p.style.bulletIndent = 10 |
|
858 |
p.style.leftIndent = 18 |
|
859 |
story.append(p) |
|
860 |
||
861 |
||
862 |
def endModule(self, name, doc, imported): |
|
863 |
DocBuilder0.endModule(self, name, doc, imported) |
|
864 |
self.story.append(PageBreak()) |
|
865 |
||
866 |
||
867 |
def beginClasses(self, names): |
|
868 |
self.story.append(Paragraph('Classes', self.makeHeadingStyle(self.indentLevel))) |
|
869 |
||
870 |
||
871 |
def beginClass(self, name, doc, bases): |
|
872 |
bt = self.bt |
|
873 |
story = self.story |
|
874 |
if bases: |
|
3721 | 875 |
bases = [b.__name__ for b in bases] # hack |
3794 | 876 |
story.append(Paragraph('%s(%s)' % (name,', '.join(bases)), self.makeHeadingStyle(self.indentLevel, 'class'))) |
2963 | 877 |
else: |
878 |
story.append(Paragraph(name, self.makeHeadingStyle(self.indentLevel, 'class'))) |
|
879 |
||
880 |
if doc: |
|
881 |
story.append(XPreformatted(htmlescape(doc), bt)) |
|
882 |
story.append(XPreformatted('', bt)) |
|
883 |
||
884 |
||
885 |
def beginMethod(self, name, doc, sig): |
|
886 |
bt = self.bt |
|
887 |
story = self.story |
|
888 |
story.append(Paragraph(name+sig, self.makeHeadingStyle(self.indentLevel, 'method', doc))) |
|
889 |
if doc: |
|
890 |
story.append(XPreformatted(htmlescape(doc), bt)) |
|
891 |
story.append(XPreformatted('', bt)) |
|
892 |
||
893 |
||
894 |
def beginFunctions(self, names): |
|
895 |
if names: |
|
896 |
self.story.append(Paragraph('Functions', self.makeHeadingStyle(self.indentLevel))) |
|
897 |
||
898 |
||
899 |
def beginFunction(self, name, doc, sig): |
|
900 |
bt = self.bt |
|
901 |
story = self.story |
|
902 |
story.append(Paragraph(name+sig, self.makeHeadingStyle(self.indentLevel, 'function'))) |
|
903 |
if doc: |
|
904 |
story.append(XPreformatted(htmlescape(doc), bt)) |
|
905 |
story.append(XPreformatted('', bt)) |
|
906 |
||
907 |
||
908 |
class UmlPdfDocBuilder0(PdfDocBuilder0): |
|
909 |
"Document the skeleton of a Python module with UML class diagrams." |
|
910 |
||
911 |
fileSuffix = '.pdf' |
|
912 |
||
913 |
def begin(self, name='', typ=''): |
|
914 |
styleSheet = getSampleStyleSheet() |
|
915 |
self.h1 = styleSheet['Heading1'] |
|
916 |
self.h2 = styleSheet['Heading2'] |
|
917 |
self.h3 = styleSheet['Heading3'] |
|
918 |
self.code = styleSheet['Code'] |
|
919 |
self.bt = styleSheet['BodyText'] |
|
920 |
self.story = [] |
|
921 |
self.classCompartment = '' |
|
922 |
self.methodCompartment = [] |
|
923 |
||
924 |
||
925 |
def beginModule(self, name, doc, imported): |
|
926 |
story = self.story |
|
927 |
h1, h2, h3, bt = self.h1, self.h2, self.h3, self.bt |
|
928 |
styleSheet = getSampleStyleSheet() |
|
929 |
bt1 = styleSheet['BodyText'] |
|
930 |
||
931 |
story.append(Paragraph(name, h1)) |
|
932 |
story.append(XPreformatted(doc, bt1)) |
|
933 |
||
934 |
if imported: |
|
935 |
story.append(Paragraph('Imported modules', self.makeHeadingStyle(self.indentLevel + 1))) |
|
936 |
for m in imported: |
|
937 |
p = Paragraph('<bullet>\201</bullet> %s' % m, bt1) |
|
938 |
p.style.bulletIndent = 10 |
|
939 |
p.style.leftIndent = 18 |
|
940 |
story.append(p) |
|
941 |
||
942 |
||
943 |
def endModule(self, name, doc, imported): |
|
944 |
self.story.append(PageBreak()) |
|
945 |
PdfDocBuilder0.endModule(self, name, doc, imported) |
|
946 |
||
947 |
||
948 |
def beginClasses(self, names): |
|
949 |
h1, h2, h3, bt = self.h1, self.h2, self.h3, self.bt |
|
950 |
if names: |
|
951 |
self.story.append(Paragraph('Classes', h2)) |
|
952 |
||
953 |
||
954 |
def beginClass(self, name, doc, bases): |
|
955 |
self.classCompartment = '' |
|
956 |
self.methodCompartment = [] |
|
957 |
||
958 |
if bases: |
|
3721 | 959 |
bases = [b.__name__ for b in bases] # hack |
3794 | 960 |
self.classCompartment = '%s(%s)' % (name, ', '.join(bases)) |
2963 | 961 |
else: |
962 |
self.classCompartment = name |
|
963 |
||
964 |
||
965 |
def endClass(self, name, doc, bases): |
|
966 |
h1, h2, h3, bt, code = self.h1, self.h2, self.h3, self.bt, self.code |
|
967 |
styleSheet = getSampleStyleSheet() |
|
968 |
bt1 = styleSheet['BodyText'] |
|
969 |
story = self.story |
|
970 |
||
971 |
# Use only the first line of the class' doc string -- |
|
972 |
# no matter how long! (Do the same later for methods) |
|
973 |
classDoc = reduceDocStringLength(doc) |
|
974 |
||
975 |
tsa = tableStyleAttributes = [] |
|
976 |
||
977 |
# Make table with class and method rows |
|
978 |
# and add it to the story. |
|
979 |
p = Paragraph('<b>%s</b>' % self.classCompartment, bt) |
|
980 |
p.style.alignment = TA_CENTER |
|
981 |
rows = [(p,)] |
|
982 |
# No doc strings, now... |
|
983 |
# rows = rows + [(Paragraph('<i>%s</i>' % classDoc, bt1),)] |
|
984 |
lenRows = len(rows) |
|
985 |
tsa.append(('BOX', (0,0), (-1,lenRows-1), 0.25, colors.black)) |
|
986 |
for name, doc, sig in self.methodCompartment: |
|
987 |
nameAndSig = Paragraph('<b>%s</b>%s' % (name, sig), bt1) |
|
988 |
rows.append((nameAndSig,)) |
|
989 |
# No doc strings, now... |
|
990 |
# docStr = Paragraph('<i>%s</i>' % reduceDocStringLength(doc), bt1) |
|
991 |
# rows.append((docStr,)) |
|
992 |
tsa.append(('BOX', (0,lenRows), (-1,-1), 0.25, colors.black)) |
|
993 |
t = Table(rows, (12*cm,)) |
|
994 |
tableStyle = TableStyle(tableStyleAttributes) |
|
995 |
t.setStyle(tableStyle) |
|
996 |
self.story.append(t) |
|
997 |
self.story.append(Spacer(1*cm, 1*cm)) |
|
998 |
||
999 |
||
1000 |
def beginMethod(self, name, doc, sig): |
|
1001 |
self.methodCompartment.append((name, doc, sig)) |
|
1002 |
||
1003 |
||
1004 |
def beginFunctions(self, names): |
|
1005 |
h1, h2, h3, bt = self.h1, self.h2, self.h3, self.bt |
|
1006 |
if names: |
|
1007 |
self.story.append(Paragraph('Functions', h2)) |
|
1008 |
self.classCompartment = chr(171) + ' Module-Level Functions ' + chr(187) |
|
1009 |
self.methodCompartment = [] |
|
1010 |
||
1011 |
||
1012 |
def beginFunction(self, name, doc, sig): |
|
1013 |
self.methodCompartment.append((name, doc, sig)) |
|
1014 |
||
1015 |
||
1016 |
def endFunctions(self, names): |
|
1017 |
h1, h2, h3, bt, code = self.h1, self.h2, self.h3, self.bt, self.code |
|
1018 |
styleSheet = getSampleStyleSheet() |
|
1019 |
bt1 = styleSheet['BodyText'] |
|
1020 |
story = self.story |
|
1021 |
if not names: |
|
1022 |
return |
|
1023 |
||
1024 |
tsa = tableStyleAttributes = [] |
|
1025 |
||
1026 |
# Make table with class and method rows |
|
1027 |
# and add it to the story. |
|
1028 |
p = Paragraph('<b>%s</b>' % self.classCompartment, bt) |
|
1029 |
p.style.alignment = TA_CENTER |
|
1030 |
rows = [(p,)] |
|
1031 |
lenRows = len(rows) |
|
1032 |
tsa.append(('BOX', (0,0), (-1,lenRows-1), 0.25, colors.black)) |
|
1033 |
for name, doc, sig in self.methodCompartment: |
|
1034 |
nameAndSig = Paragraph('<b>%s</b>%s' % (name, sig), bt1) |
|
1035 |
rows.append((nameAndSig,)) |
|
1036 |
# No doc strings, now... |
|
1037 |
# docStr = Paragraph('<i>%s</i>' % reduceDocStringLength(doc), bt1) |
|
1038 |
# rows.append((docStr,)) |
|
1039 |
tsa.append(('BOX', (0,lenRows), (-1,-1), 0.25, colors.black)) |
|
1040 |
t = Table(rows, (12*cm,)) |
|
1041 |
tableStyle = TableStyle(tableStyleAttributes) |
|
1042 |
t.setStyle(tableStyle) |
|
1043 |
self.story.append(t) |
|
1044 |
self.story.append(Spacer(1*cm, 1*cm)) |
|
1045 |
||
1046 |
||
1047 |
#################################################################### |
|
1048 |
# |
|
1049 |
# Main |
|
1050 |
# |
|
1051 |
#################################################################### |
|
1052 |
||
1053 |
def printUsage(): |
|
1054 |
"""docpy.py - Automated documentation for Python source code. |
|
1055 |
||
1056 |
Usage: python docpy.py [options] |
|
1057 |
||
1058 |
[options] |
|
1059 |
-h Print this help message. |
|
1060 |
||
1061 |
-f name Use the document builder indicated by 'name', |
|
1062 |
e.g. Ascii, Html, Pdf (default), UmlPdf. |
|
1063 |
||
1064 |
-m module Generate document for module named 'module' |
|
1065 |
(default is 'docpy'). |
|
1066 |
'module' may follow any of these forms: |
|
1067 |
- docpy.py |
|
1068 |
- docpy |
|
1069 |
- c:\\test\\docpy |
|
1070 |
and can be any of these: |
|
1071 |
- standard Python modules |
|
1072 |
- modules in the Python search path |
|
1073 |
- modules in the current directory |
|
1074 |
||
1075 |
-p package Generate document for package named 'package'. |
|
1076 |
'package' may follow any of these forms: |
|
1077 |
- reportlab |
|
1078 |
- reportlab.platypus |
|
1079 |
- c:\\test\\reportlab |
|
1080 |
and can be any of these: |
|
1081 |
- standard Python packages (?) |
|
1082 |
- packages in the Python search path |
|
1083 |
- packages in the current directory |
|
1084 |
||
1085 |
-s Silent mode (default is unset). |
|
1086 |
||
1087 |
Examples: |
|
1088 |
||
1089 |
python docpy.py -h |
|
1090 |
python docpy.py -m docpy.py -f Ascii |
|
1091 |
python docpy.py -m string -f Html |
|
1092 |
python docpy.py -m signsandsymbols.py -f Pdf |
|
1093 |
python docpy.py -p reportlab.platypus -f UmlPdf |
|
1094 |
python docpy.py -p reportlab.lib -s -f UmlPdf |
|
1095 |
""" |
|
1096 |
||
1097 |
||
1098 |
def documentModule0(pathOrName, builder, opts={}): |
|
1099 |
"""Generate documentation for one Python file in some format. |
|
1100 |
||
1101 |
This handles Python standard modules like string, custom modules |
|
1102 |
on the Python search path like e.g. docpy as well as modules |
|
1103 |
specified with their full path like C:/tmp/junk.py. |
|
1104 |
||
1105 |
The doc file will always be saved in the current directory with |
|
1106 |
a basename equal to that of the module, e.g. docpy. |
|
1107 |
""" |
|
1108 |
||
1109 |
cwd = os.getcwd() |
|
1110 |
||
1111 |
# Append directory to Python search path if we get one. |
|
1112 |
dirName = os.path.dirname(pathOrName) |
|
1113 |
if dirName: |
|
1114 |
sys.path.append(dirName) |
|
1115 |
||
1116 |
# Remove .py extension from module name. |
|
1117 |
if pathOrName[-3:] == '.py': |
|
1118 |
modname = pathOrName[:-3] |
|
1119 |
else: |
|
1120 |
modname = pathOrName |
|
1121 |
||
1122 |
# Remove directory paths from module name. |
|
1123 |
if dirName: |
|
1124 |
modname = os.path.basename(modname) |
|
1125 |
||
1126 |
# Load the module. |
|
1127 |
try: |
|
1128 |
module = __import__(modname) |
|
1129 |
except: |
|
3721 | 1130 |
print('Failed to import %s.' % modname) |
2963 | 1131 |
os.chdir(cwd) |
1132 |
return |
|
1133 |
||
1134 |
# Do the real documentation work. |
|
1135 |
s = ModuleSkeleton0() |
|
1136 |
s.inspect(module) |
|
1137 |
builder.write(s) |
|
1138 |
||
1139 |
# Remove appended directory from Python search path if we got one. |
|
1140 |
if dirName: |
|
1141 |
del sys.path[-1] |
|
1142 |
||
1143 |
os.chdir(cwd) |
|
1144 |
||
1145 |
||
3721 | 1146 |
def _packageWalkCallback(xxx_todo_changeme, dirPath, files): |
2963 | 1147 |
"A callback function used when waking over a package tree." |
3721 | 1148 |
(builder, opts) = xxx_todo_changeme |
1149 |
files = [f for f in files if f != '__init__.py'] |
|
2963 | 1150 |
|
3721 | 1151 |
files = [f for f in files if f[-3:] == '.py'] |
2963 | 1152 |
for f in files: |
1153 |
path = os.path.join(dirPath, f) |
|
1154 |
if not opts.get('isSilent', 0): |
|
3721 | 1155 |
print(path) |
2963 | 1156 |
builder.indentLevel = builder.indentLevel + 1 |
1157 |
documentModule0(path, builder) |
|
1158 |
builder.indentLevel = builder.indentLevel - 1 |
|
1159 |
||
1160 |
||
1161 |
def documentPackage0(pathOrName, builder, opts={}): |
|
1162 |
"""Generate documentation for one Python package in some format. |
|
1163 |
||
1164 |
'pathOrName' can be either a filesystem path leading to a Python |
|
1165 |
package or package name whose path will be resolved by importing |
|
1166 |
the top-level module. |
|
1167 |
||
1168 |
The doc file will always be saved in the current directory with |
|
1169 |
a basename equal to that of the package, e.g. reportlab.lib. |
|
1170 |
""" |
|
1171 |
||
1172 |
# Did we get a package path with OS-dependant seperators...? |
|
1173 |
if os.sep in pathOrName: |
|
1174 |
path = pathOrName |
|
1175 |
name = os.path.splitext(os.path.basename(path))[0] |
|
1176 |
# ... or rather a package name? |
|
1177 |
else: |
|
1178 |
name = pathOrName |
|
1179 |
package = __import__(name) |
|
1180 |
# Some special care needed for dotted names. |
|
1181 |
if '.' in name: |
|
3794 | 1182 |
subname = 'package' + name[name.find('.'):] |
2963 | 1183 |
package = eval(subname) |
1184 |
path = os.path.dirname(package.__file__) |
|
1185 |
||
1186 |
cwd = os.getcwd() |
|
1187 |
builder.beginPackage(name) |
|
3881
b3e5f1288b86
docpy.py & graphdocpy.py: eliminate walk do some fixes
robin
parents:
3794
diff
changeset
|
1188 |
if isPy3: |
b3e5f1288b86
docpy.py & graphdocpy.py: eliminate walk do some fixes
robin
parents:
3794
diff
changeset
|
1189 |
for dirpath, dirnames, filenames in os.walk(path): |
b3e5f1288b86
docpy.py & graphdocpy.py: eliminate walk do some fixes
robin
parents:
3794
diff
changeset
|
1190 |
_packageWalkCallback((builder, opts), dirpath, dirnames + filenames) |
b3e5f1288b86
docpy.py & graphdocpy.py: eliminate walk do some fixes
robin
parents:
3794
diff
changeset
|
1191 |
else: |
b3e5f1288b86
docpy.py & graphdocpy.py: eliminate walk do some fixes
robin
parents:
3794
diff
changeset
|
1192 |
os.path.walk(path, _packageWalkCallback, (builder, opts)) |
2963 | 1193 |
builder.endPackage(name) |
1194 |
os.chdir(cwd) |
|
1195 |
||
1196 |
||
1197 |
def main(): |
|
1198 |
"Handle command-line options and trigger corresponding action." |
|
1199 |
||
1200 |
opts, args = getopt.getopt(sys.argv[1:], 'hsf:m:p:') |
|
1201 |
||
1202 |
# Make an options dictionary that is easier to use. |
|
1203 |
optsDict = {} |
|
1204 |
for k, v in opts: |
|
1205 |
optsDict[k] = v |
|
3326 | 1206 |
hasOpt = optsDict.__contains__ |
2963 | 1207 |
|
1208 |
# On -h print usage and exit immediately. |
|
1209 |
if hasOpt('-h'): |
|
3721 | 1210 |
print(printUsage.__doc__) |
2963 | 1211 |
sys.exit(0) |
1212 |
||
1213 |
# On -s set silent mode. |
|
1214 |
isSilent = hasOpt('-s') |
|
1215 |
||
1216 |
# On -f set the appropriate DocBuilder to use or a default one. |
|
1217 |
builderClassName = optsDict.get('-f', 'Pdf') + 'DocBuilder0' |
|
1218 |
builder = eval(builderClassName + '()') |
|
1219 |
||
1220 |
# Set default module or package to document. |
|
1221 |
if not hasOpt('-p') and not hasOpt('-m'): |
|
1222 |
optsDict['-m'] = 'docpy' |
|
1223 |
||
1224 |
# Save a few options for further use. |
|
1225 |
options = {'isSilent':isSilent} |
|
1226 |
||
1227 |
# Now call the real documentation functions. |
|
1228 |
if hasOpt('-m'): |
|
1229 |
nameOrPath = optsDict['-m'] |
|
1230 |
if not isSilent: |
|
3721 | 1231 |
print("Generating documentation for module %s..." % nameOrPath) |
2963 | 1232 |
builder.begin(name=nameOrPath, typ='module') |
1233 |
documentModule0(nameOrPath, builder, options) |
|
1234 |
elif hasOpt('-p'): |
|
1235 |
nameOrPath = optsDict['-p'] |
|
1236 |
if not isSilent: |
|
3721 | 1237 |
print("Generating documentation for package %s..." % nameOrPath) |
2963 | 1238 |
builder.begin(name=nameOrPath, typ='package') |
1239 |
documentPackage0(nameOrPath, builder, options) |
|
1240 |
builder.end() |
|
1241 |
||
1242 |
if not isSilent: |
|
3721 | 1243 |
print("Saved %s." % builder.outPath) |
2963 | 1244 |
|
1245 |
||
1246 |
if __name__ == '__main__': |
|
1247 |
main() |