Skip to content

Commit 6bb2816

Browse files
authored
Merge pull request #108 from hugovk/add-hash-digest-to-css
Append a hash ?digest to CSS files for cache-busting
2 parents b84c913 + 6e3e8f0 commit 6bb2816

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

python_docs_theme/__init__.py

+51
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,62 @@
1+
import hashlib
12
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+
)
251

352

453
def setup(app):
554
current_dir = os.path.abspath(os.path.dirname(__file__))
655
app.add_html_theme(
756
'python_docs_theme', current_dir)
857

58+
app.connect("html-page-context", _html_page_context)
59+
960
return {
1061
'parallel_read_safe': True,
1162
'parallel_write_safe': True,

python_docs_theme/theme.conf

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[theme]
22
inherit = default
3-
stylesheet = pydoctheme.css?2022.1
3+
stylesheet = pydoctheme.css
44
pygments_style = default
55

66
[options]

0 commit comments

Comments
 (0)