/
doc_hack.py
226 lines (194 loc) · 8.95 KB
/
doc_hack.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
# coding=utf-8
import os
import re
# noinspection PyUnresolvedReferences
from herring.herring_app import task, namespace, task_execute
from herringlib.simple_logger import info, debug
from herringlib.project_settings import Project
from herringlib.safe_edit import safe_edit
with namespace('doc'):
@task()
def hack():
"""hack the RST files generated by apidoc"""
exclude_from_inheritance_diagrams = getattr(Project, 'exclude_from_inheritance_diagrams', None)
_customize_doc_src_files(exclude=exclude_from_inheritance_diagrams)
def _customize_doc_src_files(exclude=None):
"""change the auto-api generated sphinx src files to be more what we want"""
for root, dirs, files in os.walk(os.path.join(Project.docs_dir, '_src')):
for file_name in files:
if file_name != 'modules.rst':
# noinspection PyBroadException
try:
SourceFile(os.path.join(root, file_name)).hack(exclude=exclude)
except:
pass
# ignore dot sub-directories ('.*') (mainly for skipping .svn directories)
for name in dirs:
if name.startswith('.'):
dirs.remove(name)
# noinspection PyMethodMayBeStatic
class SourceFile(object):
"""
autodoc generates:
:mod:`ArgumentServiceTest` Module
---------------------------------
.. automodule:: util.unittests.ArgumentServiceTest
need to add package path from automodule line to module name in mod line.
"""
def __init__(self, file_name):
self.file_name = file_name
# build dict from automodule lines where key is base name, value is full name
self.name_dict = self._name_dict(file_name)
self.module_name = os.path.splitext(os.path.basename(file_name))[0]
self.line_length = 0
self.package = False
self.class_name = ''
def hack(self, exclude=None):
"""
substitute full names into mod lines with base names.
:param exclude: list of files to exclude from generating inheritance diagrams
:type exclude: list(str)
"""
if os.path.splitext(self.file_name)[1] != '.rst':
return
if exclude is None:
exclude = []
with safe_edit(self.file_name) as files:
in_file = files['in']
out_file = files['out']
info("Editing %s" % self.file_name)
self.line_length = 0
self.package = False
self.class_name = ''
headers_to_remove = ['Subpackages', 'Submodules', 'Module contents']
out_file.write(".. include:: ../icons.rst")
out_file.write("\n\n")
delete_next_line = False
for line in in_file.readlines():
if delete_next_line and line.startswith('---'):
info("removing " + line.strip())
delete_next_line = False
continue
delete_next_line = False
line = self._hack_mod(line)
line = self._hack_package(line)
line = self._hack_module(line)
line = self._hack_init(line)
line = self._hack_underline(line)
line = self._hack_members(line)
if line.strip() in headers_to_remove:
info("removing " + line.strip())
delete_next_line = True
continue
out_file.write(line)
out_file.write("\n\n")
# title = "%s Inheritance Diagrams" % self.module_name
# out_file.write("%s\n" % title)
# out_file.write('-' * len(title) + "\n\n")
for value in sorted(self.name_dict.values()):
if value not in exclude:
out_file.write(".. inheritance-diagram:: %s\n" % value)
out_file.write("\n\n")
def _hack_mod(self, line):
match = re.match(r':mod:`(.+)`(.*)', line)
if match:
debug("matched :mod:")
key = match.group(1)
if key in self.name_dict:
value = self.name_dict[key]
line = ''.join(":mod:`%s`%s\n" % (value, match.group(2)))
self.line_length = len(line)
self.package = re.search(r':mod:.+Package', line)
self.class_name = key
return line
def _hack_package(self, line):
match = re.match(r'(.+)\s+package\s*', line)
if match:
debug("matched package")
line = '|package| ' + match.group(1)
self.line_length = len(line)
line += '\n'
return line
def _hack_module(self, line):
match = re.match(r'(.+)\s+module\s*', line)
if match:
debug("matched module")
self.package = False
self.class_name = match.group(1).split('.')[-1]
line = '|module| ' + match.group(1)
self.line_length = len(line)
line += '\n'
return line
def _hack_init(self, line):
match = re.match(r'Module contents', line)
if match:
self.package = True
self.class_name = '__init__'
return line
def _hack_underline(self, line):
if re.match(r'[=\-\.][=\-\.][=\-\.]+', line):
debug("matched [=\-\.][=\-\.][=\-\.]+")
if self.line_length > 0:
line = "%s\n" % (line[0] * self.line_length)
if self.package:
line += self._package_line(self.module_name)
if self.class_name:
line += self._class_line(self.module_name, self.class_name)
return line
# noinspection PyMethodMayBeStatic
def _hack_members(self, line):
match = re.match(r'\s*:members:', line)
if match:
line += " :special-members:\n"
line += " :exclude-members: __dict__,__weakref__,__module__\n"
return line
def _name_dict(self, file_name):
"""extract the name dictionary from the automodule lines in the sphinx src file"""
name_dict = {}
# noinspection PyArgumentEqualDefault
with open(file_name, 'r') as in_file:
for line in in_file.readlines():
match = re.match(r'.. automodule:: (\S+)', line)
if match:
value = match.group(1)
key = value.split('.')[-1]
if '__init__' not in value:
name_dict[key] = value
return name_dict
def _package_line(self, module_name):
"""create the package figure lines for the given module"""
info("_package_line(%s)" % module_name)
line = ''
package_image = "uml/packages_{name}.svg".format(name=module_name.split('.')[-1])
classes_image = "uml/classes_{name}.svg".format(name=module_name.split('.')[-1])
image_path = os.path.join(Project.docs_dir, '_src', package_image)
if os.path.exists(image_path):
info("adding figure %s" % image_path)
line += "\n.. figure:: {image}\n :width: 1100 px\n\n {name} Packages\n\n".format(
image=package_image,
name=module_name)
line += "\n.. figure:: {image}\n\n {name} Classes\n\n".format(
image=classes_image,
name=module_name)
else:
debug("%s does not exist!" % image_path)
return line
def _class_line(self, module_name, class_name):
"""create the class figure lines for the given module and class"""
info("_class_line(%s, %s)" % (module_name, class_name))
line = ''
classes_images = [
"uml/classes_{module}.{name}.png".format(module=module_name, name=class_name),
"uml/classes_{module}.png".format(module=module_name),
]
for classes_image in classes_images:
image_path = os.path.join(Project.docs_dir, '_src', classes_image)
if os.path.exists(image_path):
info("adding figure %s" % image_path)
line += "\n.. figure:: {image}\n\n {name} Class\n\n".format(
image=classes_image,
name=class_name)
break
else:
debug("%s does not exist!" % image_path)
return line