Debian Codegraph @

cloud_sptheme/ext/role_index.py

raw symbols SCIP
1 """
2 ======================================================
3 :mod:`cloud_sptheme.ext.role_index` -- JSON Role Index
4 ======================================================
5
6 .. versionadded:: 1.8
7
8 Overview
9 ========
10 This sphinx extension for the HTML builder places a file called ``roleindex.json``
11 in the output directory along with the documentation. This file contains
12 a dictionary which mapping all reference ids (made via ``:ref:`` or ``:doc:``) to
13 a 3-element list of ``(page, anchor, title)``
14
15 This is useful for integrating a Sphinx manual into the online help of web application --
16 context-specific help can be provided by looking up a predefined ``:ref:`` tag within
17 the json file, and redirecting the user to the appropriate page and anchor location.
18
19 As an example, see the `roleindex.json <../roleindex.json>`_ for this documentation.
20
21 .. warning::
22
23 This extension should be considered "beta" quality.
24 It was recently written, may have unknown issues, and may need to be revised.
25
26 Configuration
27 =============
28 This extension reads the following ``conf.py`` options:
29
30 ``role_index_style``
31
32 style of json output -- can be ``"compact"`` (the default), or ``"pretty"`` (for debugging).
33 """
34 #=========================================================
35 # imports
36 #=========================================================
37 # core
38 from __future__ import absolute_import, division, print_function
39 import codecs
40 import logging
41 log = logging.getLogger(__name__)
42 import json
43 import os
44 # site
45 from sphinx.locale import _TranslationProxy
46 # pkg
47 from cloud_sptheme import __version__
48 # local
49 __all__ = [
50 "setup",
51 ]
52 #=========================================================
53 # hooks
54 #=========================================================
55 def write_role_index(app):
56 """
57 helper which generates ``"roleindex.json"`` for document.
58 """
59 if app.builder.name != "html":
60 return
61
62 style = app.config.role_index_style or "compact"
63
64 index = {}
65
66 # add 'ref' role mappings
67 index['ref'] = dict(
68 (key, (page, anchor, label))
69 for key, (page, anchor, label)
70 in app.env.domaindata['std']['labels'].items()
71 )
72
73 # add 'doc' role mappings
74 index['doc'] = dict(
75 (doc.lower(), (doc, "", title.astext()))
76 for doc, title in app.env.titles.items()
77 )
78
79 # create composite 'all' mapping
80 index['any'] = index['doc'].copy()
81 index['any'].update(index['ref'])
82
83 # write to file
84 def encode(value):
85 if isinstance(value, _TranslationProxy):
86 return str(value)
87 raise TypeError("can't serialize value: %r (type=%r)" % (value, type(value)))
88
89 target = os.path.join(app.builder.outdir, "roleindex.json")
90 kwds = dict(sort_keys=True, separators=(",", ":"), default=encode)
91 if style == "compact":
92 pass
93 elif style == "pretty":
94 kwds.update(separators=(", ", ": "), indent=True)
95 else:
96 raise ValueError("unknown role_index_style: %r" % style)
97 with codecs.open(target, "w", encoding="utf-8") as fh:
98 json.dump(index, fh, **kwds)
99
100 #=========================================================
101 # sphinx entrypoint
102 #=========================================================
103 def setup(app):
104
105 app.add_config_value('role_index_style', None, 'html')
106
107 # XXX: this probably isn't right event to attach to...
108 # but want to run during writing phase, after all pages have been scanned into tree,
109 # and this seems like close to the right place.
110 def wrapper(app):
111 write_role_index(app)
112 return []
113 app.connect('html-collect-pages', wrapper)
114
115 # identifies the version of our extension
116 return {'version': __version__}
117
118 #=========================================================
119 # eof
120 #=========================================================