| 1 |
"""Attempt to generate templates for module reference with Sphinx |
| 2 |
|
| 3 |
XXX - we exclude extension modules |
| 4 |
|
| 5 |
To include extension modules, first identify them as valid in the |
| 6 |
``_uri2path`` method, then handle them in the ``_parse_module`` script. |
| 7 |
|
| 8 |
We get functions and classes by parsing the text of .py files. |
| 9 |
Alternatively we could import the modules for discovery, and we'd have |
| 10 |
to do that for extension modules. This would involve changing the |
| 11 |
``_parse_module`` method to work via import and introspection, and |
| 12 |
might involve changing ``discover_modules`` (which determines which |
| 13 |
files are modules, and therefore which module URIs will be passed to |
| 14 |
``_parse_module``). |
| 15 |
|
| 16 |
NOTE: this is a modified version of a script originally shipped with the |
| 17 |
PyMVPA project, which we've adapted for NIPY use. PyMVPA is an MIT-licensed |
| 18 |
project.""" |
| 19 |
|
| 20 |
|
| 21 |
# Stdlib imports |
| 22 |
import ast |
| 23 |
import inspect |
| 24 |
import os |
| 25 |
import re |
| 26 |
from importlib import import_module |
| 27 |
from types import SimpleNamespace as Obj |
| 28 |
|
| 29 |
|
| 30 |
class FuncClsScanner(ast.NodeVisitor): |
| 31 |
"""Scan a module for top-level functions and classes. |
| 32 |
|
| 33 |
Skips objects with an @undoc decorator, or a name starting with '_'. |
| 34 |
""" |
| 35 |
def __init__(self): |
| 36 |
ast.NodeVisitor.__init__(self) |
| 37 |
self.classes = [] |
| 38 |
self.classes_seen = set() |
| 39 |
self.functions = [] |
| 40 |
|
| 41 |
@staticmethod |
| 42 |
def has_undoc_decorator(node): |
| 43 |
return any(isinstance(d, ast.Name) and d.id == 'undoc' \ |
| 44 |
for d in node.decorator_list) |
| 45 |
|
| 46 |
def visit_If(self, node): |
| 47 |
if isinstance(node.test, ast.Compare) \ |
| 48 |
and isinstance(node.test.left, ast.Name) \ |
| 49 |
and node.test.left.id == '__name__': |
| 50 |
return # Ignore classes defined in "if __name__ == '__main__':" |
| 51 |
|
| 52 |
self.generic_visit(node) |
| 53 |
|
| 54 |
def visit_FunctionDef(self, node): |
| 55 |
if not (node.name.startswith('_') or self.has_undoc_decorator(node)) \ |
| 56 |
and node.name not in self.functions: |
| 57 |
self.functions.append(node.name) |
| 58 |
|
| 59 |
def visit_ClassDef(self, node): |
| 60 |
if ( |
| 61 |
not (node.name.startswith("_") or self.has_undoc_decorator(node)) |
| 62 |
and node.name not in self.classes_seen |
| 63 |
): |
| 64 |
cls = Obj(name=node.name, sphinx_options={}) |
| 65 |
cls.has_init = any( |
| 66 |
isinstance(n, ast.FunctionDef) and n.name == "__init__" |
| 67 |
for n in node.body |
| 68 |
) |
| 69 |
self.classes.append(cls) |
| 70 |
self.classes_seen.add(node.name) |
| 71 |
|
| 72 |
def scan(self, mod): |
| 73 |
self.visit(mod) |
| 74 |
return self.functions, self.classes |
| 75 |
|
| 76 |
# Functions and classes |
| 77 |
class ApiDocWriter: |
| 78 |
''' Class for automatic detection and parsing of API docs |
| 79 |
to Sphinx-parsable reST format''' |
| 80 |
|
| 81 |
# only separating first two levels |
| 82 |
rst_section_levels = ['*', '=', '-', '~', '^'] |
| 83 |
|
| 84 |
def __init__(self, |
| 85 |
package_name, |
| 86 |
rst_extension='.rst', |
| 87 |
package_skip_patterns=None, |
| 88 |
module_skip_patterns=None, |
| 89 |
names_from__all__=None, |
| 90 |
): |
| 91 |
''' Initialize package for parsing |
| 92 |
|
| 93 |
Parameters |
| 94 |
---------- |
| 95 |
package_name : string |
| 96 |
Name of the top-level package. *package_name* must be the |
| 97 |
name of an importable package |
| 98 |
rst_extension : string, optional |
| 99 |
Extension for reST files, default '.rst' |
| 100 |
package_skip_patterns : None or sequence of {strings, regexps} |
| 101 |
Sequence of strings giving URIs of packages to be excluded |
| 102 |
Operates on the package path, starting at (including) the |
| 103 |
first dot in the package path, after *package_name* - so, |
| 104 |
if *package_name* is ``sphinx``, then ``sphinx.util`` will |
| 105 |
result in ``.util`` being passed for earching by these |
| 106 |
regexps. If is None, gives default. Default is: |
| 107 |
['\\.tests$'] |
| 108 |
module_skip_patterns : None or sequence |
| 109 |
Sequence of strings giving URIs of modules to be excluded |
| 110 |
Operates on the module name including preceding URI path, |
| 111 |
back to the first dot after *package_name*. For example |
| 112 |
``sphinx.util.console`` results in the string to search of |
| 113 |
``.util.console`` |
| 114 |
If is None, gives default. Default is: |
| 115 |
['\\.setup$', '\\._'] |
| 116 |
names_from__all__ : set, optional |
| 117 |
Modules listed in here will be scanned by doing ``from mod import *``, |
| 118 |
rather than finding function and class definitions by scanning the |
| 119 |
AST. This is intended for API modules which expose things defined in |
| 120 |
other files. Modules listed here must define ``__all__`` to avoid |
| 121 |
exposing everything they import. |
| 122 |
''' |
| 123 |
if package_skip_patterns is None: |
| 124 |
package_skip_patterns = ['\\.tests$'] |
| 125 |
if module_skip_patterns is None: |
| 126 |
module_skip_patterns = ['\\.setup$', '\\._'] |
| 127 |
self.package_name = package_name |
| 128 |
self.rst_extension = rst_extension |
| 129 |
self.package_skip_patterns = package_skip_patterns |
| 130 |
self.module_skip_patterns = module_skip_patterns |
| 131 |
self.names_from__all__ = names_from__all__ or set() |
| 132 |
|
| 133 |
def get_package_name(self): |
| 134 |
return self._package_name |
| 135 |
|
| 136 |
def set_package_name(self, package_name): |
| 137 |
''' Set package_name |
| 138 |
|
| 139 |
>>> docwriter = ApiDocWriter('sphinx') |
| 140 |
>>> import sphinx |
| 141 |
>>> docwriter.root_path == sphinx.__path__[0] |
| 142 |
True |
| 143 |
>>> docwriter.package_name = 'docutils' |
| 144 |
>>> import docutils |
| 145 |
>>> docwriter.root_path == docutils.__path__[0] |
| 146 |
True |
| 147 |
''' |
| 148 |
# It's also possible to imagine caching the module parsing here |
| 149 |
self._package_name = package_name |
| 150 |
self.root_module = import_module(package_name) |
| 151 |
self.root_path = self.root_module.__path__[0] |
| 152 |
self.written_modules = None |
| 153 |
|
| 154 |
package_name = property(get_package_name, set_package_name, None, |
| 155 |
'get/set package_name') |
| 156 |
|
| 157 |
def _uri2path(self, uri): |
| 158 |
''' Convert uri to absolute filepath |
| 159 |
|
| 160 |
Parameters |
| 161 |
---------- |
| 162 |
uri : string |
| 163 |
URI of python module to return path for |
| 164 |
|
| 165 |
Returns |
| 166 |
------- |
| 167 |
path : None or string |
| 168 |
Returns None if there is no valid path for this URI |
| 169 |
Otherwise returns absolute file system path for URI |
| 170 |
|
| 171 |
Examples |
| 172 |
-------- |
| 173 |
>>> docwriter = ApiDocWriter('sphinx') |
| 174 |
>>> import sphinx |
| 175 |
>>> modpath = sphinx.__path__[0] |
| 176 |
>>> res = docwriter._uri2path('sphinx.builder') |
| 177 |
>>> res == os.path.join(modpath, 'builder.py') |
| 178 |
True |
| 179 |
>>> res = docwriter._uri2path('sphinx') |
| 180 |
>>> res == os.path.join(modpath, '__init__.py') |
| 181 |
True |
| 182 |
>>> docwriter._uri2path('sphinx.does_not_exist') |
| 183 |
|
| 184 |
''' |
| 185 |
if uri == self.package_name: |
| 186 |
return os.path.join(self.root_path, '__init__.py') |
| 187 |
path = uri.replace('.', os.path.sep) |
| 188 |
path = path.replace(self.package_name + os.path.sep, '') |
| 189 |
path = os.path.join(self.root_path, path) |
| 190 |
# XXX maybe check for extensions as well? |
| 191 |
if os.path.exists(path + '.py'): # file |
| 192 |
path += '.py' |
| 193 |
elif os.path.exists(os.path.join(path, '__init__.py')): |
| 194 |
path = os.path.join(path, '__init__.py') |
| 195 |
else: |
| 196 |
return None |
| 197 |
return path |
| 198 |
|
| 199 |
def _path2uri(self, dirpath): |
| 200 |
''' Convert directory path to uri ''' |
| 201 |
relpath = dirpath.replace(self.root_path, self.package_name) |
| 202 |
if relpath.startswith(os.path.sep): |
| 203 |
relpath = relpath[1:] |
| 204 |
return relpath.replace(os.path.sep, '.') |
| 205 |
|
| 206 |
def _parse_module(self, uri): |
| 207 |
''' Parse module defined in *uri* ''' |
| 208 |
filename = self._uri2path(uri) |
| 209 |
if filename is None: |
| 210 |
# nothing that we could handle here. |
| 211 |
return ([],[]) |
| 212 |
with open(filename, 'rb') as f: |
| 213 |
mod = ast.parse(f.read()) |
| 214 |
return FuncClsScanner().scan(mod) |
| 215 |
|
| 216 |
def _import_funcs_classes(self, uri): |
| 217 |
"""Import * from uri, and separate out functions and classes.""" |
| 218 |
ns = {} |
| 219 |
exec('from %s import *' % uri, ns) |
| 220 |
funcs, classes = [], [] |
| 221 |
for name, obj in ns.items(): |
| 222 |
if inspect.isclass(obj): |
| 223 |
cls = Obj( |
| 224 |
name=name, |
| 225 |
has_init="__init__" in obj.__dict__, |
| 226 |
sphinx_options=getattr(obj, "_sphinx_options", {}), |
| 227 |
) |
| 228 |
classes.append(cls) |
| 229 |
elif inspect.isfunction(obj): |
| 230 |
funcs.append(name) |
| 231 |
|
| 232 |
return sorted(funcs), sorted(classes, key=lambda x: x.name) |
| 233 |
|
| 234 |
def find_funcs_classes(self, uri): |
| 235 |
"""Find the functions and classes defined in the module ``uri``""" |
| 236 |
if uri in self.names_from__all__: |
| 237 |
# For API modules which expose things defined elsewhere, import them |
| 238 |
return self._import_funcs_classes(uri) |
| 239 |
else: |
| 240 |
# For other modules, scan their AST to see what they define |
| 241 |
return self._parse_module(uri) |
| 242 |
|
| 243 |
def generate_api_doc(self, uri): |
| 244 |
'''Make autodoc documentation template string for a module |
| 245 |
|
| 246 |
Parameters |
| 247 |
---------- |
| 248 |
uri : string |
| 249 |
python location of module - e.g 'sphinx.builder' |
| 250 |
|
| 251 |
Returns |
| 252 |
------- |
| 253 |
S : string |
| 254 |
Contents of API doc |
| 255 |
''' |
| 256 |
# get the names of all classes and functions |
| 257 |
functions, classes = self.find_funcs_classes(uri) |
| 258 |
if not len(functions) and not len(classes): |
| 259 |
#print ('WARNING: Empty -', uri) # dbg |
| 260 |
return '' |
| 261 |
|
| 262 |
# Make a shorter version of the uri that omits the package name for |
| 263 |
# titles |
| 264 |
uri_short = re.sub(r'^%s\.' % self.package_name,'',uri) |
| 265 |
|
| 266 |
ad = '.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n' |
| 267 |
|
| 268 |
# Set the chapter title to read 'Module:' for all modules except for the |
| 269 |
# main packages |
| 270 |
if '.' in uri: |
| 271 |
chap_title = 'Module: :mod:`' + uri_short + '`' |
| 272 |
else: |
| 273 |
chap_title = ':mod:`' + uri_short + '`' |
| 274 |
ad += chap_title + '\n' + self.rst_section_levels[1] * len(chap_title) |
| 275 |
|
| 276 |
ad += '\n.. automodule:: ' + uri + '\n' |
| 277 |
ad += '\n.. currentmodule:: ' + uri + '\n' |
| 278 |
|
| 279 |
if classes: |
| 280 |
subhead = str(len(classes)) + (' Classes' if len(classes) > 1 else ' Class') |
| 281 |
ad += '\n'+ subhead + '\n' + \ |
| 282 |
self.rst_section_levels[2] * len(subhead) + '\n' |
| 283 |
|
| 284 |
for c in classes: |
| 285 |
opts = c.sphinx_options |
| 286 |
ad += "\n.. autoclass:: " + c.name + "\n" |
| 287 |
# must NOT exclude from index to keep cross-refs working |
| 288 |
ad += " :members:\n" |
| 289 |
if opts.get("show_inheritance", True): |
| 290 |
ad += " :show-inheritance:\n" |
| 291 |
if opts.get("show_inherited_members", False): |
| 292 |
exclusions_list = opts.get("exclude_inherited_from", []) |
| 293 |
exclusions = ( |
| 294 |
(" " + " ".join(exclusions_list)) if exclusions_list else "" |
| 295 |
) |
| 296 |
ad += f" :inherited-members:{exclusions}\n" |
| 297 |
if c.has_init: |
| 298 |
ad += '\n .. automethod:: __init__\n' |
| 299 |
|
| 300 |
if functions: |
| 301 |
subhead = str(len(functions)) + (' Functions' if len(functions) > 1 else ' Function') |
| 302 |
ad += '\n'+ subhead + '\n' + \ |
| 303 |
self.rst_section_levels[2] * len(subhead) + '\n' |
| 304 |
for f in functions: |
| 305 |
# must NOT exclude from index to keep cross-refs working |
| 306 |
ad += '\n.. autofunction:: ' + uri + '.' + f + '\n\n' |
| 307 |
return ad |
| 308 |
|
| 309 |
def _survives_exclude(self, matchstr, match_type): |
| 310 |
''' Returns True if *matchstr* does not match patterns |
| 311 |
|
| 312 |
``self.package_name`` removed from front of string if present |
| 313 |
|
| 314 |
Examples |
| 315 |
-------- |
| 316 |
>>> dw = ApiDocWriter('sphinx') |
| 317 |
>>> dw._survives_exclude('sphinx.okpkg', 'package') |
| 318 |
True |
| 319 |
>>> dw.package_skip_patterns.append('^\\.badpkg$') |
| 320 |
>>> dw._survives_exclude('sphinx.badpkg', 'package') |
| 321 |
False |
| 322 |
>>> dw._survives_exclude('sphinx.badpkg', 'module') |
| 323 |
True |
| 324 |
>>> dw._survives_exclude('sphinx.badmod', 'module') |
| 325 |
True |
| 326 |
>>> dw.module_skip_patterns.append('^\\.badmod$') |
| 327 |
>>> dw._survives_exclude('sphinx.badmod', 'module') |
| 328 |
False |
| 329 |
''' |
| 330 |
if match_type == 'module': |
| 331 |
patterns = self.module_skip_patterns |
| 332 |
elif match_type == 'package': |
| 333 |
patterns = self.package_skip_patterns |
| 334 |
else: |
| 335 |
raise ValueError('Cannot interpret match type "%s"' |
| 336 |
% match_type) |
| 337 |
# Match to URI without package name |
| 338 |
L = len(self.package_name) |
| 339 |
if matchstr[:L] == self.package_name: |
| 340 |
matchstr = matchstr[L:] |
| 341 |
for pat in patterns: |
| 342 |
try: |
| 343 |
pat.search |
| 344 |
except AttributeError: |
| 345 |
pat = re.compile(pat) |
| 346 |
if pat.search(matchstr): |
| 347 |
return False |
| 348 |
return True |
| 349 |
|
| 350 |
def discover_modules(self): |
| 351 |
''' Return module sequence discovered from ``self.package_name`` |
| 352 |
|
| 353 |
|
| 354 |
Parameters |
| 355 |
---------- |
| 356 |
None |
| 357 |
|
| 358 |
Returns |
| 359 |
------- |
| 360 |
mods : sequence |
| 361 |
Sequence of module names within ``self.package_name`` |
| 362 |
|
| 363 |
Examples |
| 364 |
-------- |
| 365 |
>>> dw = ApiDocWriter('sphinx') |
| 366 |
>>> mods = dw.discover_modules() |
| 367 |
>>> 'sphinx.util' in mods |
| 368 |
True |
| 369 |
>>> dw.package_skip_patterns.append('\\.util$') |
| 370 |
>>> 'sphinx.util' in dw.discover_modules() |
| 371 |
False |
| 372 |
>>> |
| 373 |
''' |
| 374 |
modules = [self.package_name] |
| 375 |
# raw directory parsing |
| 376 |
for dirpath, dirnames, filenames in os.walk(self.root_path): |
| 377 |
# Check directory names for packages |
| 378 |
root_uri = self._path2uri(os.path.join(self.root_path, |
| 379 |
dirpath)) |
| 380 |
for dirname in dirnames[:]: # copy list - we modify inplace |
| 381 |
package_uri = '.'.join((root_uri, dirname)) |
| 382 |
if (self._uri2path(package_uri) and |
| 383 |
self._survives_exclude(package_uri, 'package')): |
| 384 |
modules.append(package_uri) |
| 385 |
else: |
| 386 |
dirnames.remove(dirname) |
| 387 |
# Check filenames for modules |
| 388 |
for filename in filenames: |
| 389 |
module_name = filename[:-3] |
| 390 |
module_uri = '.'.join((root_uri, module_name)) |
| 391 |
if (self._uri2path(module_uri) and |
| 392 |
self._survives_exclude(module_uri, 'module')): |
| 393 |
modules.append(module_uri) |
| 394 |
return sorted(modules) |
| 395 |
|
| 396 |
def write_modules_api(self, modules,outdir): |
| 397 |
# write the list |
| 398 |
written_modules = [] |
| 399 |
for m in modules: |
| 400 |
api_str = self.generate_api_doc(m) |
| 401 |
if not api_str: |
| 402 |
continue |
| 403 |
# write out to file |
| 404 |
outfile = os.path.join(outdir, m + self.rst_extension) |
| 405 |
with open(outfile, "wt", encoding="utf-8") as fileobj: |
| 406 |
fileobj.write(api_str) |
| 407 |
written_modules.append(m) |
| 408 |
self.written_modules = written_modules |
| 409 |
|
| 410 |
def write_api_docs(self, outdir): |
| 411 |
"""Generate API reST files. |
| 412 |
|
| 413 |
Parameters |
| 414 |
---------- |
| 415 |
outdir : string |
| 416 |
Directory name in which to store files |
| 417 |
We create automatic filenames for each module |
| 418 |
|
| 419 |
Returns |
| 420 |
------- |
| 421 |
None |
| 422 |
|
| 423 |
Notes |
| 424 |
----- |
| 425 |
Sets self.written_modules to list of written modules |
| 426 |
""" |
| 427 |
if not os.path.exists(outdir): |
| 428 |
os.mkdir(outdir) |
| 429 |
# compose list of modules |
| 430 |
modules = self.discover_modules() |
| 431 |
self.write_modules_api(modules,outdir) |
| 432 |
|
| 433 |
def write_index(self, outdir, path='gen.rst', relative_to=None): |
| 434 |
"""Make a reST API index file from written files |
| 435 |
|
| 436 |
Parameters |
| 437 |
---------- |
| 438 |
outdir : string |
| 439 |
Directory to which to write generated index file |
| 440 |
path : string |
| 441 |
Filename to write index to |
| 442 |
relative_to : string |
| 443 |
path to which written filenames are relative. This |
| 444 |
component of the written file path will be removed from |
| 445 |
outdir, in the generated index. Default is None, meaning, |
| 446 |
leave path as it is. |
| 447 |
""" |
| 448 |
if self.written_modules is None: |
| 449 |
raise ValueError('No modules written') |
| 450 |
# Get full filename path |
| 451 |
path = os.path.join(outdir, path) |
| 452 |
# Path written into index is relative to rootpath |
| 453 |
if relative_to is not None: |
| 454 |
relpath = outdir.replace(relative_to + os.path.sep, '') |
| 455 |
else: |
| 456 |
relpath = outdir |
| 457 |
with open(path, "wt", encoding="utf-8") as idx: |
| 458 |
w = idx.write |
| 459 |
w('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n') |
| 460 |
w('.. autosummary::\n' |
| 461 |
' :toctree: %s\n\n' % relpath) |
| 462 |
for mod in self.written_modules: |
| 463 |
w(' %s\n' % mod) |