1
Fork 0

Add SRI extension

This commit is contained in:
Jake Howard 2023-09-15 22:29:43 +01:00
parent 425f87c609
commit c18f29bd39
Signed by: jake
GPG key ID: 57AFB45680EDD477
4 changed files with 25 additions and 6 deletions

View file

@ -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
))

View file

@ -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

View file

@ -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

View file

@ -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" %}