| 1 |
import re |
| 2 |
from fnmatch import fnmatch |
| 3 |
from pathlib import Path |
| 4 |
from string import Template |
| 5 |
from typing import Dict, Mapping, Optional, Sequence |
| 6 |
|
| 7 |
from sphinx.application import Sphinx |
| 8 |
from sphinx.util import logging |
| 9 |
from sphinx.util.osutil import SEP |
| 10 |
|
| 11 |
OPTION_REDIRECTS = "redirects" |
| 12 |
OPTION_REDIRECTS_DEFAULT: Dict[str, str] = {} |
| 13 |
|
| 14 |
OPTION_TEMPLATE_FILE = "redirect_html_template_file" |
| 15 |
OPTION_TEMPLATE_FILE_DEFAULT = None |
| 16 |
|
| 17 |
REDIRECT_FILE_DEFAULT_TEMPLATE = '<html><head><meta http-equiv="refresh" content="0; url=${to_uri}"></head></html>' # noqa: E501 |
| 18 |
|
| 19 |
logger = logging.getLogger(__name__) |
| 20 |
|
| 21 |
wildcard_pattern = re.compile(r"[\*\?\[\]]") |
| 22 |
|
| 23 |
|
| 24 |
def setup(app: Sphinx) -> Dict: |
| 25 |
""" |
| 26 |
Extension setup, called by Sphinx |
| 27 |
""" |
| 28 |
app.connect("html-collect-pages", init) |
| 29 |
app.add_config_value(OPTION_REDIRECTS, OPTION_REDIRECTS_DEFAULT, "env") |
| 30 |
app.add_config_value(OPTION_TEMPLATE_FILE, OPTION_TEMPLATE_FILE_DEFAULT, "env") |
| 31 |
return dict(parallel_read_safe=True) |
| 32 |
|
| 33 |
|
| 34 |
def init(app: Sphinx) -> Optional[Sequence]: |
| 35 |
if not app.config[OPTION_REDIRECTS]: |
| 36 |
logger.debug("No redirects configured") |
| 37 |
return [] |
| 38 |
|
| 39 |
rr = Reredirects(app) |
| 40 |
to_be_redirected = rr.grab_redirects() |
| 41 |
rr.create_redirects(to_be_redirected) |
| 42 |
|
| 43 |
# html-collect-pages requires to return iterable of pages to write, |
| 44 |
# we have no additional pages to write |
| 45 |
return [] |
| 46 |
|
| 47 |
|
| 48 |
class Reredirects: |
| 49 |
def __init__(self, app: Sphinx) -> None: |
| 50 |
self.app = app |
| 51 |
self.redirects_option: Dict[str, str] = getattr(app.config, OPTION_REDIRECTS) |
| 52 |
self.template_file_option: str = getattr(app.config, OPTION_TEMPLATE_FILE) |
| 53 |
|
| 54 |
def grab_redirects(self) -> Mapping[str, str]: |
| 55 |
"""Inspect redirects option in conf.py and returns dict mapping \ |
| 56 |
docname to target (with expanded placeholder).""" |
| 57 |
# docname-target dict |
| 58 |
to_be_redirected = {} |
| 59 |
|
| 60 |
# For each source-target redirect pair in conf.py |
| 61 |
for source, target in self.redirects_option.items(): |
| 62 |
# no wildcard, append source as-is |
| 63 |
if not self._contains_wildcard(source): |
| 64 |
to_be_redirected[source] = target |
| 65 |
continue |
| 66 |
|
| 67 |
assert self.app.env |
| 68 |
|
| 69 |
# wildcarded source, expand to docnames |
| 70 |
expanded_docs = [ |
| 71 |
doc for doc in self.app.env.found_docs if fnmatch(doc, source) |
| 72 |
] |
| 73 |
|
| 74 |
if not expanded_docs: |
| 75 |
logger.warning(f"No documents match to '{source}' redirect.") |
| 76 |
continue |
| 77 |
|
| 78 |
for doc in expanded_docs: |
| 79 |
new_target = self._apply_placeholders(doc, target) |
| 80 |
to_be_redirected[doc] = new_target |
| 81 |
|
| 82 |
return to_be_redirected |
| 83 |
|
| 84 |
def docname_out_path(self, docname: str, suffix: str) -> Sequence[str]: |
| 85 |
""" |
| 86 |
For a Sphinx docname (the path to a source document without suffix), |
| 87 |
returns path to outfile that would be created by the used builder. |
| 88 |
""" |
| 89 |
# Return as-is, if the docname already has been passed with a suffix |
| 90 |
if docname.endswith(suffix): |
| 91 |
return [docname] |
| 92 |
|
| 93 |
# Remove any trailing slashes, except for "/"" index |
| 94 |
if len(docname) > 1 and docname.endswith(SEP): |
| 95 |
docname = docname.rstrip(SEP) |
| 96 |
|
| 97 |
# Figure out whether we have dirhtml builder |
| 98 |
out_uri = self.app.builder.get_target_uri(docname=docname) # type: ignore |
| 99 |
|
| 100 |
if not out_uri.endswith(suffix): |
| 101 |
# If dirhtml builder is used, need to append "index" |
| 102 |
return [out_uri, "index"] |
| 103 |
|
| 104 |
# Otherwise, convert e.g. 'source' to 'source.html' |
| 105 |
return [out_uri] |
| 106 |
|
| 107 |
def create_redirects(self, to_be_redirected: Mapping[str, str]) -> None: |
| 108 |
"""Create actual redirect file for each pair in passed mapping of \ |
| 109 |
docnames to targets.""" |
| 110 |
|
| 111 |
# Corresponds to value of `html_file_suffix`, but takes into account |
| 112 |
# modifications done by the builder class |
| 113 |
try: |
| 114 |
suffix = self.app.builder.out_suffix # type: ignore |
| 115 |
except Exception: |
| 116 |
suffix = ".html" |
| 117 |
|
| 118 |
for docname, target in to_be_redirected.items(): |
| 119 |
out = self.docname_out_path(docname, suffix) |
| 120 |
redirect_file_abs = Path(self.app.outdir).joinpath(*out).with_suffix(suffix) |
| 121 |
|
| 122 |
redirect_file_rel = redirect_file_abs.relative_to(self.app.outdir) |
| 123 |
|
| 124 |
if redirect_file_abs.exists(): |
| 125 |
logger.info( |
| 126 |
f"Overwriting '{redirect_file_rel}' with redirect to '{target}'." |
| 127 |
) |
| 128 |
else: |
| 129 |
logger.info(f"Creating redirect '{redirect_file_rel}' to '{target}'.") |
| 130 |
|
| 131 |
self._create_redirect_file(redirect_file_abs, target) |
| 132 |
|
| 133 |
@staticmethod |
| 134 |
def _contains_wildcard(text: str) -> bool: |
| 135 |
"""Tells whether passed argument contains wildcard characters.""" |
| 136 |
return bool(wildcard_pattern.search(text)) |
| 137 |
|
| 138 |
@staticmethod |
| 139 |
def _apply_placeholders(source: str, target: str) -> str: |
| 140 |
"""Expand "source" placeholder in target and return it""" |
| 141 |
return Template(target).substitute({"source": source}) |
| 142 |
|
| 143 |
def _create_redirect_file(self, at_path: Path, to_uri: str) -> None: |
| 144 |
"""Actually create a redirect file according to redirect template""" |
| 145 |
|
| 146 |
content = self._render_redirect_template(to_uri) |
| 147 |
|
| 148 |
# create any missing parent folders |
| 149 |
at_path.parent.mkdir(parents=True, exist_ok=True) |
| 150 |
|
| 151 |
at_path.write_text(content) |
| 152 |
|
| 153 |
def _render_redirect_template(self, to_uri: str) -> str: |
| 154 |
# HTML used as redirect file content |
| 155 |
redirect_template = REDIRECT_FILE_DEFAULT_TEMPLATE |
| 156 |
if self.template_file_option: |
| 157 |
redirect_file_abs = Path(self.app.srcdir, self.template_file_option) |
| 158 |
redirect_template = redirect_file_abs.read_text() |
| 159 |
|
| 160 |
content = Template(redirect_template).substitute({"to_uri": to_uri}) |
| 161 |
|
| 162 |
return content |