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