Debian Codegraph @

src/sphinxcontrib/towncrier/ext.py

raw
1 """Sphinx extension for injecting an unreleased changelog into docs."""
2
3
4 import subprocess # noqa: S404
5 import sys
6 from contextlib import suppress as suppress_exceptions
7 from functools import lru_cache
8 from pathlib import Path
9 from typing import Dict, List, Optional, Set, Tuple, Union
10
11 from sphinx.application import Sphinx
12 from sphinx.config import Config as SphinxConfig
13 from sphinx.environment import BuildEnvironment
14 from sphinx.environment.collectors import EnvironmentCollector
15 from sphinx.util import logging
16 from sphinx.util.docutils import SphinxDirective
17 from sphinx.util.nodes import nested_parse_with_titles, nodes
18
19
20 # isort: split
21
22
23 # Ref: https://github.com/PyCQA/pylint/issues/3817
24 from docutils import statemachine # pylint: disable=wrong-import-order
25
26 from ._compat import shlex_join # noqa: WPS436
27 from ._data_transformers import ( # noqa: WPS436
28 escape_project_version_rst_substitution,
29 )
30 from ._fragment_discovery import lookup_towncrier_fragments # noqa: WPS436
31 from ._version import __version__ # noqa: WPS436
32
33
34 PROJECT_ROOT_DIR = Path(__file__).parents[3].resolve()
35 TOWNCRIER_DRAFT_CMD = (
36 sys.executable, '-m', # invoke via runpy under the same interpreter
37 'towncrier',
38 'build',
39 '--draft', # write to stdout, don't change anything on disk
40 )
41
42
43 logger = logging.getLogger(__name__)
44
45
46 @lru_cache(typed=True)
47 def _get_changelog_draft_entries(
48 target_version: str,
49 allow_empty: bool = False,
50 working_dir: Optional[str] = None,
51 config_path: Optional[str] = None,
52 ) -> str:
53 """Retrieve the unreleased changelog entries from Towncrier."""
54 extra_cli_args: Tuple[str, ...] = (
55 '--version',
56 # A version to be used in the RST title:
57 escape_project_version_rst_substitution(target_version),
58 )
59 if config_path is not None:
60 # This isn't actually supported by a released version of Towncrier yet:
61 # https://github.com/twisted/towncrier/pull/157#issuecomment-666549246
62 # https://github.com/twisted/towncrier/issues/269
63 extra_cli_args += '--config', str(config_path)
64
65 try:
66 towncrier_output = subprocess.check_output( # noqa: S603
67 TOWNCRIER_DRAFT_CMD + extra_cli_args,
68 cwd=str(working_dir) if working_dir else None,
69 stderr=subprocess.PIPE,
70 universal_newlines=True, # a "text" alias exists since Python 3.7
71 ).strip()
72
73 except subprocess.CalledProcessError as proc_exc:
74 cmd = shlex_join(proc_exc.cmd)
75 stdout = proc_exc.stdout or '[No output]'
76 stderr = proc_exc.stderr or '[No output]'
77 raise RuntimeError(
78 'Command exited unexpectedly.\n\n'
79 f'Command: {cmd}\n'
80 f'Return code: {proc_exc.returncode}\n\n'
81 f'Standard output:\n{stdout}\n\n'
82 f'Standard error:\n{stderr}',
83 ) from proc_exc
84
85 if not allow_empty and 'No significant changes' in towncrier_output:
86 raise LookupError('There are no unreleased changelog entries so far')
87
88 return towncrier_output
89
90
91 @lru_cache(maxsize=1, typed=True)
92 def _get_draft_version_fallback(
93 strategy: str,
94 sphinx_config: SphinxConfig,
95 ) -> str:
96 """Generate a fallback version string for towncrier draft."""
97 known_strategies = {'draft', 'sphinx-version', 'sphinx-release'}
98 if strategy not in known_strategies:
99 raise ValueError(
100 'Expected "strategy" to be '
101 f'one of {known_strategies!r} but got {strategy!r}',
102 )
103
104 if 'sphinx' in strategy:
105 return (
106 sphinx_config.release
107 if 'release' in strategy
108 else sphinx_config.version
109 )
110
111 return '[UNRELEASED DRAFT]'
112
113
114 def _nodes_from_document_markup_source(
115 state: statemachine.State,
116 markup_source: str,
117 ) -> List[nodes.Node]:
118 """Turn an RST or Markdown string into a list of nodes.
119
120 These nodes can be used in the document.
121 """
122 node = nodes.Element()
123 node.document = state.document
124 nested_parse_with_titles(
125 state=state,
126 content=statemachine.ViewList(
127 statemachine.string2lines(markup_source),
128 source='[towncrier-fragments]',
129 ),
130 node=node,
131 )
132 return node.children
133
134
135 class TowncrierDraftEntriesDirective(SphinxDirective):
136 """Definition of the ``towncrier-draft-entries`` directive."""
137
138 has_content = True # default: False
139
140 def run(self) -> List[nodes.Node]: # noqa: WPS210
141 """Generate a node tree in place of the directive."""
142 target_version = (
143 self.content[:1][0]
144 if self.content[:1] else None
145 )
146 if self.content[1:]: # inner content present
147 raise self.error(
148 f'Error in "{self.name!s}" directive: '
149 'only one argument permitted.',
150 )
151
152 config = self.env.config
153 autoversion_mode = config.towncrier_draft_autoversion_mode
154 include_empty = config.towncrier_draft_include_empty
155
156 towncrier_fragment_paths = lookup_towncrier_fragments(
157 working_dir=config.towncrier_draft_working_directory,
158 config_path=config.towncrier_draft_config_path,
159 )
160 for path in towncrier_fragment_paths:
161 # make sphinx discard doctree cache on file changes
162 self.env.note_dependency(str(path))
163
164 try:
165 # pylint: disable-next=line-too-long
166 self.env.towncrier_fragment_paths |= ( # type: ignore[attr-defined]
167 towncrier_fragment_paths
168 )
169 except AttributeError:
170 # If the attribute hasn't existed, initialize it instead of
171 # updating
172 self.env.towncrier_fragment_paths = ( # type: ignore[attr-defined]
173 towncrier_fragment_paths
174 )
175
176 try:
177 self.env.towncrier_fragment_docs |= { # type: ignore[attr-defined]
178 self.env.docname,
179 }
180 except AttributeError:
181 # If the attribute hasn't existed, initialize it instead of
182 # updating
183 self.env.towncrier_fragment_docs = { # type: ignore[attr-defined]
184 self.env.docname,
185 }
186
187 try:
188 draft_changes = _get_changelog_draft_entries(
189 target_version or
190 _get_draft_version_fallback(autoversion_mode, config),
191 allow_empty=include_empty,
192 working_dir=config.towncrier_draft_working_directory,
193 config_path=config.towncrier_draft_config_path,
194 )
195 except RuntimeError as runtime_err:
196 raise self.error(runtime_err)
197 except LookupError:
198 return []
199
200 return _nodes_from_document_markup_source(
201 state=self.state,
202 markup_source=draft_changes,
203 )
204
205
206 class TowncrierDraftEntriesEnvironmentCollector(EnvironmentCollector):
207 r"""Environment collector for ``TowncrierDraftEntriesDirective``.
208
209 When :py:class:`~TowncrierDraftEntriesDirective` is used in a
210 document, it depends on some dynamically generated change fragments.
211 After the first render, the doctree nodes are put in cache and are
212 reused from there. There's a way to make Sphinx aware of the
213 directive dependencies by calling :py:meth:`BuildEnvironment.\
214 note_dependency <sphinx.environment.BuildEnvironment.\
215 note_dependency>` but this will only work for fragments that have
216 existed at the time of that first directive invocation.
217
218 In order to track newly appearing change fragment dependencies,
219 we need to do so at the time of Sphinx identifying what documents
220 require rebuilding. There's :event:`env-get-outdated` that
221 allows to extend this list of planned rebuilds and we could use it
222 by assigning a document-to-fragments map from within the directive
223 and reading it in the event handler later (since env contents are
224 preserved in cache). But this approach does not take into account
225 cleanups and parallel runs of Sphinx. In order to make it truly
226 parallelism-compatible, we need to define how to merge our custom
227 cache attribute collected within multiple Sphinx subprocesses into
228 one object and that's where :py:class:`~sphinx.environment.\
229 collectors.EnvironmentCollector` comes into play.
230
231 Refs:
232 * https://github.com/sphinx-doc/sphinx/issues/8040#issuecomment-671587308
233 * https://github.com/sphinx-contrib/sphinxcontrib-towncrier/issues/1
234 """
235
236 def clear_doc(
237 self,
238 app: Sphinx,
239 env: BuildEnvironment,
240 docname: str,
241 ) -> None:
242 """Clean up env metadata related to the removed document.
243
244 This is a handler for :event:`env-purge-doc`.
245 """
246 with suppress_exceptions(AttributeError, KeyError):
247 env.towncrier_fragment_docs.remove( # type: ignore[attr-defined]
248 docname,
249 )
250
251 def merge_other(
252 self,
253 app: Sphinx,
254 env: BuildEnvironment,
255 docnames: Set[str],
256 other: BuildEnvironment,
257 ) -> None:
258 """Merge doc-to-fragments from another proc into this env.
259
260 This is a handler for :event:`env-merge-info`.
261 """
262 try:
263 other_fragment_docs: Set[str] = (
264 other.towncrier_fragment_docs # type: ignore[attr-defined]
265 )
266 except AttributeError:
267 # If the other process env doesn't have documents using
268 # `TowncrierDraftEntriesDirective`, there's nothing to merge
269 return
270
271 if not hasattr(env, 'towncrier_fragment_docs'): # noqa: WPS421
272 # If the other process env doesn't have documents using
273 # `TowncrierDraftEntriesDirective`, initialize the structure
274 # at least
275 env.towncrier_fragment_docs = set() # type: ignore[attr-defined]
276
277 if not hasattr(env, 'towncrier_fragment_paths'): # noqa: WPS421
278 env.towncrier_fragment_paths = set() # type: ignore[attr-defined]
279
280 # Since Sphinx does not pull the same document into multiple
281 # processes, we don't care about the same dict key appearing
282 # in different envs with different sets of the deps
283 env.towncrier_fragment_docs.update( # type: ignore[attr-defined]
284 other_fragment_docs,
285 )
286 env.towncrier_fragment_paths.update( # type: ignore[attr-defined]
287 other.towncrier_fragment_paths, # type: ignore[attr-defined]
288 )
289
290 def process_doc(self, app: Sphinx, doctree: nodes.document) -> None:
291 """React to :event:`doctree-read` with no-op."""
292
293 # pylint: disable=too-many-arguments
294 def get_outdated_docs( # noqa: WPS211
295 self,
296 app: Sphinx,
297 env: BuildEnvironment,
298 added: Set[str],
299 changed: Set[str],
300 removed: Set[str],
301 ) -> List[str]:
302 """Mark docs with changed fragment deps for rebuild.
303
304 This is a handler for :event:`env-get-outdated`.
305 """
306 towncrier_fragment_paths = lookup_towncrier_fragments(
307 working_dir=env.config.towncrier_draft_working_directory,
308 config_path=env.config.towncrier_draft_config_path,
309 )
310
311 fragments_changed = False
312 with suppress_exceptions(AttributeError):
313 fragments_changed = bool(
314 towncrier_fragment_paths
315 ^ env.towncrier_fragment_paths, # type: ignore[attr-defined]
316 )
317
318 return (
319 list(
320 env.towncrier_fragment_docs # type: ignore[attr-defined]
321 - changed,
322 )
323 if fragments_changed
324 else []
325 )
326
327
328 def setup(app: Sphinx) -> Dict[str, Union[bool, str]]:
329 """Initialize the extension."""
330 rebuild_trigger = 'html' # rebuild full html on settings change
331 app.add_config_value(
332 'towncrier_draft_config_path',
333 default=None,
334 rebuild=rebuild_trigger,
335 )
336 app.add_config_value(
337 'towncrier_draft_autoversion_mode',
338 default='scm-draft',
339 rebuild=rebuild_trigger,
340 )
341 app.add_config_value(
342 'towncrier_draft_include_empty',
343 default=True,
344 rebuild=rebuild_trigger,
345 )
346 app.add_config_value(
347 'towncrier_draft_working_directory',
348 default=None,
349 rebuild=rebuild_trigger,
350 )
351 app.add_directive(
352 'towncrier-draft-entries',
353 TowncrierDraftEntriesDirective,
354 )
355
356 # Register an environment collector to merge data gathered by the
357 # directive in parallel builds
358 app.add_env_collector(TowncrierDraftEntriesEnvironmentCollector)
359
360 return {
361 'parallel_read_safe': True,
362 'parallel_write_safe': True,
363 'version': __version__,
364 }