Debian Codegraph @

cloud_sptheme/ext/autodoc_sections.py

raw symbols SCIP
1 """cloud_sptheme.ext.autodoc_sections - support ReST sections in docstrings"""
2 #=============================================================================
3 # imports
4 #=============================================================================
5 # core
6 import inspect
7 import re
8 import logging; log = logging.getLogger(__name__)
9 # site
10 # pkg
11 from cloud_sptheme import __version__
12 from cloud_sptheme.utils import u, patchapplier, monkeypatch
13 # local
14 __all__ = [
15 "setup",
16 ]
17
18 #=============================================================================
19 # internal helpers used for hacking up sphinx. almost ashamed to be doing this.
20 #=============================================================================
21 def get_caller_value(module, var, rtype=None, code=None):
22 """
23 helper which looks for nearest ancestor in call stack
24 which occurred in module, and return specified local variable.
25
26 :param module:
27 name of module to look for on stack
28
29 :param var:
30 name of local variable to return
31
32 :param rtype:
33 do optional type-check to ensure **name** has expected type.
34
35 :param code:
36 optionally match based on function name (``frame.f_code.co_name``)
37 as well as module.
38 """
39 frame = None
40 try:
41 frame = inspect.currentframe().f_back
42 while True:
43 if ((frame.f_globals.get("__name__") == module) and
44 (not code or frame.f_code.co_name == code)):
45 break
46 frame = frame.f_back
47 if not frame:
48 raise RuntimeError("couldn't find module=%r, code=%r in call stack" %
49 (module, code or '<any>'))
50 value = frame.f_locals[var]
51 if rtype and not isinstance(value, rtype):
52 raise TypeError("%s: expected a %r instance: %r" % (var, rtype, value))
53 return value
54 finally:
55 frame = None
56
57 #=============================================================================
58 # autodoc monkeypatches / hacks
59 #=============================================================================
60 @patchapplier
61 def _patch_sphinx():
62 """
63 helper which monkeypatches sphinx to install some of our hooks.
64 """
65
66 #----------------------------------------------------------------------
67 # patch document.note_implicit_target() to look for _modify_new_desc_section
68 # attribute, as signal that it should munge up node that's passed to it,
69 # to represent new description-level section, rather than document-level section.
70 # this flag is then set by RSTState.new_subsection() patch, below.
71 # NOTE: ideally, all this action could be done by a hook w/in
72 # RSTState.new_subsection(), but would have to modify source.
73 #----------------------------------------------------------------------
74 from docutils.nodes import document, make_id
75
76 @monkeypatch(document)
77 def note_implicit_target(_wrapped, self, target, *args, **kwds):
78 # use default behavior unless signal flag is set
79 entry = self._modify_new_desc_section
80 if not entry:
81 return _wrapped(self, target, *args, **kwds)
82 self._modify_new_desc_section = None
83
84 # NOTE: target should be section() node we're modifying,
85 # as we just got called from RSTState.new_subsection(),
86 # which is what sets modify_new_desc_section flag.
87 # 'entry' should be last item in memo.desc_stack
88 # (see below).
89
90 # add our custom css classes for styling
91 # NOTE: adding 'section-header' class to H<N> node,
92 # so that our css rules don't have to be duplicated for every H<N> value.
93 target['classes'].append("desc-section")
94 target['classes'].append("desc-section-%d" % entry['level'])
95 target[0]['classes'].append("section-header")
96
97 # for duration of call, modify settings.id_prefix to include
98 # decription prefix in any auto-generated ids. this helpers
99 # section names remaining unique even if used between classes
100 # (e.g. common names such as 'Constructor Options')
101 settings = self.settings
102 orig = settings.id_prefix
103 try:
104 if entry['prefix']:
105 if orig:
106 settings.id_prefix = u("%s-%s") % (settings.id_prefix, entry['prefix'])
107 else:
108 settings.id_prefix = entry['prefix']
109 return _wrapped(self, target, *args, **kwds)
110 finally:
111 settings.id_prefix = orig
112
113 document._modify_new_desc_section = None
114
115 #----------------------------------------------------------------------
116 # patch RSTState.new_subsection() to generate sections nested within
117 # a description. It reads ``memo.desc_stack`` to determine if it's within
118 # a description. If set, this attr should be a list of dicts,
119 # each entry representing a nested description (e.g. an ObjectDescription)
120 # whose content is being parsed, most recent should be last.
121 # Each entry should be a dict containing:
122 #
123 # If there are no description entries active, the normal behavior is used.
124 #
125 # Each dict should contain the following keys:
126 # * prefix -- None, or string to use as prefix for section identifiers.
127 # helps keep links unique w/in document.
128 # * signode -- signature node used to generate prefix (for debugging)
129 # * owner -- arbitary object (ObjectDescription in our case)
130 # which added this entry to list. intended as sanity check
131 # when popping entries back off stack.
132 # * level -- section level w/in declaration (autoset by code below)
133 #----------------------------------------------------------------------
134 from docutils.parsers.rst.states import RSTState
135
136 @monkeypatch(RSTState)
137 def new_subsection(_wrapped, self, *args, **kwds):
138 desc_stack = getattr(self.memo, "desc_stack", None)
139 if desc_stack:
140 # after new_subsection() creates section node,
141 # it will invoke document.note_implicit_target().
142 # setting this attr signals our monkeypatch of that method (above)
143 # to make changes to that node based on desc_stack entry.
144 # NOTE: ideally, the note_implicit_target() monkeypatch,
145 # as well as this code, would be placed inside RSTState.new_subsection(),
146 # but that would require modifying sphinx's source :(
147 entry = desc_stack[-1]
148 entry['level'] = self.memo.section_level+1 # set level w/in description
149 self.document._modify_new_desc_section = entry # enable note hack
150
151 # hand off to real method
152 return _wrapped(self, *args, **kwds)
153
154 #----------------------------------------------------------------------
155 # monkeypatch ObjectDescription.run() so that:
156 # 1. before calling state.nested_parse(), we push a desc context
157 # onto state_machine.desc_context_stack (see above).
158 # 2. when it does call state.nested_parse() the first time,
159 # ``match_titles=True`` gets set.
160 # FIXME: using a really awkward way to accomplish this :|
161 # 3. pop our context off desc_context_stack when done.
162 #----------------------------------------------------------------------
163 from sphinx.directives import ObjectDescription
164 from sphinx.addnodes import desc as DescNodeType
165
166 @monkeypatch(ObjectDescription)
167 def run(_wrapped_run, self):
168 # ObjectDescription.before_content() will be invoked right before
169 # run calls ``self.state.nested_parse()``. We take advantage of that
170 # by wrapping the instance's before_content() call so that the last
171 # thing is does is set up ``self.state`` the way we want.
172
173 # NOTE: have to patch per-instance, since subclasses that override this
174 # don't tend to invoke super()
175 @monkeypatch(self)
176 def before_content(_wrapped_before):
177 # let real method do all the setup it wants.
178 _wrapped_before()
179
180 #----------------------------------------------------------------------
181 # need to figure out prefix to prepend to our description sections,
182 # so their IDs are unique. for now, using signature node
183 # ObjectDescription.run() has finished generating right before before_content()
184 # was called. Unfortunately, it's not available via self,
185 # so we have to reach into call stack to grab it...
186 # NOTE: ideally we would do this in ObjectDescription.run().
187 #----------------------------------------------------------------------
188 node = get_caller_value("sphinx.directives", "node",
189 rtype=DescNodeType, code="run")
190 # FIXME: would like a more bullet-proof way of deriving our id prefix...
191 signode = node.children[0]
192 if signode.get("ids"):
193 base = signode['ids'][0]
194 elif signode.get("names"):
195 base = signode['names'][0]
196 else:
197 base = signode.astext()
198 prefix = re.sub("[^a-zA-Z0-9_.]+", "-", base).strip("-") + "-"
199
200 # now that we've got that info, add our description context entry
201 # to the stack
202 memo = self.state.memo
203 if not hasattr(memo, "desc_stack"):
204 memo.desc_stack = []
205 memo.desc_stack.append(dict( # see new_subsection() above for dict format
206 prefix=prefix,
207 owner=self,
208 signode=signode,
209 level=0,
210 ))
211
212 #----------------------------------------------------------------------
213 # hack up ``state.nested_parse()`` so that the next time it's called,
214 # 'match_titles=True' is set. that call should happen as soon as this
215 # function returns back to ObjectDescription.run()
216 # NOTE: ideally, we would just set match_titles=True within ObjectDescription.run()
217 #----------------------------------------------------------------------
218 state = self.state
219 if not hasattr(state, "_set_next_match_titles_flag"):
220 # state is persistent object, only want to patch it once.
221 @monkeypatch(state)
222 def nested_parse(_wrapped_parse, *args, **kwds):
223 if state._set_next_match_titles_flag:
224 kwds['match_titles'] = True
225 state._set_next_match_titles_flag = False
226 return _wrapped_parse(*args, **kwds)
227
228 # signal our hack to set match_titles
229 state._set_next_match_titles_flag = True
230
231 @monkeypatch(self)
232 def after_content(_wrapped_after):
233 # remove our description context entry
234 # NOTE: ideally would do this in ObjectDescription.run()
235 desc = self.state.memo.desc_stack.pop()
236 assert desc['owner'] is self, "sanity check failed"
237
238 # let real method do it's work
239 return _wrapped_after()
240
241 # now invoke the real run() method.
242 # as soon as it calls before_content(), our hack above will patch self.state.
243 # after before_content() returns, real run method will call self.state.nested_parse(),
244 # and invoke our patched version instead.
245 return _wrapped_run(self)
246
247 #----------------------------------------------------------------------
248 # make autodoc invoke parse_nested_section_with_titles() for ALL objects
249 # if this isn't done, autodoc generates paragraphs instead of sections.
250 # this causes all nested content to be omitted
251 # FIXME: why is the lack of this causing a problem? should track it down.
252 #----------------------------------------------------------------------
253 from sphinx.ext.autodoc import Documenter
254 Documenter.titles_allowed = True
255
256 #----------------------------------------------------------------------
257 # finally, monkeypatch DocFieldTransformer.transform_all()
258 # so that it transforms doc fields within one of our nested sections
259 # (default code only looks at top-level nodes)
260 #
261 # FIXME: find a cleaner way to do this :|
262 #----------------------------------------------------------------------
263 from sphinx.util.docfields import DocFieldTransformer
264 from docutils.nodes import section
265
266 @monkeypatch(DocFieldTransformer)
267 def transform_all(_wrapped, self, node):
268 # transform immediate node contents like normal
269 _wrapped(self, node)
270
271 # our nested sections show up as definition lists,
272 # so make sure transform_all is also invoked for the contents
273 # of any definition list
274 for child in node:
275 if isinstance(child, section):
276 _wrapped(self, child.children)
277
278 #----------------------------------------------------------------------
279 # sigh. done monkeypatching.
280 #----------------------------------------------------------------------
281
282 #=============================================================================
283 # docstring mangling
284 #=============================================================================
285 def trim_module_header(app, what, name, obj, options, lines):
286 """
287 helper to remove one-line description from top of module (if preset).
288 """
289 if what != "module":
290 return
291 _title_re = re.compile(r"""
292 ^ \s*
293 ( {0} \s* -- \s* )?
294 [a-z0-9 _."']*
295 $
296 """.format(re.escape(name)), re.X|re.I)
297 if len(lines) > 1 and _title_re.match(lines[0]) and lines[1].strip() == '':
298 del lines[:2]
299
300 #=============================================================================
301 # sphinx extension entrypoint
302 #=============================================================================
303 def setup(app):
304 # don't patch sphinx unless this extension is actually in use
305 _patch_sphinx()
306
307 # clean up leading bit of module docstring
308 app.connect('autodoc-process-docstring', trim_module_header)
309
310 # identifies the version of our extension
311 return {'version': __version__}
312
313 #=============================================================================
314 # documentation helper
315 #
316 # NOTE: this function doesn't actually do anything,
317 # it exists to test this extension's behavior as part of docs/cloud_theme_test
318 #=============================================================================
319 def _doctestfunc():
320 """
321 The :mod:`~cloud_sptheme.ext.autodoc_sections` extension should generate
322 nested sections as found within object docstrings.
323
324 Nested Section
325 ==============
326
327 :param arg: xxx
328
329 .. attribute:: foo
330 :noindex:
331
332 bar
333
334 These sections can in turn contain others:
335
336 Child Section
337 -------------
338
339 Which allows breaking long class docstrings up in meaningful ways.
340
341 Child Section 2
342 ---------------
343
344 And more content
345
346 Nested Section 2
347 ================
348
349 end of class
350 """
351 pass
352
353 #=============================================================================
354 # eof
355 #=============================================================================