1
Fork 0
mkdocs-site/hooks/pygments-styles.py
2023-09-15 22:29:43 +01:00

36 lines
1 KiB
Python

import tempfile
import os
from pygments.formatters.html import HtmlFormatter
from mkdocs.structure.files import File
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(*args, **kwargs):
clean_directory(PYGMENTS_STYLE_DIR)
on_build_error = on_pre_build = on_post_build
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):
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=PYGMENTS_STYLES_DEST,
src_dir=PYGMENTS_STYLE_DIR,
dest_dir=config["site_dir"],
use_directory_urls=False
))