1
Fork 0
mkdocs-site/hooks/pygments-styles.py

37 lines
1 KiB
Python
Raw Normal View History

2023-09-14 21:28:35 +01:00
import tempfile
import os
from pygments.formatters.html import HtmlFormatter
from mkdocs.structure.files import File
from minify_html import minify
2023-09-15 21:56:31 +01:00
from mkdocs.utils import write_file, clean_directory
2023-09-14 21:28:35 +01:00
PYGMENTS_STYLE_DIR = tempfile.mkdtemp()
2023-09-15 22:29:43 +01:00
PYGMENTS_STYLES_DEST = "assets/pygments.css"
2023-09-14 21:28:35 +01:00
2023-09-15 22:29:43 +01:00
def on_post_build(*args, **kwargs):
2023-09-15 21:56:31 +01:00
clean_directory(PYGMENTS_STYLE_DIR)
on_build_error = on_pre_build = on_post_build
2023-09-14 21:28:35 +01:00
def minify_css(styles: str) -> str:
wrapped_styles = f"<style>{styles}</styles>"
minified_styles = minify(wrapped_styles, minify_css=True, keep_comments=True)
return minified_styles.removeprefix("<style>").removesuffix("</style>")
def on_files(files, config):
2023-09-15 22:29:43 +01:00
style_file = os.path.join(PYGMENTS_STYLE_DIR, PYGMENTS_STYLES_DEST)
2023-09-14 21:28:35 +01:00
style = minify_css(HtmlFormatter(style="monokai").get_style_defs())
write_file(style.encode(), style_file)
files.append(File(
2023-09-15 22:29:43 +01:00
path=PYGMENTS_STYLES_DEST,
2023-09-14 21:28:35 +01:00
src_dir=PYGMENTS_STYLE_DIR,
2023-09-15 22:29:43 +01:00
dest_dir=config["site_dir"],
2023-09-14 21:28:35 +01:00
use_directory_urls=False
))