Debian Codegraph @

cloud_sptheme/ext/page_only.py

raw symbols SCIP
1 """
2 ==============================================================
3 :mod:`cloud_sptheme.ext.page_only` -- Exclude Pages from Build
4 ==============================================================
5
6 .. versionadded:: 1.8
7
8 Overview
9 ========
10 This extension provides a ``.. page-only::`` directive,
11 which allows conditionally omitting entire pages from the document based on build tags.
12
13 The first line of a page should be a ``.. page-only:: <expr>`` directive;
14 where ``<expr>`` is a tag, or simple tag expression, just like ``.. only::``.
15 If the expression evaluates to False, the page won't be included in the final build
16 (and should be silently omitted from any TOC lists).
17
18 E.g. ``.. page-only:: draft and html``
19 """
20 #=============================================================================
21 # imports
22 #=============================================================================
23 # core
24 from __future__ import absolute_import, division, print_function
25 import io
26 import re
27 from weakref import WeakKeyDictionary
28 # site
29 from docutils.parsers.rst import Directive
30 import sphinx
31 import sphinx.addnodes
32 from sphinx.util import logging
33 # pkg
34 from cloud_sptheme import __version__
35 from cloud_sptheme.utils import patchapplier, monkeypatch
36 # local
37 logger = logging.getLogger(__name__)
38 __all__ = [
39 "setup",
40 ]
41
42 #=============================================================================
43 # patching
44 #=============================================================================
45 @patchapplier
46 def _patch_sphinx():
47
48 #
49 # to get files list right, best to modify found_files before env.get_outdated_files()
50 # gets a hold of them, and starts looking for changes.
51 #
52 from sphinx.environment import BuildEnvironment
53 @monkeypatch(BuildEnvironment)
54 def get_outdated_files(__wrapped__, env, config_changed):
55 # call out hook to modify found_docs to remove omitted entries,
56 # and store them in env.omitted_by_page_only
57 strip_omitted_docs(env)
58
59 # hand off to orig function
60 return __wrapped__(env, config_changed)
61
62 #
63 # patch TocTree.run() so it doesn't warning about broken toc entries.
64 #
65 from sphinx.directives.other import TocTree
66 @monkeypatch(TocTree)
67 def run(__wrapped__, self):
68 env = self.state.document.settings.env
69 omitted_docs = env.omitted_by_pageonly
70 found_docs = env.found_docs
71 try:
72 # temporarily restore found_docs so TocTree doesn't throw warning.
73 # NOTE: this causes broken toc entries to be generated (rather than warnings).
74 # these are cleaned up by remove_toc_entries() below
75 _set_found_docs(env, found_docs | omitted_docs)
76 return __wrapped__(self)
77 finally:
78 _set_found_docs(env, found_docs)
79
80
81 def _set_found_docs(env, found_docs):
82 """
83 compat helper for writing found_docs attribute
84 """
85 if sphinx.version_info < (2, 0):
86 env.found_docs = found_docs
87 else:
88 env.project.docnames = found_docs
89
90 #=============================================================================
91 # hooks
92 #=============================================================================
93
94 #: regex used to detect page-only directive
95 _header_re = re.compile(r"^\.\.\s+page-only::\s+(?P<expr>.+)\s*$")
96
97
98 #: as hack, using this to store reference to app so we can resolve it w/in env monkeypatch
99 _env_to_app = WeakKeyDictionary()
100
101
102 def install_app_ref(app):
103 """
104 hack to get app ref w/in env.get_outdated_files() monkeypatch,
105 called on 'builder-inited' event
106 """
107 _env_to_app[app.env] = app
108
109
110 def strip_omitted_docs(env):
111 """
112 helper invoked right before env.get_outdated_files() is called,
113 scans for omitted files and modifies document set accordingly.
114
115 called via monkeypatch before .get_outdated_files() is run,
116 which happens during env.update(), shortly before 'env-get-outdated' event.
117 """
118 # scan through found docs, removing any that should be omitted
119 app = _env_to_app[env]
120 found_docs = env.found_docs
121 omitted_docs = set()
122 for doc in found_docs:
123 # find first non-empty line
124 with io.open(env.doc2path(doc), encoding="latin-1") as fh:
125 line = ''
126 for line in fh:
127 if line.strip():
128 break
129
130 # check if it's a PageOnly directive
131 m = _header_re.match(line)
132 if not m:
133 continue
134
135 # add page to omitted list if expression doesn't validate
136 if not app.tags.eval_condition(m.group("expr")):
137 omitted_docs.add(doc)
138
139 if omitted_docs:
140 logger.info("%s pages omitted by page-only" % len(omitted_docs))
141
142 # persist omitted list for TocTree.run() wrapper and remove_from_toc()
143 env.omitted_by_pageonly = omitted_docs
144
145 # remove omitted from 'found_docs', so get_outdated_files() doesn't see them
146 found_docs.difference_update(omitted_docs)
147
148
149 class PageOnly(Directive):
150 """
151 Directive used to capture info.
152 Notes that this doesn't actually do anything, job has already been done by find_omitted_docs().
153 This is just here to prevent parse errors.
154 """
155 # NOTE: cloned from Author directive, should be ok...
156 has_content = False
157 required_arguments = 1
158 optional_arguments = 0
159 final_argument_whitespace = True
160 option_spec = {}
161
162 def run(self):
163 # XXX: could issue warning if this is encountered anywhere but top of document.
164 return []
165
166
167 def remove_from_toc(app, doctree):
168 """
169 remove omitted pages from TOC, let through by TocTree.run() monkeypatch
170 called on doctree-read event.
171 """
172 omitted_docs = app.env.omitted_by_pageonly
173 for toctreenode in doctree.traverse(sphinx.addnodes.toctree):
174 entries = toctreenode['entries']
175 # print("%r %r %r" % (doctree, toctreenode, entries))
176 # dbgcon()
177 idx = 0
178 while idx < len(entries):
179 entry = entries[idx]
180 # entry is (label|None, doc) tuple...
181 if str(entry[1]) in omitted_docs:
182 del entries[idx]
183 else:
184 idx += 1
185
186 #=============================================================================
187 # sphinx entrypoint
188 #=============================================================================
189 def setup(app):
190 _patch_sphinx()
191 app.add_directive('page-only', PageOnly)
192 app.connect('builder-inited', install_app_ref)
193 app.connect('doctree-read', remove_from_toc)
194
195 # identifies the version of our extension
196 return {'version': __version__}
197
198 #=============================================================================
199 # eoc
200 #=============================================================================