From 258d5540817bb441ef503374a7d9d0fcd6438dcc Mon Sep 17 00:00:00 2001 From: David Lord Date: Sun, 15 Oct 2023 03:33:57 -0700 Subject: [PATCH] Fix dirhtml canonical url (#727) --- src/furo/__init__.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/furo/__init__.py b/src/furo/__init__.py index 071e26cf..ec2a8b31 100644 --- a/src/furo/__init__.py +++ b/src/furo/__init__.py @@ -14,6 +14,7 @@ from pygments.formatters import HtmlFormatter from pygments.style import Style from pygments.token import Text +from sphinx.builders.dirhtml import DirectoryHTMLBuilder from sphinx.builders.html import StandaloneHTMLBuilder from sphinx.environment.adapters.toctree import TocTree from sphinx.errors import ConfigError @@ -178,6 +179,27 @@ def _add_asset_hashes(static: List[str], add_digest_to: List[str]) -> None: static[index].filename = _asset_hash(asset) # type: ignore[attr-defined] +def _fix_canonical_url( + app: sphinx.application.Sphinx, pagename: str, context: Dict[str, Any] +) -> None: + """Fix the canonical URL when using the dirhtml builder. + + Sphinx builds a canonical URL if ``html_baseurl`` config is set. However, + it builds a URL ending with ".html" when using the dirhtml builder, which is + incorrect. Detect this and generate the correct URL for each page. + """ + if ( + not app.config.html_baseurl + or not isinstance(app.builder, DirectoryHTMLBuilder) + or not context["pageurl"] + or not context["pageurl"].endswith(".html") + ): + return + + target = app.builder.get_target_uri(pagename) + context["pageurl"] = app.config.html_baseurl + target + + def _html_page_context( app: sphinx.application.Sphinx, pagename: str, @@ -196,6 +218,8 @@ def _html_page_context( ["scripts/furo.js"], ) + _fix_canonical_url(app, pagename, context) + # Basic constants context["furo_version"] = __version__