From ba36f9b92a4e5ca638f35a9ed5d6c75228de53ec Mon Sep 17 00:00:00 2001 From: Andrew Godwin Date: Sun, 27 Nov 2022 16:16:01 -0700 Subject: Fix Sphinx canonical links --- docs/extensions/canonical_fix.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 docs/extensions/canonical_fix.py (limited to 'docs/extensions') diff --git a/docs/extensions/canonical_fix.py b/docs/extensions/canonical_fix.py new file mode 100644 index 0000000..509a546 --- /dev/null +++ b/docs/extensions/canonical_fix.py @@ -0,0 +1,30 @@ +from sphinx.application import Sphinx +from sphinx.builders.dirhtml import DirectoryHTMLBuilder + + +def setup(app: Sphinx): + app.connect("html-page-context", canonical_url) + + +def canonical_url(app: Sphinx, pagename, templatename, context, doctree): + """Sphinx 1.8 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. + Also accepts the custom, deprecated ``canonical_url`` config as the + base URL. This will be removed in version 2.1. + """ + base = app.config.html_baseurl + + if ( + not base + or not isinstance(app.builder, DirectoryHTMLBuilder) + or not context["pageurl"] + or not context["pageurl"].endswith(".html") + ): + return + + # Fix pageurl for dirhtml builder if this version of Sphinx still + # generates .html URLs. + target = app.builder.get_target_uri(pagename) + context["pageurl"] = base + target -- cgit v1.2.3