# compiles the site import markdown import yaml import re import os import datetime import pytz import socket import shutil from jinja2 import Template def extract_metadata(md_content): match = re.match(r"^---\n(.*?)\n---\n(.*)", md_content, re.DOTALL) if match: metadata, content = match.groups() metadata_dict = yaml.safe_load(metadata) return metadata_dict, content return {}, md_content def get_template_filename(metadata): layout = metadata.get("layout", "default") # default to 'default' return f"{layout}.html" def convert_md_to_html(md_file, template): with open(md_file, "r", encoding="utf-8") as f: md_content = f.read() # extract metadata metadata, md_body = extract_metadata(md_content) # convert md to html html_content = markdown.markdown(md_body) # render the template rendered_html = template.render( title=metadata.get("title", "untitled"), content=html_content ) tz = pytz.timezone('UTC') build_date = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S %Z%z") hostname = socket.gethostname() rendered_html += f"\n" return rendered_html def compile_site(): if not os.path.exists("dist/"): os.makedirs("dist/") for filename in os.listdir("site/"): if filename.endswith(".md"): md_path = os.path.join("site/", filename) with open(md_path, "r", encoding="utf-8") as f: md_content = f.read() metadata, _ = extract_metadata(md_content) template_filename = get_template_filename(metadata) template_path = os.path.join("layouts/", template_filename) with open(template_path, "r", encoding="utf-8") as f: template = Template(f.read()) html_filename = filename.replace(".md", ".html") html_path = os.path.join("dist/", html_filename) html_content = convert_md_to_html(md_path, template) with open(html_path, "w", encoding="utf-8") as f: f.write(html_content) print(f"converted {md_path} -> {html_path} using template {template_filename}") assets_source = "assets" assets_dest = "dist/" + "assets" if os.path.exists(assets_source): shutil.copytree(assets_source, assets_dest, dirs_exist_ok=True) print(f"copied assets from {assets_source} to {assets_dest}") else: print(f"no assets folder found at {assets_source}") if __name__ == "__main__": compile_site()