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