Debian Codegraph @

brian2/sphinxext/generate_reference.py

raw
1 """
2 Automatically generate Brian's reference documentation.
3
4 Based on sphinx-apidoc, published under a BSD license: http://sphinx-doc.org/
5 """
6
7 import inspect
8 import os
9 import sys
10 from os import path
11
12 from .examplefinder import auto_find_examples
13
14 INITPY = "__init__.py"
15
16 OPTIONS = ["show-inheritance"]
17
18
19 def makename(package, module):
20 """Join package and module with a dot."""
21 # Both package and module can be None/empty.
22 if package:
23 name = package
24 if module:
25 name += f".{module}"
26 else:
27 name = module
28 return name
29
30
31 def write_file(name, text, destdir, suffix):
32 """Write the output file for module/package <name>."""
33 fname = path.join(destdir, f"{name}.{suffix}")
34 print(f"Creating file {fname}.")
35 f = open(fname, "w")
36 try:
37 f.write(text)
38 finally:
39 f.close()
40
41
42 def format_heading(level, text):
43 """Create a heading of <level> [1, 2 or 3 supported]."""
44 underlining = ["=", "-", "~"][level - 1] * len(text)
45 return f"{text}\n{underlining}\n\n"
46
47
48 def format_directive(module, destdir, package=None, basename="brian2"):
49 """Create the automodule directive and add the options."""
50 directive = f".. automodule:: {makename(package, module)}\n"
51 for option in OPTIONS:
52 directive += f" :{option}:\n"
53 directive += "\n"
54 # document all the classes in the modules
55 full_name = f"{basename}.{module}"
56 __import__(full_name)
57 mod = sys.modules[full_name]
58 dir_members = dir(mod)
59 classes = []
60 functions = []
61 variables = []
62 for member in dir_members:
63 _temp = __import__(full_name, {}, {}, [member], 0)
64 member_obj = getattr(_temp, member)
65 member_module = getattr(member_obj, "__module__", None)
66 # only document members that where defined in this module
67 if member_module == full_name and not member.startswith("_"):
68 if inspect.isclass(member_obj):
69 classes.append((member, member_obj))
70 elif inspect.isfunction(member_obj):
71 functions.append((member, member_obj))
72 else:
73 variables.append((member, member_obj))
74
75 if classes:
76 directive += "**Classes**\n\n"
77 for member, member_obj in classes:
78 directive += f".. autosummary:: {member}\n"
79 directive += " :toctree:\n\n"
80 create_member_file(full_name, member, member_obj, destdir)
81 if functions:
82 directive += "**Functions**\n\n"
83 for member, member_obj in functions:
84 directive += f".. autosummary:: {member}\n"
85 directive += " :toctree:\n\n"
86 create_member_file(full_name, member, member_obj, destdir)
87 if variables:
88 directive += "**Objects**\n\n"
89 for member, member_obj in variables:
90 directive += f".. autosummary:: {member}\n"
91 directive += " :toctree:\n\n"
92 create_member_file(full_name, member, member_obj, destdir)
93
94 return directive
95
96
97 def find_shortest_import(module_name, obj_name):
98 parts = module_name.split(".")
99 for idx in range(1, len(parts) + 1):
100 try:
101 result = __import__(
102 ".".join(parts[:idx]), globals(), {}, fromlist=[str(obj_name)], level=0
103 )
104 result_obj = getattr(result, obj_name, None)
105 if (
106 result_obj is not None
107 and getattr(result_obj, "__module__", None) == module_name
108 ):
109 # import seems to have worked
110 return ".".join(parts[:idx])
111 except ImportError:
112 pass
113 raise AssertionError(f"Couldn't import {module_name}.{obj_name}")
114
115
116 def create_member_file(module_name, member, member_obj, destdir, suffix="rst"):
117 """Build the text of the file and write the file."""
118
119 text = f".. currentmodule:: {module_name}\n\n"
120
121 shortest_import = find_shortest_import(module_name, member)
122 import_text = f"(*Shortest import*: ``from {shortest_import} import {member})``\n\n"
123 if inspect.isclass(member_obj):
124 text += format_heading(1, f"{member} class")
125 text += import_text
126 text += f".. autoclass:: {member}\n\n"
127 text += auto_find_examples(member_obj, headersymbol="-")
128 elif inspect.isfunction(member_obj):
129 text += format_heading(1, f"{member} function")
130 text += import_text
131 text += f".. autofunction:: {member}\n\n"
132 else:
133 text += format_heading(1, f"{member} object")
134 text += import_text
135 text += f".. autodata:: {member}\n"
136
137 write_file(makename(module_name, member), text, destdir, suffix)
138
139
140 def create_package_file(
141 root, master_package, subroot, py_files, subs, destdir, excludes, suffix="rst"
142 ):
143 """Build the text of the file and write the file."""
144 package = path.split(root)[-1]
145 text = format_heading(1, f"{package} package")
146 # add each module in the package
147 for py_file in py_files:
148 if shall_skip(path.join(root, py_file)):
149 continue
150 is_package = py_file == INITPY
151 py_file = path.splitext(py_file)[0]
152 py_path = makename(subroot, py_file)
153 # we don't want an additional header for the package,
154 if not is_package:
155 heading = f":mod:`{py_file}` module"
156 text += format_heading(2, heading)
157 text += format_directive(
158 is_package and subroot or py_path, destdir, master_package
159 )
160 text += "\n"
161
162 # build a list of directories that are packages (contain an INITPY file)
163 subs = [sub for sub in subs if path.isfile(path.join(root, sub, INITPY))]
164 # if there are some package directories, add a TOC for theses subpackages
165 if subs:
166 text += format_heading(2, "Subpackages")
167 text += ".. toctree::\n"
168 text += " :maxdepth: 2\n\n"
169 for sub in subs:
170 if not is_excluded(os.path.join(root, sub), excludes):
171 text += f" {makename(master_package, subroot)}.{sub}\n"
172 text += "\n"
173
174 write_file(makename(master_package, subroot), text, destdir, suffix)
175
176
177 def shall_skip(module):
178 """Check if we want to skip this module."""
179 # skip it if there is nothing (or just \n or \r\n) in the file
180 return path.getsize(module) <= 2
181
182
183 def recurse_tree(rootpath, exclude_dirs, exclude_files, destdir):
184 """
185 Look for every file in the directory tree and create the corresponding
186 ReST files.
187 """
188 # use absolute path for root, as relative paths like '../../foo' cause
189 # 'if "/." in root ...' to filter out *all* modules otherwise
190 rootpath = path.normpath(path.abspath(rootpath))
191 # check if the base directory is a package and get its name
192 if INITPY in os.listdir(rootpath):
193 root_package = rootpath.split(path.sep)[-1]
194 else:
195 # otherwise, the base is a directory with packages
196 root_package = None
197
198 toplevels = []
199 for root, subs, files in os.walk(rootpath):
200 if is_excluded(root, exclude_dirs):
201 del subs[:]
202 continue
203 # document only Python module files
204 py_files = sorted(
205 [
206 f
207 for f in files
208 if (path.splitext(f)[1] == ".py" and f not in exclude_files)
209 ]
210 )
211 is_pkg = INITPY in py_files
212 if is_pkg:
213 py_files.remove(INITPY)
214 py_files.insert(0, INITPY)
215 elif root != rootpath:
216 # only accept non-package at toplevel
217 del subs[:]
218 continue
219 # remove hidden ('.') and private ('_') directories
220 subs[:] = sorted(sub for sub in subs if sub[0] not in [".", "_"])
221
222 if is_pkg:
223 # we are in a package with something to document
224 if subs or len(py_files) > 1 or not shall_skip(path.join(root, INITPY)):
225 subpackage = (
226 root[len(rootpath) :].lstrip(path.sep).replace(path.sep, ".")
227 )
228 create_package_file(
229 root,
230 root_package,
231 subpackage,
232 py_files,
233 subs,
234 destdir,
235 exclude_dirs,
236 )
237 toplevels.append(makename(root_package, subpackage))
238 else:
239 raise AssertionError("Expected it to be a package")
240
241 return toplevels
242
243
244 def normalize_excludes(rootpath, excludes):
245 """
246 Normalize the excluded directory list:
247 * must be either an absolute path or start with rootpath,
248 * otherwise it is joined with rootpath
249 * with trailing slash
250 """
251 f_excludes = []
252 for exclude in excludes:
253 if not path.isabs(exclude) and not exclude.startswith(rootpath):
254 exclude = path.join(rootpath, exclude)
255 f_excludes.append(path.normpath(exclude) + path.sep)
256 return f_excludes
257
258
259 def is_excluded(root, excludes):
260 """
261 Check if the directory is in the exclude list.
262
263 Note: by having trailing slashes, we avoid common prefix issues, like
264 e.g. an exlude "foo" also accidentally excluding "foobar".
265 """
266 sep = path.sep
267 if not root.endswith(sep):
268 root += sep
269 for exclude in excludes:
270 if root.startswith(exclude):
271 return True
272 return False
273
274
275 def main(rootpath, exclude_dirs, exclude_files, destdir):
276 if not os.path.exists(destdir):
277 os.makedirs(destdir)
278
279 exclude_dirs = normalize_excludes(rootpath, exclude_dirs)
280 recurse_tree(rootpath, exclude_dirs, exclude_files, destdir)