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

36 lines
1,021 B
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 21:56:31 +01:00
def on_post_build(config):
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):
style_file = os.path.join(PYGMENTS_STYLE_DIR, "pygments.css")
style = minify_css(HtmlFormatter(style="monokai").get_style_defs())
write_file(style.encode(), style_file)
files.append(File(
path=os.path.basename(style_file),
src_dir=PYGMENTS_STYLE_DIR,
dest_dir=os.path.join(config["site_dir"], "assets"),
use_directory_urls=False
))