-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
regenerate_readme.py
265 lines (212 loc) · 8.11 KB
/
regenerate_readme.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import sys
import ast
import argparse
import inspect
from textwrap import dedent
from typing import Any
from contextlib import contextmanager
from string import whitespace
import re
import logging
logger = logging.getLogger(__name__)
class MyVisitor(ast.NodeVisitor):
def __init__(self, source: str):
super().__init__()
self.source = source
# Line number counting in ast starts at 1
self.source_lines = [""] + source.splitlines(keepends=False)
self.stack = []
self.section_chars = '#*=-^"' + '"' * 1000
self.flair_pattern = r"^\|[a-zA-Z_-]+\|$"
self.all_filter = []
@property
def depth(self):
return len(self.stack)
@contextmanager
def stacker(self, node):
self.stack.append(node)
try:
yield
finally:
self.stack.pop()
def make_titletext(self, text, prefix="", suffix="") -> str:
text = prefix + text + suffix
underline_len = len(text.encode())
return "\n" + text + "\n" + self.section_chars[self.depth] * underline_len
def dig(self, node):
with self.stacker(node):
super().generic_visit(node)
def text_from_node_to_before_body(self, node) -> str:
# text = ' '.join(self.source_lines[node.lineno:node.body[0].lineno])
lines = self.source_lines[node.lineno : node.body[0].lineno]
lines = map(str.strip, lines)
lines = [re.sub(r",$", ", ", line) for line in lines]
text = "".join(lines)
return text.strip(whitespace + ":")
def generic_visit(self, node: ast.AST) -> Any:
logger.info(" " * 4 * len(self.stack) + "visited %s", node)
self.dig(node)
def visit_Module(self, node: ast.Module) -> Any:
logger.info("visited module", node)
self.dig(node)
def stack_contains_a_function_before_a_class(self) -> False:
for node in reversed(self.stack):
if isinstance(node, ast.ClassDef):
return False
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
return True
else:
return False
def scoop_flair_items_from_first_body_expr(self, node):
# Extract flair tags out of docstring. Note: we don't print out the
# docstring here, that will be left to the ``visit_Expr`` method.
# We just want the flair so that the title can be modified
docstring = ast.get_docstring(node)
flair_items = []
if docstring:
flair_items = re.findall(self.flair_pattern, docstring, flags=re.MULTILINE)
flair_text = " ".join(flair_items) + (" " if flair_items else "")
return flair_text
def visit_FunctionDef(self, node: ast.FunctionDef) -> Any:
if self.stack_contains_a_function_before_a_class():
# No documentation for nested functions
return
if node.name.startswith("_"):
return
if self.depth == 1 and node.name not in self.all_filter:
return
text = self.text_from_node_to_before_body(node)
text = re.sub(r"^def ", "", text)
anchor_text = node.name
if isinstance(self.stack[-1], ast.ClassDef):
class_name = self.stack[-1].name
text = f"{class_name}.{text}"
anchor_text = f"{class_name}.{anchor_text}"
decs = ""
if node.decorator_list:
logger.info(node.decorator_list)
decs = (
" ".join(
"@" + n.name if hasattr(n, "name") else "@" + n.id
for n in node.decorator_list
)
+ " "
)
text = decs + text
flair_text = self.scoop_flair_items_from_first_body_expr(node)
text = flair_text + "``" + text + "``"
print()
print(f".. _{anchor_text}:")
print()
print(self.make_titletext(text))
# Recurse
self.dig(node)
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> Any:
logger.info("visited async function %s", node)
self.visit_FunctionDef(node)
self.dig(node)
def visit_ClassDef(self, node: ast.ClassDef) -> Any:
if node.name.startswith("_"):
return
if self.depth == 1 and node.name not in self.all_filter:
return
anchor_text = node.name
print()
print(f".. _{anchor_text}:")
print()
text = self.text_from_node_to_before_body(node)
flair_text = self.scoop_flair_items_from_first_body_expr(node)
text = flair_text + "``" + text + "``"
print(self.make_titletext(text))
self.dig(node)
def visit_Expr(self, node: ast.Expr) -> Any:
"""Handles docstrings and any other strings that might just appear
in various places."""
is_constant_str = isinstance(node.value, ast.Constant) and isinstance(
node.value.value, str
)
if not is_constant_str:
return
# First line might have different indentation!
first_line, _, other_lines = node.value.value.partition("\n")
text = first_line.strip() + "\n" + dedent(other_lines)
text = re.sub(self.flair_pattern, "", text, flags=re.MULTILINE)
# Replace doctest notifiers
tokens = ["<BLANKLINE>", "# doctest: +SKIP", "# doctest: +ELLIPSIS"]
for t in tokens:
text = text.replace(t, " " * len(t))
print(text)
def visit_Assign(self, node: ast.Assign) -> Any:
"""This is only used to collect the __all__ values to filter
the output for those."""
if not hasattr(node.targets[0], "id"):
return
if node.targets[0].id != "__all__":
return
self.all_filter = [n.value for n in node.value.elts]
def main(args):
file_contents = open(args.module).read()
mod = ast.parse(file_contents, filename=args.module)
visitor = MyVisitor(file_contents)
visitor.visit(mod)
def make_titletext(name, element, level, prefix=""):
section_chars = '#*=-^"'
if inspect.isclass(element):
text = f"class {name}"
elif inspect.ismethod(element):
# class methods
sig = inspect.signature(element)
text = f"*classmethod* ``{element.__qualname__}{sig}``"
elif inspect.isfunction(element):
# class methods
sig = inspect.signature(element)
text = f"``{element.__qualname__}{sig}``"
else:
try:
sig = inspect.signature(element)
text = f"``{element.__qualname__}{sig}``"
except (ValueError, TypeError):
text = name
if prefix:
text = prefix + text
underline_len = len(text.encode())
return "\n" + text + "\n" + section_chars[level] * underline_len
def parse(node, level=0, include_names=None):
def elems_by_appearance(node):
if node.__name__ == "type":
return
def line_number(node):
try:
return inspect.getsourcelines(node)[1]
except TypeError:
return 0
def subnodes(node):
for n in dir(node):
try:
yield getattr(node, n)
except AttributeError:
continue
yield from sorted(subnodes(node), key=line_number)
for element in elems_by_appearance(node):
try:
name = element.__name__
except AttributeError:
continue
if name.startswith("_"):
continue
allow_emit = level != 1 or (
not include_names or element.__name__ in include_names
)
if allow_emit:
yield name, element, level
if hasattr(element, "__doc__"):
print(name, "hasdoc")
if inspect.isclass(element):
yield from parse(element, level + 1)
if __name__ == "__main__":
logging.basicConfig(level="WARNING", stream=sys.stderr)
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--module", help="Module name to document")
parser.add_argument("-a", "--all", help="Only document entries in __all__")
args = parser.parse_args()
main(args)