__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 = {} 96 97def add_page(self, location, page): 98if location.endswith("/"): 99location += "index.html" 100location = location.lstrip("/") # interpret it as site root, not OS root 101self.pages[location] = page 102 103def add_from_index(self, index, location, template, static=False, **kwargs): 104location = location.lstrip("/") # interpret it as site root, not OS root 105if static: 106for document in index: 107self.pages[os.path.join(location, document.file_name)] = Static(self, document) 108else: 109for document in index: 110self.pages[os.path.join(location, document.file_name)] = Page(self, template, os.path.join(index.directory, document), **kwargs) 111 112def filter(self, name): 113def decorator(func): 114self.template_engine.filters[name] = func 115return func 116 117return decorator 118 119def build(self): 120# Clear the build directory if it exists. 121if os.path.isdir(self.build_dir): 122delete_directory_contents(self.build_dir) 123for location, page in self.pages.items(): 124# Create the required directories. 125os.makedirs(os.path.join(self.build_dir, os.path.dirname(location)), exist_ok=True) 126if isinstance(page, str): 127with open(os.path.join(self.build_dir, location), "w") as f: 128f.write(page) 129elif isinstance(page, bytes): 130with open(os.path.join(self.build_dir, location), "wb") as f: 131f.write(page) 132else: 133raise ValueError(f"{type(page)} cannot be used as a document") 134 135 136class Page(str): 137def __new__(cls, site, template, document, **kwargs): 138return site.template_engine.get_template(template).render(document=document, **kwargs) 139 140 141class Static(bytes): 142def __new__(cls, site, document): 143return document.content 144