-
Notifications
You must be signed in to change notification settings - Fork 8
/
autogen.py
58 lines (45 loc) · 1.83 KB
/
autogen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import os
import pathlib
import six
# From https://github.com/keras-team/keras/blob/0a0ac3fa5462cf4a72636ca4498a0a82ac91fc32/docs/autogen.py
def get_module_docstring(filepath):
"""Extract the module docstring.
Also finds the line at which the docstring ends.
"""
co = compile(open(filepath, encoding="utf-8").read(), filepath, "exec")
if co.co_consts and isinstance(co.co_consts[0], six.string_types):
docstring = co.co_consts[0]
else:
print("Could not get the docstring from " + filepath)
docstring = ""
return docstring, co.co_firstlineno
def copy_examples(examples_dir, destination_dir):
"""Copy the examples directory in the documentation.
Prettify files by extracting the docstrings written in Markdown.
"""
pathlib.Path(destination_dir).mkdir(exist_ok=True)
for file in os.listdir(examples_dir):
if not file.endswith(".py"):
continue
module_path = os.path.join(examples_dir, file)
docstring, starting_line = get_module_docstring(module_path)
destination_file = os.path.join(destination_dir, file[:-2] + "md")
with open(destination_file, "w+", encoding="utf-8") as f_out, open(
os.path.join(examples_dir, file), "r+", encoding="utf-8"
) as f_in:
f_out.write(docstring + "\n\n")
# skip docstring
for _ in range(starting_line):
next(f_in)
f_out.write("```python\n")
# next line might be empty.
line = next(f_in)
if line != "\n":
f_out.write(line)
# copy the rest of the file.
for line in f_in:
f_out.write(line)
f_out.write("```")
if __name__ == "__main__":
print(os.getcwd())
copy_examples("./docs/examples", "./_build/pydocmd/examples")