|
| 1 | +import hashlib |
1 | 2 | import os
|
| 3 | +from functools import lru_cache |
| 4 | +from pathlib import Path |
| 5 | +from typing import Any, Dict, List |
| 6 | + |
| 7 | +import sphinx.application |
| 8 | +from sphinx.builders.html import StandaloneHTMLBuilder |
| 9 | + |
| 10 | +THEME_PATH = Path(__file__).parent.resolve() |
| 11 | + |
| 12 | + |
| 13 | +@lru_cache(maxsize=None) |
| 14 | +def _asset_hash(path: str) -> str: |
| 15 | + """Append a `?digest=` to an url based on the file content.""" |
| 16 | + full_path = THEME_PATH / path.replace("_static/", "static/") |
| 17 | + digest = hashlib.sha1(full_path.read_bytes()).hexdigest() |
| 18 | + |
| 19 | + return f"{path}?digest={digest}" |
| 20 | + |
| 21 | + |
| 22 | +def _add_asset_hashes(static: List[str], add_digest_to: List[str]) -> None: |
| 23 | + for asset in add_digest_to: |
| 24 | + index = static.index(asset) |
| 25 | + static[index].filename = _asset_hash(asset) # type: ignore |
| 26 | + |
| 27 | + |
| 28 | +def _html_page_context( |
| 29 | + app: sphinx.application.Sphinx, |
| 30 | + pagename: str, |
| 31 | + templatename: str, |
| 32 | + context: Dict[str, Any], |
| 33 | + doctree: Any, |
| 34 | +) -> None: |
| 35 | + if app.config.html_theme != "python_docs_theme": |
| 36 | + return |
| 37 | + |
| 38 | + assert isinstance(app.builder, StandaloneHTMLBuilder) |
| 39 | + |
| 40 | + if "css_files" in context: |
| 41 | + if "_static/pydoctheme.css" not in context["css_files"]: |
| 42 | + raise ValueError( |
| 43 | + "This documentation is not using `pydoctheme.css` as the stylesheet. " |
| 44 | + "If you have set `html_style` in your conf.py file, remove it." |
| 45 | + ) |
| 46 | + |
| 47 | + _add_asset_hashes( |
| 48 | + context["css_files"], |
| 49 | + ["_static/pydoctheme.css"], |
| 50 | + ) |
2 | 51 |
|
3 | 52 |
|
4 | 53 | def setup(app):
|
5 | 54 | current_dir = os.path.abspath(os.path.dirname(__file__))
|
6 | 55 | app.add_html_theme(
|
7 | 56 | 'python_docs_theme', current_dir)
|
8 | 57 |
|
| 58 | + app.connect("html-page-context", _html_page_context) |
| 59 | + |
9 | 60 | return {
|
10 | 61 | 'parallel_read_safe': True,
|
11 | 62 | 'parallel_write_safe': True,
|
|
0 commit comments