Debian Codegraph @

docs/source/conf.py

raw ◀ ▶
1 Debian patch touch this file
1 #!/usr/bin/env python3
2 #
3 # Trio documentation build configuration file, created by
4 # sphinx-quickstart on Sat Jan 21 19:11:14 2017.
5 #
6 # This file is execfile()d with the current directory set to its
7 # containing dir.
8 #
9 # Note that not all possible configuration values are present in this
10 # autogenerated file.
11 #
12 # All configuration values have a default; values that are commented out
13 # serve to show the default.
14
15 # If extensions (or modules to document with autodoc) are in another directory,
16 # add these directories to sys.path here. If the directory is relative to the
17 # documentation root, use os.path.abspath to make it absolute, like shown here.
18 #
19 from __future__ import annotations
20
21 import collections.abc
22 import glob
23 import os
24 import sys
25 from pathlib import Path
26 from typing import TYPE_CHECKING, cast
27
28 if sys.version_info >= (3, 11):
29 from sphinx.util.inventory import _InventoryItem
30
31 from sphinx.util.logging import getLogger
32
33 if TYPE_CHECKING:
34 from sphinx.application import Sphinx
•35 from sphinx.util.typing import Inventory
36
37 import OpenSSL
38
39 # For our local_customization module
40 sys.path.insert(0, os.path.abspath("."))
41
42 # Enable reloading with `typing.TYPE_CHECKING` being True
43 os.environ["SPHINX_AUTODOC_RELOAD_MODULES"] = "1"
44
45 # Handle writing newsfragments into the history file.
46 # We want to keep files unchanged when testing locally.
47 # So immediately revert the contents after running towncrier,
48 # then substitute when Sphinx wants to read it in.
49 history_file = Path("history.rst")
50
51 history_new: str | None
52 if glob.glob("../../newsfragments/*.*.rst"):
53 print("-- Found newsfragments; running towncrier --", flush=True)
54 history_orig = history_file.read_bytes()
55 import subprocess
56
57 # In case changes were staged, preserve indexed version.
58 # This grabs the hash of the current staged version.
59 history_staged = subprocess.run(
60 ["git", "rev-parse", "--verify", ":docs/source/history.rst"],
61 check=True,
62 cwd="../..",
63 stdout=subprocess.PIPE,
64 encoding="ascii",
65 ).stdout.strip()
66 try:
67 subprocess.run(
68 ["towncrier", "--keep", "--date", "not released yet"],
69 cwd="../..",
70 check=True,
71 )
72 history_new = history_file.read_text("utf8")
73 finally:
74 # Make sure this reverts even if a failure occurred.
75 # Restore whatever was staged.
76 print(f"Restoring history.rst = {history_staged}")
77 subprocess.run(
78 [
79 "git",
80 "update-index",
81 "--cacheinfo",
82 f"100644,{history_staged},docs/source/history.rst",
83 ],
84 cwd="../..",
85 check=False,
86 )
87 # And restore the working copy.
88 history_file.write_bytes(history_orig)
89 del history_orig # We don't need this any more.
90 else:
91 # Leave it as is.
92 history_new = None
93
94
95 def on_read_source(app: Sphinx, docname: str, content: list[str]) -> None:
96 """Substitute the modified history file."""
97 if docname == "history" and history_new is not None:
98 # This is a 1-item list with the file contents.
99 content[0] = history_new
100
101
102 # Sphinx is very finicky, and somewhat buggy, so we have several different
103 # methods to help it resolve links.
104 # 1. The ones that are not possible to fix are added to `nitpick_ignore`
105 # 2. some can be resolved with a simple alias in `autodoc_type_aliases`,
106 # even if that is primarily meant for TypeAliases
107 # 3. autodoc_process_signature is hooked up to an event, and we use it for
108 # whole-sale replacing types in signatures where internal details are not
109 # relevant or hard to read.
110 # 4. add_intersphinx manually modifies the intersphinx mappings after
111 # objects.inv has been parsed, to resolve bugs and version differences
112 # that causes some objects to be looked up incorrectly.
113 # 5. docs/source/typevars.py handles redirecting `typing_extensions` objects to `typing`, and linking `TypeVar`s to `typing.TypeVar` instead of sphinx wanting to link them to their individual definitions.
114 # It's possible there's better methods for resolving some of the above
115 # problems, but this works for now:tm:
116
117 # Warn about all references to unknown targets
118 nitpicky = True
119 # Except for these ones, which we expect to point to unknown targets:
120 nitpick_ignore = [
121 ("py:class", "CapacityLimiter-like object"),
122 ("py:class", "bytes-like"),
123 # Was removed but still shows up in changelog
124 ("py:class", "trio.lowlevel.RunLocal"),
125 # trio.abc is documented at random places scattered throughout the docs
126 ("py:mod", "trio.abc"),
127 ("py:exc", "Anything else"),
128 ("py:class", "async function"),
129 ("py:class", "sync function"),
130 # these do not have documentation on python.org
131 # nor entries in objects.inv
132 ("py:class", "socket.AddressFamily"),
133 ("py:class", "socket.SocketKind"),
134 ]
135 autodoc_inherit_docstrings = False
136 default_role = "obj"
137
138
139 # A dictionary for users defined type aliases that maps a type name to the full-qualified object name. It is used to keep type aliases not evaluated in the document.
140 # https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#confval-autodoc_type_aliases
141 # but it can also be used to help resolve various linking problems
142 autodoc_type_aliases = {
143 # SSLListener.accept's return type is seen as trio._ssl.SSLStream
144 "SSLStream": "trio.SSLStream",
145 }
146
147
148 # https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#event-autodoc-process-signature
149 def autodoc_process_signature(
150 app: Sphinx,
151 what: str,
152 name: str,
153 obj: object,
154 options: object,
155 signature: str,
156 return_annotation: str,
157 ) -> tuple[str, str]:
158 """Modify found signatures to fix various issues."""
159 if signature is not None:
160 signature = signature.replace("~_contextvars.Context", "~contextvars.Context")
161 if name == "trio.lowlevel.RunVar": # Typevar is not useful here.
162 signature = signature.replace(": ~trio._core._local.T", "")
163 if "_NoValue" in signature:
164 # Strip the type from the union, make it look like = ...
165 signature = signature.replace(" | type[trio._core._local._NoValue]", "")
166 signature = signature.replace("<class 'trio._core._local._NoValue'>", "...")
167 if "DTLS" in name:
168 signature = signature.replace("SSL.Context", "OpenSSL.SSL.Context")
169 # Don't specify PathLike[str] | PathLike[bytes], this is just for humans.
170 signature = signature.replace("StrOrBytesPath", "str | bytes | os.PathLike")
171
172 return signature, return_annotation
173
174
175 # currently undocumented things
176 logger = getLogger("trio")
177 UNDOCUMENTED = {
178 "trio._subprocess.HasFileno.fileno",
179 "trio.lowlevel.ParkingLot.broken_by",
180 }
181
182
183 def autodoc_process_docstring(
184 app: Sphinx,
185 what: str,
186 name: str,
187 obj: object,
188 options: object,
189 lines: list[str],
190 ) -> None:
191 if not lines:
192 # TODO: document these and remove them from here
193 if name in UNDOCUMENTED:
194 return
195
196 logger.warning(f"{name} has no docstring")
197 else:
198 if name in UNDOCUMENTED:
199 logger.warning(
200 f"outdated list of undocumented things in docs/source/conf.py: {name!r} has a docstring"
201 )
202
203
204 def setup(app: Sphinx) -> None:
205 # Add our custom styling to make our documentation better!
206 app.add_css_file("styles.css")
207 app.connect("autodoc-process-signature", autodoc_process_signature)
208 app.connect("autodoc-process-docstring", autodoc_process_docstring)
209
210 # After Intersphinx runs, add additional mappings.
211 app.connect("builder-inited", add_intersphinx, priority=1000)
212 app.connect("source-read", on_read_source)
213
214
215 html_context = {"current_version": os.environ.get("READTHEDOCS_VERSION_NAME")}
216
217 # -- General configuration ------------------------------------------------
218
219 # If your documentation needs a minimal Sphinx version, state it here.
220 #
221 # needs_sphinx = '1.0'
222
223 # Add any Sphinx extension module names here, as strings. They can be
224 # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
225 # ones.
226 extensions = [
227 "sphinx.ext.autodoc",
228 "sphinx.ext.intersphinx",
229 "sphinx.ext.coverage",
230 "sphinx.ext.napoleon",
231 "sphinxcontrib_trio",
232 "sphinxcontrib.jquery",
233 "sphinx_codeautolink",
234 "local_customization",
235 "typevars",
236 ]
237
238 def check_object_path(
239 key: str, url: str, path: str
240 ) -> dict[str, tuple[str, str]]:
241 if os.path.isfile(path):
242 return {key: (url, path)}
243 return {}
•244
245
246 intersphinx_mapping = {}
247 intersphinx_mapping.update(
248 check_object_path(
249 "python",
250 "https://docs.python.org/",
251 "/usr/share/doc/python" + ".".join((str(x) for x in sys.version_info[:2])) + "/html/objects.inv"
252 )
253 )
254 intersphinx_mapping.update(
255 check_object_path(
256 "pyopenssl",
257 "https://www.pyopenssl.org/en/{v}".format(v=OpenSSL.__version__),
258 "/usr/share/doc/python-openssl-doc/html/objects.inv"
259 )
260 )
261 intersphinx_mapping.update(
262 check_object_path(
263 "outcome",
264 "https://outcome.readthedocs.io/en/latest/",
265 "/usr/share/doc/python-outcome-doc/html/objects.inv"
266 )
267 )
268 intersphinx_mapping.update(
269 check_object_path(
270 "sniffio",
271 "https://sniffio.readthedocs.io/en/latest/",
272 "/usr/share/doc/python-sniffio-doc/html/objects.inv"
273 )
274 )
275 intersphinx_mapping.update(
276 check_object_path(
277 "trio-util",
278 "https://trio-util.readthedocs.io/en/latest/",
279 "/usr/share/doc/python-trio-util-doc/html/objects.inv"
280 )
281 )
282 intersphinx_mapping.update(
283 check_object_path(
284 "flake8-async",
285 "https://flake8-async.readthedocs.io/en/latest/",
286 "/usr/share/doc/python-flake8-async-doc/html/objects.inv"
287 )
288 )
289
290 # See https://sphinx-codeautolink.readthedocs.io/en/latest/reference.html#configuration
291 codeautolink_autodoc_inject = False
292 codeautolink_global_preface = """
293 import trio
294 from trio import *
295 """
296
297
298 def add_intersphinx(app: Sphinx) -> None:
299 """Add some specific intersphinx mappings.
300
301 Hooked up to builder-inited. app.builder.env.interpshinx_inventory is not an official API, so this may break on new sphinx versions.
302 """
303
304 def add_mapping(
305 reftype: str,
306 library: str,
307 obj: str,
308 version: str = "3.12",
309 target: str | None = None,
310 ) -> None:
311 """helper function"""
312 url_version = "3" if version == "3.12" else version
313 if target is None:
314 target = f"{library}.{obj}"
315
316 # sphinx doing fancy caching stuff makes this attribute invisible
317 # to type checkers
318 inventory = app.builder.env.intersphinx_inventory # type: ignore[attr-defined]
319 assert isinstance(inventory, dict)
320 inventory = cast("Inventory", inventory)
321
322 if sys.version_info >= (3, 11):
323 inventory[f"py:{reftype}"][f"{target}"] = _InventoryItem(
324 project_name="Python",
325 project_version=version,
326 uri=f"https://docs.python.org/{url_version}/library/{library}.html/{obj}",
327 display_name="-",
328 )
329 else:
330 inventory[f"py:{reftype}"][f"{target}"] = (
331 "Python",
332 version,
333 f"https://docs.python.org/{url_version}/library/{library}.html/{obj}",
334 "-",
335 )
336
337 # This has been removed in Py3.12, so add a link to the 3.11 version with deprecation warnings.
338 add_mapping("method", "pathlib", "Path.link_to", "3.11")
339
340 # defined in py:data in objects.inv, but sphinx looks for a py:class
341 # see https://github.com/sphinx-doc/sphinx/issues/10974
342 # to dump the objects.inv for the stdlib, you can run
343 # python -m sphinx.ext.intersphinx http://docs.python.org/3/objects.inv
344 add_mapping("class", "math", "inf")
345 add_mapping("class", "types", "FrameType")
346
347 # new in py3.12, and need target because sphinx is unable to look up
348 # the module of the object if compiling on <3.12
349 if not hasattr(collections.abc, "Buffer"):
350 add_mapping("class", "collections.abc", "Buffer", target="Buffer")
351
352
353 autodoc_member_order = "bysource"
354
355 # Add any paths that contain templates here, relative to this directory.
356 templates_path = ["_templates"]
357
358 # The suffix(es) of source filenames.
359 # You can specify multiple suffix as a list of string:
360 #
361 # source_suffix = ['.rst', '.md']
362 source_suffix = ".rst"
363
364 # The master toctree document.
365 master_doc = "index"
366
367 # General information about the project.
368 project = "Trio"
369 copyright = "2017, Nathaniel J. Smith" # noqa: A001 # Name shadows builtin
370 author = "Nathaniel J. Smith"
371
372 # The version info for the project you're documenting, acts as replacement for
373 # |version| and |release|, also used in various other places throughout the
374 # built documents.
375 #
376 # The short X.Y version.
377 import importlib.metadata
378
379 version = importlib.metadata.version("trio")
380 # The full version, including alpha/beta/rc tags.
381 release = version
382
383 html_favicon = "_static/favicon-32.png"
384 html_logo = "../../logo/wordmark-transparent.svg"
385 # & down below in html_theme_options we set logo_only=True
386
387 # The language for content autogenerated by Sphinx. Refer to documentation
388 # for a list of supported languages.
389 #
390 # This is also used if you do content translation via gettext catalogs.
391 # Usually you set "language" from the command line for these cases.
392 language = "en"
393
394 # List of patterns, relative to source directory, that match files and
395 # directories to ignore when looking for source files.
396 # This patterns also effect to html_static_path and html_extra_path
397 exclude_patterns: list[str] = []
398
399 # The name of the Pygments (syntax highlighting) style to use.
400 pygments_style = "default"
401
402 highlight_language = "python3"
403
404 # If true, `todo` and `todoList` produce output, else they produce nothing.
405 todo_include_todos = False
406
407 # This avoids a warning by the epub builder that it can't figure out
408 # the MIME type for our favicon.
409 suppress_warnings = ["epub.unknown_project_files"]
410
411
412 # -- Options for HTML output ----------------------------------------------
413
414 # The theme to use for HTML and HTML Help pages. See the documentation for
415 # a list of builtin themes.
416 #
417 # html_theme = 'alabaster'
418
419 # We have to set this ourselves, not only because it's useful for local
420 # testing, but also because if we don't then RTD will throw away our
421 # html_theme_options.
422 html_theme = "sphinx_rtd_theme"
423
424 # Theme options are theme-specific and customize the look and feel of a theme
425 # further. For a list of options available for each theme, see the
426 # documentation.
427 #
428 html_theme_options = {
429 # default is 2
430 # show deeper nesting in the RTD theme's sidebar TOC
431 # https://stackoverflow.com/questions/27669376/
432 # I'm not 100% sure this actually does anything with our current
433 # versions/settings...
434 "navigation_depth": 4,
435 "logo_only": True,
436 "prev_next_buttons_location": "both",
437 "style_nav_header_background": "#d2e7fa",
438 }
439
440 # Add any paths that contain custom static files (such as style sheets) here,
441 # relative to this directory. They are copied after the builtin static files,
442 # so a file named "default.css" will overwrite the builtin "default.css".
443 html_static_path = ["_static"]
444
445
446 # -- Options for HTMLHelp output ------------------------------------------
447
448 # Output file base name for HTML help builder.
449 htmlhelp_basename = "Triodoc"
450
451
452 # -- Options for LaTeX output ---------------------------------------------
453
454 latex_elements: dict[str, object] = {
455 # The paper size ('letterpaper' or 'a4paper').
456 #
457 # 'papersize': 'letterpaper',
458 # The font size ('10pt', '11pt' or '12pt').
459 #
460 # 'pointsize': '10pt',
461 # Additional stuff for the LaTeX preamble.
462 #
463 # 'preamble': '',
464 # Latex figure (float) alignment
465 #
466 # 'figure_align': 'htbp',
467 }
468
469 # Grouping the document tree into LaTeX files. List of tuples
470 # (source start file, target name, title,
471 # author, documentclass [howto, manual, or own class]).
472 latex_documents = [
473 (master_doc, "Trio.tex", "Trio Documentation", "Nathaniel J. Smith", "manual"),
474 ]
475
476
477 # -- Options for manual page output ---------------------------------------
478
479 # One entry per manual page. List of tuples
480 # (source start file, name, description, authors, manual section).
481 man_pages = [(master_doc, "trio", "Trio Documentation", [author], 1)]
482
483
484 # -- Options for Texinfo output -------------------------------------------
485
486 # Grouping the document tree into Texinfo files. List of tuples
487 # (source start file, target name, title, author,
488 # dir menu entry, description, category)
489 texinfo_documents = [
490 (
491 master_doc,
492 "Trio",
493 "Trio Documentation",
494 author,
495 "Trio",
496 "One line description of project.",
497 "Miscellaneous",
498 ),
499 ]