diff --git a/hooks/pygments-styles.py b/hooks/pygments-styles.py index 9252bdc..c0f093a 100644 --- a/hooks/pygments-styles.py +++ b/hooks/pygments-styles.py @@ -6,8 +6,9 @@ from minify_html import minify from mkdocs.utils import write_file, clean_directory PYGMENTS_STYLE_DIR = tempfile.mkdtemp() +PYGMENTS_STYLES_DEST = "assets/pygments.css" -def on_post_build(config): +def on_post_build(*args, **kwargs): clean_directory(PYGMENTS_STYLE_DIR) on_build_error = on_pre_build = on_post_build @@ -21,15 +22,15 @@ def minify_css(styles: str) -> str: def on_files(files, config): - style_file = os.path.join(PYGMENTS_STYLE_DIR, "pygments.css") + style_file = os.path.join(PYGMENTS_STYLE_DIR, PYGMENTS_STYLES_DEST) style = minify_css(HtmlFormatter(style="monokai").get_style_defs()) write_file(style.encode(), style_file) files.append(File( - path=os.path.basename(style_file), + path=PYGMENTS_STYLES_DEST, src_dir=PYGMENTS_STYLE_DIR, - dest_dir=os.path.join(config["site_dir"], "assets"), + dest_dir=config["site_dir"], use_directory_urls=False )) diff --git a/hooks/static.py b/hooks/static.py index d035fe2..f91a914 100644 --- a/hooks/static.py +++ b/hooks/static.py @@ -43,6 +43,7 @@ def on_files(files: Files, config): def on_env(env: jinja2.Environment, config, files): env.add_extension(make_static_extension(files)) + env.add_extension(make_sri_extension(files)) return env @@ -52,6 +53,20 @@ def make_static_extension(files: Files): def render(self, filename): file = files.get_file_from_path(filename) - return file.url + return f"/{file.url}" return StaticExtension + + +def make_sri_extension(files: Files): + class SRIExtension(StandaloneTag): + tags = {"sri_integrity"} + + def render(self, filename): + file = files.get_file_from_path(filename) + with open(file.abs_src_path, "rb") as f: + digest = hashlib.file_digest(f, "sha256").hexdigest() + + return f"sha256-{digest}" + + return SRIExtension diff --git a/hooks/tags.py b/hooks/tags.py index 6c9cb54..4cd3f36 100644 --- a/hooks/tags.py +++ b/hooks/tags.py @@ -5,7 +5,7 @@ import os TAGS_TEMP_DIR = tempfile.mkdtemp() -def on_post_build(config): +def on_post_build(*args, **kwargs): clean_directory(TAGS_TEMP_DIR) on_build_error = on_pre_build = on_post_build diff --git a/theme/main.html b/theme/main.html index c9a55c0..30f7f69 100644 --- a/theme/main.html +++ b/theme/main.html @@ -19,3 +19,6 @@ URL: {{ get_page_url("tags/tag1.md") }} Image resized: {{ "./assets/test.jpg"|resize_image(1500) }} Globals: {{ globals.foo }} + +Static path: {% static "assets/pygments.css" %} +SRI: {% sri_integrity "assets/pygments.css" %}