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