Debian Codegraph @

brian2/sphinxext/generate_examples.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import fnmatch
2 import glob
3 import os
4 import shutil
5 from collections import defaultdict
6
7
8 class GlobDirectoryWalker:
9 # a forward iterator that traverses a directory tree
10
11 def __init__(self, directory, pattern="*"):
12 self.stack = [directory]
13 self.pattern = pattern
14 self.files = []
15 self.index = 0
16
17 def __getitem__(self, index):
18 while True:
19 try:
20 file = self.files[self.index]
21 self.index = self.index + 1
22 except IndexError:
23 # pop next directory from stack
24 self.directory = self.stack.pop()
25 if os.path.isdir(self.directory):
26 self.files = os.listdir(self.directory)
27 else:
28 self.files = []
29 self.index = 0
30 else:
31 # got a filename
32 fullname = os.path.join(self.directory, file)
33 if os.path.isdir(fullname) and not os.path.islink(fullname):
34 self.stack.append(fullname)
35 if fnmatch.fnmatch(file, self.pattern):
36 return fullname
37
38
39 def main(rootpath, destdir):
40 if not os.path.exists(destdir):
41 shutil.os.makedirs(destdir)
42
43 examplesfnames = [fname for fname in GlobDirectoryWalker(rootpath, "*.py")]
44 allowed_additional_file_extensions = [".rst", ".md", ".txt", ".mplstyle"]
45 additional_files = [
46 fname
47 for fname in GlobDirectoryWalker(rootpath, "*.*")
48 if os.path.splitext(fname)[1] in allowed_additional_file_extensions
49 ]
50
51 data_file_extensions = [".npy"]
52 data_files = [
53 fname
54 for fname in GlobDirectoryWalker(rootpath, "*.*")
55 if os.path.splitext(fname)[1] in data_file_extensions
56 ]
57
58 print(f"Documenting {len(examplesfnames)} examples")
59 print(f"Documenting {len(additional_files)} additional files")
60 print(f"Documenting {len(data_files)} data files")
61
62 examplespaths = []
63 examplesbasenames = []
64 relativepaths = []
65 outnames = []
66 for f in examplesfnames:
67 path, file = os.path.split(f)
68 relpath = os.path.relpath(path, rootpath)
69 if relpath == ".":
70 relpath = ""
71 path = os.path.normpath(path)
72 filebase, ext = os.path.splitext(file)
73 exname = filebase
74 if relpath:
75 exname = relpath.replace("/", ".").replace("\\", ".") + "." + exname
76 examplespaths.append(path)
77 examplesbasenames.append(filebase)
78 relativepaths.append(relpath)
79 outnames.append(exname)
80 # We assume all files are encoded as UTF-8
81 examplescode = []
82 for fname in examplesfnames:
83 with open(fname, encoding="utf-8") as f:
84 examplescode.append(f.read())
85 examplesdocs = []
86 examplesafterdoccode = []
87 for code in examplescode:
88 codesplit = code.split("\n")
89 comment_lines = 0
90 for line in codesplit:
91 if line.startswith("#") or len(line) == 0:
92 comment_lines += 1
93 else:
94 break
95 codesplit = codesplit[comment_lines:]
96 readingdoc = False
97 doc = []
98 afterdoccode = ""
99 for i in range(len(codesplit)):
100 stripped = codesplit[i].strip()
101 if stripped[:3] == '"""' or stripped[:3] == "'''":
102 if not readingdoc:
103 readingdoc = True
104 else:
105 afterdoccode = "\n".join(codesplit[i + 1 :])
106 break
107 elif readingdoc:
108 doc.append(codesplit[i])
109 else: # No doc
110 afterdoccode = "\n".join(codesplit[i:])
111 break
112 examplesdocs.append("\n".join(doc))
113 examplesafterdoccode.append(afterdoccode)
114
115 categories = defaultdict(list)
116 examples = zip(
117 examplesfnames,
118 examplespaths,
119 examplesbasenames,
120 examplescode,
121 examplesdocs,
122 examplesafterdoccode,
123 relativepaths,
124 outnames,
125 strict=True,
126 )
127 # Get the path relative to the examples director (not relative to the
128 # directory where this file is installed
129 if "BRIAN2_DOCS_EXAMPLE_DIR" in os.environ:
130 rootdir = os.environ["BRIAN2_DOCS_EXAMPLE_DIR"]
131 else:
132 rootdir, _ = os.path.split(__file__)
133 rootdir = os.path.normpath(os.path.join(rootdir, "../../examples"))
134 eximgpath = os.path.abspath(
135 os.path.join(rootdir, "../docs_sphinx/resources/examples_images")
136 )
137 print("Searching for example images in directory", eximgpath)
138 for _fname, _path, basename, _code, docs, afterdoccode, relpath, exname in examples:
139 categories[relpath].append((exname, basename))
140 title = "Example: " + basename
141 output = ".. currentmodule:: brian2\n\n"
142 output += ".. " + basename + ":\n\n"
143 output += title + "\n" + "=" * len(title) + "\n\n"
144 note = f"""
145 .. only:: html
146
147 .. |launchbinder| image:: http://mybinder.org/badge.svg
148 .. _launchbinder: https://mybinder.org/v2/gh/brian-team/brian2-binder/master?filepath=examples/{exname.replace(".", "/")}.ipynb
149
150 .. note::
151 You can launch an interactive, editable version of this
152 example without installing any local files
153 using the Binder service (although note that at some times this
154 may be slow or fail to open): |launchbinder|_
155
156 """
157 output += note + "\n\n"
158 output += docs + "\n\n::\n\n"
159 output += "\n".join([" " + line for line in afterdoccode.split("\n")])
160 output += "\n\n"
161
162 eximgpattern = os.path.join(eximgpath, f"{exname}.*")
163 images = glob.glob(eximgpattern + ".png") + glob.glob(eximgpattern + ".gif")
164 for image in sorted(images):
165 _, image = os.path.split(image)
166 print("Found example image file", image)
167 output += f".. image:: ../resources/examples_images/{image}\n\n"
168
169 with open(os.path.join(destdir, exname + ".rst"), "w", encoding="utf-8") as f:
170 f.write(output)
171
172 category_additional_files = defaultdict(list)
173 for fname in additional_files:
174 path, file = os.path.split(fname)
175 relpath = os.path.relpath(path, rootpath)
176 if relpath == ".":
177 relpath = ""
178 full_name = relpath.replace("/", ".").replace("\\", ".") + "." + file + ".rst"
179 category_additional_files[relpath].append((file, full_name))
180 with open(fname, encoding="utf-8") as f:
181 content = f.read()
182 output = file + "\n" + "=" * len(file) + "\n\n"
183 output += ".. code-block:: none\n\n"
184 content_lines = ["\t" + line for line in content.split("\n")]
185 output += "\n".join(content_lines)
186 output += "\n\n"
187 with open(os.path.join(destdir, full_name), "w", encoding="utf-8") as f:
188 f.write(output)
189
190 category_data_files = defaultdict(list)
191 for fname in data_files:
192 path, file = os.path.split(fname)
193 relpath = os.path.relpath(path, rootpath)
194 if relpath == ".":
195 relpath = ""
196 full_name = relpath.replace("/", ".").replace("\\", ".") + "." + file + ".rst"
197 category_data_files[relpath].append((file, full_name))
198 output = file + "\n" + "=" * len(file) + "\n\n"
199 output += (
200 "Download:"
201 f" :download:`{file} <{os.path.join('/../examples/', relpath, file)}>`\n\n"
202 )
203 with open(os.path.join(destdir, full_name), "w", encoding="utf-8") as f:
204 f.write(output)
205
206 mainpage_text = "Examples\n"
207 mainpage_text += "========\n\n"
208
209 def insert_category(category, mainpage_text):
210 if category:
211 label = category.lower().replace(" ", "-").replace("/", ".")
212 mainpage_text += f"\n.. _{label}:\n\n"
213 mainpage_text += "\n" + category + "\n" + "-" * len(category) + "\n\n"
214 mainpage_text += ".. toctree::\n"
215 mainpage_text += " :maxdepth: 1\n\n"
216 for exname, basename in sorted(categories[category]):
217 mainpage_text += f" {basename} <{exname}>\n"
218 for fname, full_name in sorted(category_additional_files[category]):
219 mainpage_text += f" {fname} <{full_name}>\n"
220 for fname, full_name in sorted(category_data_files[category]):
221 mainpage_text += f" {fname} <{full_name}>\n"
222 return mainpage_text
223
224 mainpage_text = insert_category("", mainpage_text)
225 for category in sorted(categories.keys()):
226 if category:
227 mainpage_text = insert_category(category, mainpage_text)
228
229 with open(os.path.join(destdir, "index.rst"), "w") as f:
230 f.write(mainpage_text)
231
232
233 if __name__ == "__main__":
234 main("../../examples", "../../docs_sphinx/examples")