__init__.py
Python script, ASCII text executable
1#!/usr/bin/env python3 2 3import os 4import jinja2 5from ruamel.yaml import YAML 6import shutil 7import contextlib 8 9 10@contextlib.contextmanager 11def in_directory(directory): 12cwd = os.getcwd() 13os.chdir(directory) 14try: 15yield 16finally: 17os.chdir(cwd) 18 19 20def delete_directory_contents(directory): 21for root, dirs, files in os.walk(directory): 22for file in files: 23os.remove(os.path.join(root, file)) 24for dir in dirs: 25shutil.rmtree(os.path.join(root, dir)) 26 27 28class Document: 29def __init__(self, file_name): 30self.file_name = file_name 31self.encoding = "utf-8" 32# If the file is text, read it. 33self.front_matter = YAML() 34try: 35with open(file_name, "r", encoding=self.encoding) as f: 36print("!" + f"Loading document {file_name}".center(80, "-") + "!") 37 38# Parse front matter if available. 39front_matter = "" 40initial_line = f.readline() 41if initial_line == "---\n": 42print("!" + "Front matter found".center(80, "-") + "!") 43line = "" 44while line != "---\n": 45line = f.readline() 46if line != "---\n": 47front_matter += line 48print("!" + "Front matter loaded".center(80, "-") + "!") 49print(front_matter) 50 51if front_matter: 52self.front_matter = self.front_matter.load(front_matter) 53 54print("!" + "Reading content".center(80, "-") + "!") 55 56self.content = initial_line + f.read() 57 58print("!" + "Content loaded".center(80, "-") + "!") 59print(self.content) 60except UnicodeDecodeError: 61print("!" + "Text decoding failed, assuming binary.".center(80, "-") + "!") 62self.encoding = None 63with open(file_name, "rb") as f: 64self.content = f.read() 65print("!" + "Binary content loaded".center(80, "-") + "!") 66 67 68class Index: 69def __init__(self, directory, recursive=False): 70self.directory = directory 71# Temporarily move to the specified directory in order to read the files. 72with in_directory(directory): 73if recursive: 74self.file_names = [os.path.join(dir_path, f) for dir_path, dir_name, filenames in os.walk(".") for f in filenames] 75else: 76self.file_names = [i for i in os.listdir() if os.path.isfile(i)] 77self.documents = [Document(i) for i in self.file_names] 78self.__current_index = 0 79 80def __iter__(self): 81return self 82 83def __next__(self): 84if self.__current_index >= len(self.documents): 85raise StopIteration 86else: 87self.__current_index += 1 88return self.documents[self.__current_index - 1] 89 90 91class Site: 92def __init__(self, build_dir, template_dir="templates"): 93self.build_dir = build_dir 94self.template_engine = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir)) 95self.pages = {} 96self.context = {} 97 98def add_page(self, location, page): 99if location.endswith("/"): 100location += "index.html" 101location = location.lstrip("/") # interpret it as site root, not OS root 102self.pages[location] = page 103 104def add_from_index(self, index, location, template, static=False, **kwargs): 105location = location.lstrip("/") # interpret it as site root, not OS root 106kwargs = {**self.context, **kwargs} 107if static: 108for document in index: 109self.pages[os.path.join(location, document.file_name)] = Static(self, document) 110else: 111for document in index: 112self.pages[os.path.join(location, document.file_name)] = Page(self, template, os.path.join(index.directory, document), **kwargs) 113 114def filter(self, name): 115def decorator(func): 116self.template_engine.filters[name] = func 117return func 118 119return decorator 120 121def build(self): 122# Clear the build directory if it exists. 123if os.path.isdir(self.build_dir): 124delete_directory_contents(self.build_dir) 125for location, page in self.pages.items(): 126# Create the required directories. 127os.makedirs(os.path.join(self.build_dir, os.path.dirname(location)), exist_ok=True) 128if isinstance(page, str): 129with open(os.path.join(self.build_dir, location), "w") as f: 130f.write(page) 131elif isinstance(page, bytes): 132with open(os.path.join(self.build_dir, location), "wb") as f: 133f.write(page) 134else: 135raise ValueError(f"{type(page)} cannot be used as a document") 136 137 138class Page(str): 139def __new__(cls, site, template, document, **kwargs): 140kwargs = {**site.context, **kwargs} 141return site.template_engine.get_template(template).render(document=document, **kwargs) 142 143 144class Static(bytes): 145def __new__(cls, site, document): 146return document.content 147