ExternalLink.py

Summary

Lines:

266 of 273 covered (97.4%)

Excluded lines:

1

Branches:

96 of 98 taken (98.0%), 2 lines partially

Coverage:

97.6%

Directory:

Sphinx

Missed lines:

479, 547-549, 626-627, 633

Source

pyTooling/Sphinx/ExternalLink.pycoveredpartialuncoveredexcludednot executable
1# ==================================================================================================================== #
2#             _____           _ _               ____        _     _                                                    #
3#  _ __  _   |_   _|__   ___ | (_)_ __   __ _  / ___| _ __ | |__ (_)_ __ __  __                                        #
4# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` | \___ \| '_ \| '_ \| | '_ \\ \/ /                                        #
5# | |_) | |_| || | (_) | (_) | | | | | | (_| |_ ___) | |_) | | | | | | | |>  <                                         #
6# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____/| .__/|_| |_|_|_| |_/_/\_\                                        #
7# |_|    |___/                          |___/        |_|                                                               #
8# ==================================================================================================================== #
9# Authors:                                                                                                             #
10#   Patrick Lehmann                                                                                                    #
11#                                                                                                                      #
12# License:                                                                                                             #
13# ==================================================================================================================== #
14# Copyright 2026-2026 Patrick Lehmann - Bötzingen, Germany                                                             #
15#                                                                                                                      #
16# Licensed under the Apache License, Version 2.0 (the "License");                                                      #
17# you may not use this file except in compliance with the License.                                                     #
18# You may obtain a copy of the License at                                                                              #
19#                                                                                                                      #
20#   http://www.apache.org/licenses/LICENSE-2.0                                                                         #
21#                                                                                                                      #
22# Unless required by applicable law or agreed to in writing, software                                                  #
23# distributed under the License is distributed on an "AS IS" BASIS,                                                    #
24# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.                                             #
25# See the License for the specific language governing permissions and                                                  #
26# limitations under the License.                                                                                       #
27#                                                                                                                      #
28# SPDX-License-Identifier: Apache-2.0                                                                                  #
29# ==================================================================================================================== #
30#
31"""
32Icons behind the external links of a document in HTML, each chosen by the link's target.
33
34A link to GitHub gets GitHub's mark, an e-mail address an envelope, and a link to a host without an icon of its own a
35square with an arrow pointing out of it.
36
37Two post-transforms mark the links, for HTML only: :class:`MarkExternalLinks` before Sphinx resolves the references,
38so it sees the links written with their URI - also those of a :mod:`sphinx.ext.extlinks` role -, and
39:class:`MarkIntersphinxLinks` after, so it sees the links Sphinx resolved to another project's documentation - e.g. by
40:mod:`sphinx.ext.intersphinx`. A marked link gets a CSS class naming its icon, which the stylesheet draws, and opens
41in a new browser tab - unless configuration value ``pyTooling_ExternalLink_NewTab`` is ``False``, or the link is an
42e-mail address.
43
44A third post-transform, :class:`MarkDownloadLinks`, gives the links of Sphinx' ``:download:`` role a download icon. A
45link to an archive - a file name ending in an extension of :data:`ARCHIVE_FORMATS`, e.g. ``.zip`` or ``.tar.gz`` - gets
46the archive icon instead, also a link written with its URI.
47
48A fourth post-transform, :class:`AddDownloadSizes`, writes the size of a download's file behind its link, and an
49archive's format, e.g. ``(ZIP, 1.2 MiB)``. The size of a file of the documentation is read from the file system; the
50size of another site's file is asked with an HTTP ``HEAD`` request, only if its URI matches a pattern of configuration
51value ``pyTooling_ExternalLink_RemoteSizes``. An archive, whose size isn't known, gets its format only, e.g. ``(ZIP)``.
52
53.. code-block:: Python
54
55   # doc/conf.py
56   pyTooling_ExternalLink_Icons =             "all"
57   pyTooling_ExternalLink_NewTab =            True
58   pyTooling_ExternalLink_Hosts =             {
59     "gitlab.example.org": "gitlab",
60   }
61   pyTooling_ExternalLink_DownloadSizes =     True
62   pyTooling_ExternalLink_RemoteSizes =       [
63     "https://github.com/pyTooling/*/releases/download/*",
64   ]
65   pyTooling_ExternalLink_RemoteSizeTimeout = 5.0
66
67.. seealso::
68
69   :ref:`LINK/External`
70      |rarr| The icons, the configuration values and the stylesheet's custom properties, with rendered examples.
71"""
72from fnmatch                           import fnmatchcase
73from math                              import isfinite
74from pathlib                           import Path
75from typing                            import Any, ClassVar, Literal, Mapping, Self, Sequence
76from urllib.parse                      import urlsplit
77from weakref                           import WeakKeyDictionary
78
79from docutils                          import nodes
80from requests.exceptions               import HTTPError, RequestException, Timeout
81from sphinx.addnodes                   import download_reference
82from sphinx.application                import Sphinx
83from sphinx.config                     import Config
84from sphinx.environment                import BuildEnvironment
85from sphinx.transforms.post_transforms import SphinxPostTransform
86from sphinx.util.logging               import getLogger
87from sphinx.util.requests              import head
88
89from pyTooling.Common                  import StringEnum, getFullyQualifiedName, getTypeName
90from pyTooling.Decorators              import export
91from pyTooling.Sphinx                  import SphinxExtensionError
92
93
94__all__ = ["CONFIG_PREFIX", "HOST_ICONS", "ARCHIVE_FORMATS"]
95
96CONFIG_PREFIX = "pyTooling_ExternalLink"
97"""Prefix of the configuration values, e.g. ``pyTooling_ExternalLink_Icons``."""
98
99
100@export
101class ExternalLinkIcons(StringEnum):
102	"""
103	Which external links get an icon, as configuration value ``pyTooling_ExternalLink_Icons`` states it.
104	"""
105
106	Disabled = "none"      #: No link.
107	Explicit = "explicit"  #: Links written with their URI, also those of a :mod:`sphinx.ext.extlinks` role.
108	All =      "all"       #: These, and links resolved to another project's documentation.
109
110	DEFAULT =  Explicit    #: Without a configuration value, the links written with their URI get an icon.
111
112
113@export
114class LinkIcon(StringEnum):
115	"""
116	The icon drawn behind an external link; the link gets the CSS class ``pytooling-link-icon-<value>``.
117	"""
118
119	External =    "external"     #: A square with an arrow pointing out of it.
120	Mail =        "mail"         #: An envelope.
121	GitHub =      "github"       #: GitHub's mark.
122	GitLab =      "gitlab"       #: GitLab's tanuki.
123	Python =      "python"       #: Python's logo.
124	NumPy =       "numpy"        #: NumPy's logo.
125	PyPy =        "pypy"         #: PyPy's logo.
126	Pytest =      "pytest"       #: pytest's logo.
127	Pydantic =    "pydantic"     #: Pydantic's logo.
128	ReadTheDocs = "readthedocs"  #: Read the Docs' logo.
129	Sphinx =      "sphinx"       #: Sphinx' logo.
130	Download =    "download"     #: An arrow pointing down into a tray; the icon of a download link.
131	Archive =     "archive"      #: A file with a zipper; the icon of a link to an archive.
132
133	DEFAULT =     External       #: A host without an icon of its own gets the square with the arrow.
134
135	@classmethod
136	def FromURI(cls, uri: str, hosts: Mapping[str, Self]) -> Self:
137		"""
138		Choose the icon of a link by its target.
139
140		A ``mailto:`` URI gets :attr:`Mail`, a URI whose path ends in an archive's extension :attr:`Archive` - see
141		:func:`getArchiveExtension`. Any other URI gets the icon of its host, which is looked up in ``hosts`` with its full
142		domain name first, then without its first label, and so on: ``docs.python.org`` is found as ``python.org``. A URI
143		without a host, or with a host not found, gets :attr:`DEFAULT`.
144
145		:param uri:   The link's target.
146		:param hosts: The icons, keyed by domain name in lower case.
147		:returns:     The link's icon.
148		"""
149		target = urlsplit(uri)
150		if target.scheme == "mailto":
151			return cls.Mail
152		elif getArchiveExtension(uri) != "":
153			return cls.Archive
154		elif (host := target.hostname) is None:
155			return cls.DEFAULT
156
157		labels = host.split(".")
158		for index in range(len(labels)):
159			if (domainName := ".".join(labels[index:])) in hosts:
160				return hosts[domainName]
161
162		return cls.DEFAULT
163
164
165HOST_ICONS: dict[str, LinkIcon] = {
166	"github.com":      LinkIcon.GitHub,
167	"gitlab.com":      LinkIcon.GitLab,
168	"python.org":      LinkIcon.Python,
169	"pypi.org":        LinkIcon.Python,
170	"numpy.org":       LinkIcon.NumPy,
171	"pypy.org":        LinkIcon.PyPy,
172	"pytest.org":      LinkIcon.Pytest,
173	"pydantic.dev":    LinkIcon.Pydantic,
174	"readthedocs.io":  LinkIcon.ReadTheDocs,
175	"readthedocs.org": LinkIcon.ReadTheDocs,
176	"rtfd.io":         LinkIcon.ReadTheDocs,
177	"sphinx-doc.org":  LinkIcon.Sphinx,
178}
179"""
180The icon of a link to a host or to one of its subdomains, keyed by the host's domain name in lower case.
181
182A project adds hosts, or replaces an icon, with configuration value ``pyTooling_ExternalLink_Hosts``.
183"""
184
185ARCHIVE_FORMATS: dict[str, str] = {
186	"zip":     "ZIP",
187	"tar.gz":  "tar.gz",
188	"tgz":     "tar.gz",
189	"tar.bz2": "tar.bz2",
190	"tar.xz":  "tar.xz",
191	"tar.zst": "tar.zst",
192	"7z":      "7z",
193}
194"""
195The formats of archives, keyed by their file name extension in lower case, as the label a download's size names.
196
197A link to a file with one of these extensions gets the icon :attr:`LinkIcon.Archive`.
198"""
199
200
201@export
202def getArchiveExtension(uri: str) -> str:
203	"""
204	Return the extension of the archive a link targets, as key of :data:`ARCHIVE_FORMATS`.
205
206	The extensions are compared with the end of the URI's path, ignoring case; a query and a fragment are ignored. A
207	local file name is a URI without a scheme: ``files/Archive.ZIP`` ends in ``zip``.
208
209	:param uri: The link's target.
210	:returns:   The extension, or an empty string if the path doesn't end in an archive's extension.
211	"""
212	path = urlsplit(uri).path.lower()
213	for extension in ARCHIVE_FORMATS:
214		if path.endswith(f".{extension}"):
215			return extension
216
217	return ""
218
219
220@export
221def checkExternalLinkConfiguration(sphinx: Sphinx, config: Config) -> None:
222	"""
223	Call-back for Sphinx' ``config-inited`` event, reading the configuration values of the external links' icons.
224
225	``pyTooling_ExternalLink_Icons`` is replaced by the member of :class:`ExternalLinkIcons` it names,
226	``pyTooling_ExternalLink_Hosts`` by a dictionary of the members of :class:`LinkIcon` its values name, keyed by its
227	hosts in lower case, ``pyTooling_ExternalLink_RemoteSizes`` by a tuple of its patterns, and
228	``pyTooling_ExternalLink_RemoteSizeTimeout`` by a :class:`float`.
229
230	:param sphinx:                The Sphinx application.
231	:param config:                The configuration, after :file:`conf.py` was read.
232	:raises SphinxExtensionError: If ``pyTooling_ExternalLink_Icons`` is not a string.
233	:raises SphinxExtensionError: If ``pyTooling_ExternalLink_Icons`` names no member of :class:`ExternalLinkIcons`.
234	:raises SphinxExtensionError: If ``pyTooling_ExternalLink_NewTab`` is not a boolean.
235	:raises SphinxExtensionError: If ``pyTooling_ExternalLink_Hosts`` is not a dictionary.
236	:raises SphinxExtensionError: If a host of ``pyTooling_ExternalLink_Hosts`` is not a string.
237	:raises SphinxExtensionError: If a host of ``pyTooling_ExternalLink_Hosts`` is empty.
238	:raises SphinxExtensionError: If an icon of ``pyTooling_ExternalLink_Hosts`` is not a string.
239	:raises SphinxExtensionError: If an icon of ``pyTooling_ExternalLink_Hosts`` names no member of :class:`LinkIcon`.
240	:raises SphinxExtensionError: If ``pyTooling_ExternalLink_DownloadSizes`` is not a boolean.
241	:raises SphinxExtensionError: If ``pyTooling_ExternalLink_RemoteSizes`` is not a list.
242	:raises SphinxExtensionError: If a pattern of ``pyTooling_ExternalLink_RemoteSizes`` is not a string.
243	:raises SphinxExtensionError: If a pattern of ``pyTooling_ExternalLink_RemoteSizes`` is empty.
244	:raises SphinxExtensionError: If ``pyTooling_ExternalLink_RemoteSizeTimeout`` is not a number.
245	:raises SphinxExtensionError: If ``pyTooling_ExternalLink_RemoteSizeTimeout`` is not a positive, finite number.
246	"""
247	icons = config[f"{CONFIG_PREFIX}_Icons"]
248	if icons is not None and not isinstance(icons, str):
249		ex = SphinxExtensionError(f"conf.py: {CONFIG_PREFIX}_Icons: Value is not of type 'str'.")
250		ex.add_note(f"Got type '{getFullyQualifiedName(icons)}'.")
251		raise ex
252
253	try:
254		config[f"{CONFIG_PREFIX}_Icons"] = ExternalLinkIcons.Parse(icons)
255	except ValueError as cause:
256		ex = SphinxExtensionError(f"conf.py: {CONFIG_PREFIX}_Icons: '{icons}' is not a selection of links.")
257		ex.add_note(f"Allowed values: {', '.join(ExternalLinkIcons)}.")
258		raise ex from cause
259
260	if not isinstance(newTab := config[f"{CONFIG_PREFIX}_NewTab"], bool):
261		ex = SphinxExtensionError(f"conf.py: {CONFIG_PREFIX}_NewTab: Value is not of type 'bool'.")
262		ex.add_note(f"Got type '{getFullyQualifiedName(newTab)}'.")
263		raise ex
264
265	hosts = config[f"{CONFIG_PREFIX}_Hosts"]
266	if not isinstance(hosts, Mapping):
267		ex = SphinxExtensionError(f"conf.py: {CONFIG_PREFIX}_Hosts: Value is not a dictionary.")
268		ex.add_note(f"Got type '{getFullyQualifiedName(hosts)}'.")
269		raise ex
270
271	hostIcons: dict[str, LinkIcon] = {}
272	for host, icon in hosts.items():
273		if not isinstance(host, str):
274			ex = SphinxExtensionError(f"conf.py: {CONFIG_PREFIX}_Hosts: Host '{host}' is not of type 'str'.")
275			ex.add_note(f"Got type '{getFullyQualifiedName(host)}'.")
276			raise ex
277		elif host == "":
278			raise SphinxExtensionError(f"conf.py: {CONFIG_PREFIX}_Hosts: Host is empty.")
279
280		if icon is not None and not isinstance(icon, str):
281			ex = SphinxExtensionError(f"conf.py: {CONFIG_PREFIX}_Hosts: Icon of host '{host}' is not of type 'str'.")
282			ex.add_note(f"Got type '{getFullyQualifiedName(icon)}'.")
283			raise ex
284
285		try:
286			hostIcons[host.lower()] = LinkIcon.Parse(icon)
287		except ValueError as cause:
288			ex = SphinxExtensionError(f"conf.py: {CONFIG_PREFIX}_Hosts: Icon '{icon}' of host '{host}' is not an icon.")
289			ex.add_note(f"Allowed values: {', '.join(LinkIcon)}.")
290			raise ex from cause
291
292	config[f"{CONFIG_PREFIX}_Hosts"] = hostIcons
293
294	if not isinstance(downloadSizes := config[f"{CONFIG_PREFIX}_DownloadSizes"], bool):
295		ex = SphinxExtensionError(f"conf.py: {CONFIG_PREFIX}_DownloadSizes: Value is not of type 'bool'.")
296		ex.add_note(f"Got type '{getFullyQualifiedName(downloadSizes)}'.")
297		raise ex
298
299	remoteSizes = config[f"{CONFIG_PREFIX}_RemoteSizes"]
300	if isinstance(remoteSizes, str) or not isinstance(remoteSizes, Sequence):
301		ex = SphinxExtensionError(f"conf.py: {CONFIG_PREFIX}_RemoteSizes: Value is not a list.")
302		ex.add_note(f"Got type '{getFullyQualifiedName(remoteSizes)}'.")
303		raise ex
304
305	for pattern in remoteSizes:
306		if not isinstance(pattern, str):
307			ex = SphinxExtensionError(f"conf.py: {CONFIG_PREFIX}_RemoteSizes: Pattern '{pattern}' is not of type 'str'.")
308			ex.add_note(f"Got type '{getFullyQualifiedName(pattern)}'.")
309			raise ex
310		elif pattern == "":
311			raise SphinxExtensionError(f"conf.py: {CONFIG_PREFIX}_RemoteSizes: Pattern is empty.")
312
313	config[f"{CONFIG_PREFIX}_RemoteSizes"] = tuple(remoteSizes)
314
315	timeout = config[f"{CONFIG_PREFIX}_RemoteSizeTimeout"]
316	if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):
317		ex = SphinxExtensionError(f"conf.py: {CONFIG_PREFIX}_RemoteSizeTimeout: Value is not of type 'float'.")
318		ex.add_note(f"Got type '{getFullyQualifiedName(timeout)}'.")
319		raise ex
320	elif not (timeout > 0 and isfinite(timeout)):
321		ex = SphinxExtensionError(f"conf.py: {CONFIG_PREFIX}_RemoteSizeTimeout: Value is not a positive, finite number.")
322		ex.add_note(f"Got value '{timeout}'.")
323		raise ex
324
325	config[f"{CONFIG_PREFIX}_RemoteSizeTimeout"] = float(timeout)
326
327
328@export
329class BaseExternalLinkTransform(SphinxPostTransform):
330	"""
331	Base-class of the post-transforms marking external links in HTML, so the stylesheet draws an icon behind each.
332
333	A marked link gets the CSS class :attr:`linkClass`, and the CSS class ``pytooling-link-icon-<icon>`` naming the icon
334	:meth:`LinkIcon.FromURI` chooses for it; a link to an archive also gets the CSS class
335	``pytooling-archive-<extension>``, e.g. ``pytooling-archive-tar-gz``, naming its format. A link holding an image -
336	e.g. a badge - isn't marked, nor is a download link: :class:`MarkDownloadLinks` marks those.
337
338	If ``pyTooling_ExternalLink_NewTab`` is ``True``, a marked link opens in a new browser tab: it gets the attributes
339	``target="_blank"`` and ``rel="noopener noreferrer"``, which Sphinx' HTML writer copies into the ``<a>`` element. An
340	e-mail address doesn't, as a browser would open an empty tab beside the mail program.
341	"""
342
343	formats =   ("html", )                               #: Output formats the transform runs for.
344	linkClass:  ClassVar[str]                            #: CSS class of a link the transform marks.
345	selections: ClassVar[tuple[ExternalLinkIcons, ...]]  #: Values of ``pyTooling_ExternalLink_Icons`` it runs for.
346
347	#: The configuration values of the external links' icons, as ``name: (default, rebuild, types)``. Each is
348	#: registered with :data:`CONFIG_PREFIX` as prefix, e.g. ``pyTooling_ExternalLink_Icons``.
349	#:
350	#: ``Icons`` names a member of :class:`ExternalLinkIcons`; ``None`` is its ``DEFAULT``. ``NewTab`` states whether a
351	#: marked link opens in a new browser tab. ``Hosts`` maps a host's domain name to the name of a member of
352	#: :class:`LinkIcon`, adding to :data:`HOST_ICONS` or replacing its icon. ``DownloadSizes`` states whether
353	#: :class:`AddDownloadSizes` writes the downloads' sizes, ``RemoteSizes`` lists the patterns of the URIs whose size it
354	#: asks for, and ``RemoteSizeTimeout`` is the seconds it waits for a response. All are ``"html"``-rebuilt: the marks
355	#: and sizes are written into the pages, never into the environment.
356	configValues: ClassVar[dict[str, tuple[Any, Literal["html"], Any]]] = {
357		"Icons":             (None, "html", (str, ExternalLinkIcons)),
358		"NewTab":            (True, "html", bool),
359		"Hosts":             ({},   "html", dict),
360		"DownloadSizes":     (True, "html", bool),
361		"RemoteSizes":       ([],   "html", (list, tuple)),
362		"RemoteSizeTimeout": (5.0,  "html", (int, float)),
363	}
364
365	def run(self, **kwargs: Any) -> None:
366		"""
367		Mark every link :meth:`_Selects` selects, if ``pyTooling_ExternalLink_Icons`` is one of :attr:`selections`.
368
369		:param kwargs: Keyword arguments Sphinx passes to a post-transform; none is used.
370		"""
371		if self.config[f"{CONFIG_PREFIX}_Icons"] not in self.selections:
372			return
373
374		hosts = HOST_ICONS.copy()
375		hosts.update(self.config[f"{CONFIG_PREFIX}_Hosts"])
376		newTab = self.config[f"{CONFIG_PREFIX}_NewTab"]
377		for reference in self.document.findall(nodes.reference):
378			if isinstance(reference, download_reference) or "refuri" not in reference or not self._Selects(reference):
379				continue
380			elif next(reference.findall(nodes.image), None) is not None:
381				continue
382
383			icon = LinkIcon.FromURI(reference["refuri"], hosts)
384			reference["classes"] += [self.linkClass, f"pytooling-link-icon-{icon}"]
385			if icon is LinkIcon.Archive:
386				extension = getArchiveExtension(reference["refuri"])
387				reference["classes"].append(f"pytooling-archive-{extension.replace('.', '-')}")
388
389			if newTab and icon is not LinkIcon.Mail:
390				reference["target"] = "_blank"
391				reference["rel"] =    "noopener noreferrer"
392
393	def _Selects(self, reference: nodes.reference) -> bool:
394		"""
395		Decide whether a link with a URI is marked.
396
397		:param reference: The link.
398		:returns:         ``True`` if the link is marked.
399		"""
400		raise NotImplementedError(f"Method '{getTypeName(self)}._Selects' is abstract.")
401
402
403@export
404class MarkExternalLinks(BaseExternalLinkTransform):
405	"""
406	A post-transform marking the links written with an absolute URI, before Sphinx resolves the references.
407
408	A link of a :mod:`sphinx.ext.extlinks` role, e.g. ``:gh:``, is one of them.
409	"""
410
411	default_priority = 5                                                    #: Before Sphinx' ``ReferencesResolver`` (10).
412	linkClass =        "pytooling-external-link"                            #: CSS class of a marked link.
413	selections =       (ExternalLinkIcons.Explicit, ExternalLinkIcons.All)  #: Values it runs for.
414
415	def _Selects(self, reference: nodes.reference) -> bool:
416		"""
417		Select a link to an absolute URI of scheme ``http``, ``https``, ``ftp`` or ``mailto``.
418
419		:param reference: The link.
420		:returns:         ``True`` if the link isn't internal and its URI has one of these schemes.
421		"""
422		return not reference.get("internal", False) and urlsplit(reference["refuri"]).scheme in (
423			"http", "https", "ftp", "mailto"
424		)
425
426
427@export
428class MarkIntersphinxLinks(BaseExternalLinkTransform):
429	"""
430	A post-transform marking the links Sphinx resolved to another project's documentation.
431
432	Such a link - e.g. one of :mod:`sphinx.ext.intersphinx` - is one :class:`MarkExternalLinks` didn't mark, which its
433	resolver declared not ``internal``. Its URI may be relative, for a project whose inventory is a local file; then it
434	gets the icon :attr:`LinkIcon.External`.
435	"""
436
437	default_priority = 20                            #: After Sphinx' ``ReferencesResolver`` (10).
438	linkClass =        "pytooling-intersphinx-link"  #: CSS class of a marked link.
439	selections =       (ExternalLinkIcons.All, )     #: Values it runs for.
440
441	def _Selects(self, reference: nodes.reference) -> bool:
442		"""
443		Select a link declared not ``internal`` by its resolver, which :class:`MarkExternalLinks` didn't mark.
444
445		:param reference: The link.
446		:returns:         ``True`` if the link's attribute ``internal`` is ``False`` and the link isn't marked yet.
447		"""
448		return reference.get("internal", None) is False and MarkExternalLinks.linkClass not in reference["classes"]
449
450
451@export
452class MarkDownloadLinks(SphinxPostTransform):
453	"""
454	A post-transform marking the links of Sphinx' ``:download:`` role in HTML, so the stylesheet draws a download icon
455	behind each.
456
457	A marked link gets the CSS classes ``pytooling-download-link`` and ``pytooling-link-icon-download``, whether the file
458	is part of the documentation or another site's. A link to an archive gets ``pytooling-link-icon-archive`` instead,
459	and ``pytooling-archive-<extension>`` naming its format - see :func:`getArchiveExtension`. A marked link stays in the
460	browser's tab, as the browser saves the file. A link holding an image isn't marked.
461	"""
462
463	default_priority = 5                                                    #: Before Sphinx' ``ReferencesResolver`` (10).
464	formats =          ("html", )                                           #: Output formats the transform runs for.
465	linkClass =        "pytooling-download-link"                            #: CSS class of a marked link.
466	selections =       (ExternalLinkIcons.Explicit, ExternalLinkIcons.All)  #: Values it runs for.
467
468	def run(self, **kwargs: Any) -> None:
469		"""
470		Mark every download link, if ``pyTooling_ExternalLink_Icons`` is one of :attr:`selections`.
471
472		:param kwargs: Keyword arguments Sphinx passes to a post-transform; none is used.
473		"""
474		if self.config[f"{CONFIG_PREFIX}_Icons"] not in self.selections:
475			return
476
477		for reference in self.document.findall(download_reference):
478			if next(reference.findall(nodes.image), None) is not None:
479				continue
480			elif (extension := getArchiveExtension(reference["reftarget"])) == "":
481				reference["classes"] += [self.linkClass, f"pytooling-link-icon-{LinkIcon.Download}"]
482			else:
483				reference["classes"] += [
484					self.linkClass, f"pytooling-link-icon-{LinkIcon.Archive}", f"pytooling-archive-{extension.replace('.', '-')}"
485				]
486
487
488@export
489class DownloadSizeError(SphinxExtensionError):
490	"""
491	The size of a download's file is unknown: the file can't be read, or a server didn't tell it.
492	"""
493
494
495@export
496class AddDownloadSizes(SphinxPostTransform):
497	"""
498	A post-transform writing the size of a download's file behind its link in HTML, and the format of an archive.
499
500	A download is a link of Sphinx' ``:download:`` role, or a link written with an ``http`` or ``https`` URI whose path
501	ends in an archive's extension - see :func:`getArchiveExtension`. Its size follows the link as an inline node of CSS
502	class :attr:`sizeClass`, e.g. ``(340.0 kiB)``, for an archive with its format's label of :data:`ARCHIVE_FORMATS`,
503	e.g. ``(ZIP, 1.2 MiB)``. A link holding an image gets none.
504
505	The size of a file of the documentation is read from the file system. The size of another site's file is asked with
506	an HTTP ``HEAD`` request, following redirections, only if its URI is of scheme ``http`` or ``https`` and matches a
507	pattern of ``pyTooling_ExternalLink_RemoteSizes``; each URI is asked once per build. If the size is unknown - e.g. a
508	file Sphinx didn't find, no response within ``pyTooling_ExternalLink_RemoteSizeTimeout`` seconds, an HTTP error, or a
509	response without a ``Content-Length`` -, Sphinx warns at the link with the warning type ``pyTooling.download_size``.
510	A download, whose size isn't known, gets no size; an archive gets its format only, e.g. ``(ZIP)``. No download gets
511	a size or a format, if ``pyTooling_ExternalLink_DownloadSizes`` is ``False``.
512	"""
513
514	default_priority = 25                         #: After the post-transforms marking the links.
515	formats =          ("html", )                 #: Output formats the transform runs for.
516	sizeClass =        "pytooling-download-size"  #: CSS class of the size behind a link.
517
518	#: The sizes of the remote files asked for, per build environment - i.e. per build -, in bytes, keyed by URI.
519	_remoteSizes:    ClassVar[WeakKeyDictionary[BuildEnvironment, dict[str, int]]] =               WeakKeyDictionary()
520	#: Why the sizes of remote files asked for are unknown, per build environment, keyed by URI.
521	_remoteFailures: ClassVar[WeakKeyDictionary[BuildEnvironment, dict[str, DownloadSizeError]]] = WeakKeyDictionary()
522
523	def run(self, **kwargs: Any) -> None:
524		"""
525		Write the size behind every download, if ``pyTooling_ExternalLink_DownloadSizes`` is ``True``.
526
527		:param kwargs: Keyword arguments Sphinx passes to a post-transform; none is used.
528		"""
529		if not self.config[f"{CONFIG_PREFIX}_DownloadSizes"]:
530			return
531
532		patterns = self.config[f"{CONFIG_PREFIX}_RemoteSizes"]
533		timeout =  self.config[f"{CONFIG_PREFIX}_RemoteSizeTimeout"]
534		sizes =    self._remoteSizes.setdefault(self.env, {})
535		failures = self._remoteFailures.setdefault(self.env, {})
536		for reference in list(self.document.findall(nodes.reference)):
537			isDownload = isinstance(reference, download_reference)
538			if next(reference.findall(nodes.image), None) is not None:
539				continue
540			elif isDownload and "refuri" not in reference:
541				if "filename" not in reference:
542					continue
543
544				uri = reference["reftarget"]
545				try:
546					sizeText = self._FormatSize(Path(self.env.relfn2path(uri, self.env.docname)[1]).stat().st_size)
547				except OSError as ex:
548					self._WarnUnknownSize(reference, uri, f"{ex.strerror}.")
549					sizeText = ""
550			elif urlsplit(uri := reference.get("refuri", "")).scheme not in ("http", "https"):
551				continue
552			elif not isDownload and getArchiveExtension(uri) == "":
553				continue
554			elif not any(fnmatchcase(uri, pattern) for pattern in patterns):
555				sizeText = ""
556			elif uri in sizes:
557				sizeText = self._FormatSize(sizes[uri])
558			elif uri in failures:
559				self._WarnUnknownSize(reference, uri, failures[uri])
560				sizeText = ""
561			else:
562				try:
563					sizes[uri] = self._RequestSize(uri, timeout, self.config)
564				except DownloadSizeError as ex:
565					failures[uri] = ex
566					self._WarnUnknownSize(reference, uri, ex)
567					sizeText = ""
568				else:
569					sizeText = self._FormatSize(sizes[uri])
570
571			extension = getArchiveExtension(uri)
572			if extension == "" and sizeText == "":
573				continue
574			elif extension == "":
575				text = f"({sizeText})"
576			elif sizeText == "":
577				text = f"({ARCHIVE_FORMATS[extension]})"
578			else:
579				text = f"({ARCHIVE_FORMATS[extension]}, {sizeText})"
580
581			reference.parent.insert(
582				reference.parent.index(reference) + 1, [nodes.Text(" "), nodes.inline("", text, classes=[self.sizeClass])]
583			)
584
585	@staticmethod
586	def _WarnUnknownSize(reference: nodes.reference, uri: str, reason: object) -> None:
587		"""
588		Warn at a download's link, that its file's size is unknown.
589
590		The warning's type is ``pyTooling.download_size``, so a project can suppress it.
591
592		:param reference: The download's link.
593		:param uri:       The file's URI, or its path as written in the document.
594		:param reason:    Why the size is unknown.
595		"""
596		getLogger(__name__).warning(
597			f"Size of download '{uri}' is unknown. {reason}", location=reference, type="pyTooling", subtype="download_size"
598		)
599
600	@staticmethod
601	def _RequestSize(uri: str, timeout: float, config: Config) -> int:
602		"""
603		Ask a server for the size of a file, with an HTTP ``HEAD`` request.
604
605		The request is sent by :mod:`sphinx.util.requests`, so it follows Sphinx' configuration values ``user_agent``,
606		``tls_verify`` and ``tls_cacerts``. It follows redirections, e.g. of a GitHub release's asset to its storage.
607
608		:param uri:                The file's URI.
609		:param timeout:            Seconds to wait for a response.
610		:param config:             Sphinx' configuration.
611		:returns:                  The file's size in bytes, as the response's ``Content-Length`` states it.
612		:raises DownloadSizeError: If the server doesn't respond within ``timeout`` seconds, responds with an HTTP error, or
613		                           the request fails otherwise.
614		:raises DownloadSizeError: If the response has no ``Content-Length``, or one that is no number.
615		"""
616		try:
617			response = head(
618				uri, allow_redirects=True, timeout=timeout, _user_agent=config.user_agent,
619				_tls_info=(config.tls_verify, config.tls_cacerts)
620			)
621			response.raise_for_status()
622		except Timeout as ex:
623			raise DownloadSizeError(f"No response within {timeout} seconds.") from ex
624		except HTTPError as ex:
625			raise DownloadSizeError(f"Server responded {ex.response.status_code} {ex.response.reason}.") from ex
626		except RequestException as ex:
627			raise DownloadSizeError(f"Request failed: {ex}") from ex
628
629		length = response.headers.get("Content-Length", "")
630		if length == "":
631			raise DownloadSizeError("Response has no 'Content-Length'.")
632		elif not length.isdecimal():
633			raise DownloadSizeError(f"Response's 'Content-Length' '{length}' is no number.")
634
635		return int(length)
636
637	@staticmethod
638	def _FormatSize(size: int) -> str:
639		"""
640		Format a file's size in binary units.
641
642		A size below 1024 bytes is written in bytes, e.g. ``1023 B``; a larger one in the largest unit of kiB, MiB and GiB
643		it reaches, with one decimal, e.g. ``1.0 kiB``.
644
645		:param size: The size in bytes.
646		:returns:    The size and its unit.
647		"""
648		if size < 1024:
649			return f"{size} B"
650
651		for exponent, unit in (
652			(1, "kiB"),
653			(2, "MiB")
654		):
655			if (value := round(size / 1024 ** exponent, 1)) < 1024:
656				return f"{value:.1f} {unit}"
657
658		return f"{size / 1024 ** 3:.1f} GiB"