diff --git a/doc/sphinxext/redirect_from.py b/doc/sphinxext/redirect_from.py index 7a7e6aa9cdc8..37b56373a3bf 100644 --- a/doc/sphinxext/redirect_from.py +++ b/doc/sphinxext/redirect_from.py @@ -33,7 +33,7 @@ """ from pathlib import Path -from docutils.parsers.rst import Directive +from sphinx.util.docutils import SphinxDirective from sphinx.domains import Domain from sphinx.util import logging @@ -51,9 +51,9 @@ def setup(app): - RedirectFrom.app = app app.add_directive("redirect-from", RedirectFrom) app.add_domain(RedirectFromDomain) + app.connect("builder-inited", _clear_redirects) app.connect("build-finished", _generate_redirects) metadata = {'parallel_read_safe': True} @@ -73,8 +73,8 @@ def redirects(self): """The mapping of the redirects.""" return self.data.setdefault('redirects', {}) - def clear_doc(self, docnames): - self.redirects.clear() + def clear_doc(self, docname): + self.redirects.pop(docname, None) def merge_domaindata(self, docnames, otherdata): for src, dst in otherdata['redirects'].items(): @@ -86,15 +86,14 @@ def merge_domaindata(self, docnames, otherdata): f"{self.redirects[src]} and {otherdata['redirects'][src]}") -class RedirectFrom(Directive): +class RedirectFrom(SphinxDirective): required_arguments = 1 def run(self): redirected_doc, = self.arguments - env = self.app.env - domain = env.get_domain('redirect_from') - current_doc = env.path2doc(self.state.document.current_source) - redirected_reldoc, _ = env.relfn2path(redirected_doc, current_doc) + domain = self.env.get_domain('redirect_from') + current_doc = self.env.path2doc(self.state.document.current_source) + redirected_reldoc, _ = self.env.relfn2path(redirected_doc, current_doc) if redirected_reldoc in domain.redirects: raise ValueError( f"{redirected_reldoc} is already noted as redirecting to " @@ -119,3 +118,10 @@ def _generate_redirects(app, exception): logger.info('making refresh html file: %s redirect to %s', k, v) p.parent.mkdir(parents=True, exist_ok=True) p.write_text(html, encoding='utf-8') + + +def _clear_redirects(app): + domain = app.env.get_domain('redirect_from') + if domain.redirects: + logger.info('clearing cached redirects') + domain.redirects.clear()