9
9
import requests
10
10
from requests .exceptions import ConnectionError , HTTPError , RetryError
11
11
from sphinx .application import Sphinx
12
+ from sphinx .builders .dirhtml import DirectoryHTMLBuilder
12
13
from sphinx .errors import ExtensionError
13
14
14
15
from . import edit_this_page , logo , pygment , short_link , toctree , translator , utils
@@ -215,6 +216,30 @@ def update_and_remove_templates(
215
216
context ["theme_version" ] = __version__
216
217
217
218
219
+ def _fix_canonical_url (
220
+ app : Sphinx , pagename : str , templatename : str , context : dict , doctree
221
+ ) -> None :
222
+ """Fix the canonical URL when using the dirhtml builder.
223
+
224
+ Sphinx builds a canonical URL if ``html_baseurl`` config is set. However,
225
+ it builds a URL ending with ".html" when using the dirhtml builder, which is
226
+ incorrect. Detect this and generate the correct URL for each page.
227
+
228
+ Workaround for https://github.com/sphinx-doc/sphinx/issues/9730; can be removed
229
+ when that is fixed, released, and available in our minimum supported Sphinx version.
230
+ """
231
+ if (
232
+ not app .config .html_baseurl
233
+ or not isinstance (app .builder , DirectoryHTMLBuilder )
234
+ or not context ["pageurl" ]
235
+ or not context ["pageurl" ].endswith (".html" )
236
+ ):
237
+ return
238
+
239
+ target = app .builder .get_target_uri (pagename )
240
+ context ["pageurl" ] = app .config .html_baseurl + target
241
+
242
+
218
243
def setup (app : Sphinx ) -> Dict [str , str ]:
219
244
"""Setup the Sphinx application."""
220
245
here = Path (__file__ ).parent .resolve ()
@@ -226,6 +251,7 @@ def setup(app: Sphinx) -> Dict[str, str]:
226
251
227
252
app .connect ("builder-inited" , translator .setup_translators )
228
253
app .connect ("builder-inited" , update_config )
254
+ app .connect ("html-page-context" , _fix_canonical_url )
229
255
app .connect ("html-page-context" , edit_this_page .setup_edit_url )
230
256
app .connect ("html-page-context" , toctree .add_toctree_functions )
231
257
app .connect ("html-page-context" , update_and_remove_templates )
0 commit comments