179
|
1 |
# -*- coding: utf-8 -*-
|
|
2 |
"""
|
|
3 |
sphinx.ext.ifconfig
|
|
4 |
~~~~~~~~~~~~~~~~~~~
|
|
5 |
|
|
6 |
Provides the ``ifconfig`` directive that allows to write documentation
|
|
7 |
that is included depending on configuration variables.
|
|
8 |
|
|
9 |
Usage::
|
|
10 |
|
|
11 |
.. ifconfig:: releaselevel in ('alpha', 'beta', 'rc')
|
|
12 |
|
|
13 |
This stuff is only included in the built docs for unstable versions.
|
|
14 |
|
|
15 |
The argument for ``ifconfig`` is a plain Python expression, evaluated in the
|
|
16 |
namespace of the project configuration (that is, all variables from ``conf.py``
|
|
17 |
are available.)
|
|
18 |
|
|
19 |
:copyright: 2008 by Georg Brandl.
|
|
20 |
:license: BSD.
|
|
21 |
"""
|
|
22 |
|
|
23 |
from docutils import nodes
|
|
24 |
|
|
25 |
|
|
26 |
class ifconfig(nodes.Element): pass
|
|
27 |
|
|
28 |
|
|
29 |
def ifconfig_directive(name, arguments, options, content, lineno,
|
|
30 |
content_offset, block_text, state, state_machine):
|
|
31 |
node = ifconfig()
|
|
32 |
node.line = lineno
|
|
33 |
node['expr'] = arguments[0]
|
|
34 |
state.nested_parse(content, content_offset, node)
|
|
35 |
return [node]
|
|
36 |
|
|
37 |
|
|
38 |
def process_ifconfig_nodes(app, doctree, docname):
|
|
39 |
ns = app.config.__dict__.copy()
|
|
40 |
ns['builder'] = app.builder.name
|
|
41 |
for node in doctree.traverse(ifconfig):
|
|
42 |
try:
|
|
43 |
res = eval(node['expr'], ns)
|
|
44 |
except Exception, err:
|
|
45 |
# handle exceptions in a clean fashion
|
|
46 |
from traceback import format_exception_only
|
|
47 |
msg = ''.join(format_exception_only(err.__class__, err))
|
|
48 |
newnode = doctree.reporter.error('Exception occured in '
|
|
49 |
'ifconfig expression: \n%s' %
|
|
50 |
msg, base_node=node)
|
|
51 |
node.replace_self(newnode)
|
|
52 |
else:
|
|
53 |
if not res:
|
|
54 |
node.replace_self([])
|
|
55 |
else:
|
|
56 |
node.replace_self(node.children)
|
|
57 |
|
|
58 |
|
|
59 |
def setup(app):
|
|
60 |
app.add_node(ifconfig)
|
|
61 |
app.add_directive('ifconfig', ifconfig_directive, 1, (1, 0, 1))
|
|
62 |
app.connect('doctree-resolved', process_ifconfig_nodes)
|