By using this site, you agree to have cookies stored on your device, strictly for functional purposes, such as storing your session and preferences.

Dismiss

 __init__.py

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