| 1 |
# This file is part of Hypothesis, which may be found at |
| 2 |
# https://github.com/HypothesisWorks/hypothesis/ |
| 3 |
# |
| 4 |
# Copyright the Hypothesis Authors. |
| 5 |
# Individual contributors are listed in AUTHORS.rst and the git log. |
| 6 |
# |
| 7 |
# This Source Code Form is subject to the terms of the Mozilla Public License, |
| 8 |
# v. 2.0. If a copy of the MPL was not distributed with this file, You can |
| 9 |
# obtain one at https://mozilla.org/MPL/2.0/. |
| 10 |
|
| 11 |
# vendored from https://github.com/documatt/sphinx-reredirects under the MIT |
| 12 |
# license, with thanks |
| 13 |
|
| 14 |
# ruff: noqa: G004 |
| 15 |
|
| 16 |
import re |
| 17 |
from collections.abc import Mapping, Sequence |
| 18 |
from fnmatch import fnmatch |
| 19 |
from pathlib import Path |
| 20 |
from string import Template |
| 21 |
from urllib.parse import urlparse |
| 22 |
|
| 23 |
from sphinx.application import Sphinx |
| 24 |
from sphinx.builders.linkcheck import CheckExternalLinksBuilder, Hyperlink |
| 25 |
from sphinx.util import logging |
| 26 |
from sphinx.util.osutil import SEP |
| 27 |
|
| 28 |
OPTION_REDIRECTS = "redirects" |
| 29 |
OPTION_REDIRECTS_DEFAULT: dict[str, str] = {} |
| 30 |
|
| 31 |
OPTION_TEMPLATE_FILE = "redirect_html_template_file" |
| 32 |
OPTION_TEMPLATE_FILE_DEFAULT = None |
| 33 |
|
| 34 |
REDIRECT_FILE_DEFAULT_TEMPLATE = ( |
| 35 |
'<html><head><meta http-equiv="refresh" content="0; url=${to_uri}"></head></html>' |
| 36 |
) |
| 37 |
|
| 38 |
logger = logging.getLogger(__name__) |
| 39 |
|
| 40 |
wildcard_pattern = re.compile(r"[\*\?\[\]]") |
| 41 |
|
| 42 |
|
| 43 |
def setup(app: Sphinx) -> dict: |
| 44 |
""" |
| 45 |
Extension setup, called by Sphinx |
| 46 |
""" |
| 47 |
app.connect("html-collect-pages", init) |
| 48 |
app.connect("builder-inited", collect_redirects_for_linkcheck) |
| 49 |
app.add_config_value(OPTION_REDIRECTS, OPTION_REDIRECTS_DEFAULT, "env") |
| 50 |
app.add_config_value(OPTION_TEMPLATE_FILE, OPTION_TEMPLATE_FILE_DEFAULT, "env") |
| 51 |
return {"parallel_read_safe": True} |
| 52 |
|
| 53 |
|
| 54 |
def init(app: Sphinx) -> Sequence | None: |
| 55 |
if not app.config[OPTION_REDIRECTS]: |
| 56 |
logger.debug("No redirects configured") |
| 57 |
return [] |
| 58 |
|
| 59 |
rr = Reredirects(app) |
| 60 |
to_be_redirected = rr.grab_redirects() |
| 61 |
rr.create_redirects(to_be_redirected) |
| 62 |
|
| 63 |
# html-collect-pages requires to return iterable of pages to write, |
| 64 |
# we have no additional pages to write |
| 65 |
return [] |
| 66 |
|
| 67 |
|
| 68 |
class Reredirects: |
| 69 |
def __init__(self, app: Sphinx) -> None: |
| 70 |
self.app = app |
| 71 |
self.redirects_option: dict[str, str] = getattr(app.config, OPTION_REDIRECTS) |
| 72 |
self.template_file_option: str = getattr(app.config, OPTION_TEMPLATE_FILE) |
| 73 |
|
| 74 |
def grab_redirects(self) -> Mapping[str, str]: |
| 75 |
"""Inspect redirects option in conf.py and returns dict mapping |
| 76 |
docname to target (with expanded placeholder).""" |
| 77 |
# docname-target dict |
| 78 |
to_be_redirected = {} |
| 79 |
|
| 80 |
# For each source-target redirect pair in conf.py |
| 81 |
for source, target in self.redirects_option.items(): |
| 82 |
# no wildcard, append source as-is |
| 83 |
if not self._contains_wildcard(source): |
| 84 |
to_be_redirected[source] = target |
| 85 |
continue |
| 86 |
|
| 87 |
assert self.app.env |
| 88 |
|
| 89 |
# wildcarded source, expand to docnames |
| 90 |
expanded_docs = [ |
| 91 |
doc for doc in self.app.env.found_docs if fnmatch(doc, source) |
| 92 |
] |
| 93 |
|
| 94 |
if not expanded_docs: |
| 95 |
logger.warning(f"No documents match to '{source}' redirect.") |
| 96 |
continue |
| 97 |
|
| 98 |
for doc in expanded_docs: |
| 99 |
new_target = self._apply_placeholders(doc, target) |
| 100 |
to_be_redirected[doc] = new_target |
| 101 |
|
| 102 |
return to_be_redirected |
| 103 |
|
| 104 |
def docname_out_path(self, docname: str, suffix: str) -> Sequence[str]: |
| 105 |
""" |
| 106 |
For a Sphinx docname (the path to a source document without suffix), |
| 107 |
returns path to outfile that would be created by the used builder. |
| 108 |
""" |
| 109 |
# Return as-is, if the docname already has been passed with a suffix |
| 110 |
if docname.endswith(suffix): |
| 111 |
return [docname] |
| 112 |
|
| 113 |
# Remove any trailing slashes, except for "/"" index |
| 114 |
if len(docname) > 1 and docname.endswith(SEP): |
| 115 |
docname = docname.rstrip(SEP) |
| 116 |
|
| 117 |
# Figure out whether we have dirhtml builder |
| 118 |
out_uri = self.app.builder.get_target_uri(docname=docname) # type: ignore |
| 119 |
|
| 120 |
if not out_uri.endswith(suffix): |
| 121 |
# If dirhtml builder is used, need to append "index" |
| 122 |
return [out_uri, "index"] |
| 123 |
|
| 124 |
# Otherwise, convert e.g. 'source' to 'source.html' |
| 125 |
return [out_uri] |
| 126 |
|
| 127 |
def create_redirects(self, to_be_redirected: Mapping[str, str]) -> None: |
| 128 |
"""Create actual redirect file for each pair in passed mapping of |
| 129 |
docnames to targets.""" |
| 130 |
|
| 131 |
# Corresponds to value of `html_file_suffix`, but takes into account |
| 132 |
# modifications done by the builder class |
| 133 |
try: |
| 134 |
suffix = self.app.builder.out_suffix # type: ignore |
| 135 |
except Exception: |
| 136 |
suffix = ".html" |
| 137 |
|
| 138 |
for docname, target in to_be_redirected.items(): |
| 139 |
out = self.docname_out_path(docname, suffix) |
| 140 |
redirect_file_abs = Path(self.app.outdir).joinpath(*out).with_suffix(suffix) |
| 141 |
|
| 142 |
redirect_file_rel = redirect_file_abs.relative_to(self.app.outdir) |
| 143 |
|
| 144 |
if redirect_file_abs.exists(): |
| 145 |
logger.info( |
| 146 |
f"Overwriting '{redirect_file_rel}' with redirect to '{target}'." |
| 147 |
) |
| 148 |
else: |
| 149 |
logger.info(f"Creating redirect '{redirect_file_rel}' to '{target}'.") |
| 150 |
|
| 151 |
self._create_redirect_file(redirect_file_abs, target) |
| 152 |
|
| 153 |
@staticmethod |
| 154 |
def _contains_wildcard(text: str) -> bool: |
| 155 |
"""Tells whether passed argument contains wildcard characters.""" |
| 156 |
return bool(wildcard_pattern.search(text)) |
| 157 |
|
| 158 |
@staticmethod |
| 159 |
def _apply_placeholders(source: str, target: str) -> str: |
| 160 |
"""Expand "source" placeholder in target and return it""" |
| 161 |
return Template(target).substitute({"source": source}) |
| 162 |
|
| 163 |
def _create_redirect_file(self, at_path: Path, to_uri: str) -> None: |
| 164 |
"""Actually create a redirect file according to redirect template""" |
| 165 |
|
| 166 |
content = self._render_redirect_template(to_uri) |
| 167 |
|
| 168 |
# create any missing parent folders |
| 169 |
at_path.parent.mkdir(parents=True, exist_ok=True) |
| 170 |
|
| 171 |
at_path.write_text(content, encoding="utf-8") |
| 172 |
|
| 173 |
def _render_redirect_template(self, to_uri: str) -> str: |
| 174 |
# HTML used as redirect file content |
| 175 |
redirect_template = REDIRECT_FILE_DEFAULT_TEMPLATE |
| 176 |
if self.template_file_option: |
| 177 |
redirect_file_abs = Path(self.app.srcdir, self.template_file_option) |
| 178 |
redirect_template = redirect_file_abs.read_text(encoding="utf-8") |
| 179 |
|
| 180 |
return Template(redirect_template).substitute({"to_uri": to_uri}) |
| 181 |
|
| 182 |
|
| 183 |
def collect_redirects_for_linkcheck(app): |
| 184 |
# Ignore when not invoked with linkcheck builder |
| 185 |
if not isinstance(app.builder, CheckExternalLinksBuilder): |
| 186 |
return |
| 187 |
|
| 188 |
redirects = Reredirects(app).grab_redirects() |
| 189 |
|
| 190 |
for docname, target in redirects.items(): |
| 191 |
# Give a Sphinx or extensions change to modify original target URL |
| 192 |
if new_target := app.emit_firstresult("linkcheck-process-uri", target): |
| 193 |
target = new_target |
| 194 |
|
| 195 |
if urlparse(target).scheme not in ("http", "https"): |
| 196 |
# Checking redirects to other pages of the same documentation is not |
| 197 |
# supported for now. |
| 198 |
continue |
| 199 |
|
| 200 |
# Add target external URL to hyperlinks which linkcheck builder will check |
| 201 |
docpath = app.env.doc2path(docname) |
| 202 |
hyperlink = Hyperlink(uri=target, docname=docname, docpath=docpath, lineno=-1) |
| 203 |
app.builder.hyperlinks[target] = hyperlink |