-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.py
326 lines (296 loc) · 11.8 KB
/
build.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# This code is licensed under the LGPL.
# The reason for such is that it allows for the use of it
# within proprietry applications.
#
# To view a copy of the LGPL, please refer to
# https://www.gnu.org/licenses/lgpl-3.0.en.html
from Renderers import RenderTemplate, RenderMarkdown
from sys import argv
from shutil import rmtree as DeleteDirectory
from os import mkdir as CreateDirectory, listdir as ListDirectory, unlink as DeleteFile
from os.path import isfile as IsFile, exists as PathExists
from distutils.dir_util import copy_tree as CopyDirectory
from datetime import datetime
from json import dump as DumpJSON
from yaml import safe_load as LoadYML
from re import sub as RegReplace
from typing import Literal
def GetCurTime():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
START_TIME = GetCurTime()
DEPLOY_BUILD_DIR = {
"gh-pages-deploy": "build",
"gl-pages-deploy": "public",
"cb-pages": "build",
} # Separate because this site is built with an action that won't work if they aren't
LOCAL_BUILD_DIR = "build"
PAGES_DEPLOY = argv[1] if len(argv) > 1 else None
BUILD_DIRECTORY = DEPLOY_BUILD_DIR[PAGES_DEPLOY] if PAGES_DEPLOY is not None else LOCAL_BUILD_DIR
PAGES = {
"index.html": "index.html",
"blog-list.html": "blog/index.html",
"blog-feed.rss": "blog/feed.rss",
"blog-feed.atom": "blog/feed.atom",
"404.html": "404.html",
"404.html": "not_found.html",
}
DISALLOWED_SITEMAP = {
"404.html",
"blog-feed.rss",
"blog-feed.atom",
"blog-list.html",
"index.html",
"not_found.html",
}
REDIRECTS = {
"link-tree.html": "/list/link-tree.html", # Old location -> new location
"extras.html": "https://steve0greatness.github.io/extras",
"guestbook.html": "https://steve0greatness.atabook.org/",
}
SITEMAP_HREF = "https://steve0greatness.nekoweb.org/"
sitemap = [
SITEMAP_HREF + "blog/",
SITEMAP_HREF,
]
def EscapeHTMLForRSS(HTML: str) -> str:
values = {
"&": "&", # & is first for a reason, do not change it's location.
"<": "<",
">": ">",
"§": "§",
}
RssHtml = HTML
for old, new in values.items():
RssHtml = RssHtml.replace(old, new)
return RssHtml
def WipeFinalDir():
if not PathExists(BUILD_DIRECTORY):
print("Directory didn't existing, creating it...")
CreateDirectory(BUILD_DIRECTORY)
return
print("Directory exists, wiping it...")
for item in ListDirectory(BUILD_DIRECTORY):
path = BUILD_DIRECTORY + "/" + item
if IsFile(path):
DeleteFile(path)
continue
DeleteDirectory(path)
def PostDateToDateObj(Date):
return datetime.strptime(Date, "%Y %b %d")
def PostSortHelper(Post):
return PostDateToDateObj(Post["date"])
def GetBlogList():
print("Grabbing post list")
PostSlugs: tuple[tuple[Literal["blog-posts", "drafts"], str], ...] = tuple( ("blog-posts", file) for file in ListDirectory("blog-posts") )
if not PAGES_DEPLOY and PathExists("drafts"):
PostSlugs = PostSlugs + tuple( ("drafts", file) for file in ListDirectory("drafts") )
Posts = []
for dir, slug in PostSlugs:
if not slug.endswith(".md"):
continue
print("Grabbing post list blog-posts/%s" % (slug))
with open(dir + "/" + slug, encoding="utf-8") as MDFile:
RawMD = MDFile.read()
PostHTML = RenderMarkdown(RawMD)
Item = PostHTML.metadata
Item["content"] = PostHTML
Item["raw-content"] = RawMD
Item["rss-content"] = EscapeHTMLForRSS(PostHTML)
Item["rss-post-time"] = PostDateToDateObj(Item["date"]).strftime("%a, %d %b %Y") + " 00:00:00 GMT"
Item["atom-post-time"] = PostDateToDateObj(Item["date"]).strftime("%Y-%m-%d") + "T00:00:00Z"
Item["opengraph-date"] = PostDateToDateObj(Item["date"]).strftime("%Y-%m-%d")
Item["opengraph-update"] = Item["opengraph-date"]
Item["atom-update-time"] = Item["atom-post-time"]
if "updated" in Item:
Item["atom-update-time"] = PostDateToDateObj(Item["updated"]).strftime("%Y-%m-%d") + "T00:00:00Z"
Item["opengraph-update"] = PostDateToDateObj(Item["updated"]).strftime("%Y-%m-%d")
Item["pathname"] = slug.replace(".md", ".html")
Item["plaintext"] = slug.replace(".md", ".txt")
Item["origin"] = slug
Item["is-draft"] = dir == "drafts"
Posts.append(Item)
PostsByDate = sorted(Posts, key=PostSortHelper, reverse=True)
return PostsByDate
PostList = []
def ListParseCategory(Obj, depth):
html = "<h%d id=\"%s\">%s</h%d>" % (2+depth, Obj["id"], Obj["title"], 2+depth)
if "paragraph" in Obj:
html += "<p>%s</p>" % Obj["paragraph"]
listType = "ul"
if "list-type" in Obj and Obj["list-type"] == "ordered":
listType = "ol"
html += "<%s>" % listType
for item in Obj["list"]:
html += "<li>" + LIST_PARSER_DICT[item["type"]](item, depth + 1) + "</li>"
html += "</%s>" % listType
return html
def ListParseLink(Obj, depth):
html = "<a href=\"%s\">" % Obj["href"]
text = Obj["text"]
if "text-type" in Obj and Obj["text-type"] == "text/markdown":
text = RenderMarkdown(text).replace("<p>", "").replace("</p>", "")
html += text + "</a>"
if "comment" in Obj:
html += "(%s)" % Obj["comment"]
return html
def ListParseText(Obj, depth):
text = Obj["text"]
# if "text-type" in Obj and Obj["text-type"] == "text/markdown":
# print(RenderMarkdown(text))
# text = RenderMarkdown(text) # this doesn't work???
if "comment" in Obj:
text += "(%s)" % Obj["comment"]
return text
LIST_PARSER_DICT = {
"category": ListParseCategory,
"link": ListParseLink,
"text": ListParseText,
}
def GetLists():
ListSlugs = ListDirectory("lists")
Lists = []
for slug in ListSlugs:
List = {
"title": "",
"content": "",
"filename": slug
}
with open("lists/" + slug, encoding="utf-8") as ListYML:
ListDict = LoadYML(ListYML.read())
List["title"] = ListDict["title"]
if "paragraph" in ListDict:
List["content"] += "<p>%s</p>" % ListDict["paragraph"]
List["content"] += "<ul>"
for item in ListDict["list"]:
List["content"] += "<li>" + LIST_PARSER_DICT[item["type"]](item, 0) + "</li>"
List["content"] += "</ul>"
Lists.append(List)
sitemap.append(SITEMAP_HREF + "list/" + slug)
sitemap.append(SITEMAP_HREF + "list/")
return Lists
def RenderPosts():
global PostList
for post in PostList:
Revised = post["updated"] if "updated" in post else False
RenderedHTML = RenderTemplate(
"blog-post.html",
Revised=Revised,
Title=post["title"],
PostDate=post["date"],
Content=post["content"],
PostPath=post["pathname"],
PlaintextPath=post["plaintext"],
IsDraft=post["is-draft"],
OpenGraphDate=post["opengraph-date"],
post=post,
CompileTime=GetCurTime(),
SiteCompileTime=START_TIME,
ViewName="blog-post.html"
)
print("Building blog-posts/%s to %s/blog/%s" % (post["origin"], BUILD_DIRECTORY, post["pathname"]))
with open(BUILD_DIRECTORY + "/blog/" + post["pathname"], "w", encoding="utf-8") as PostHTMLFile:
PostHTMLFile.write(RenderedHTML)
print("Copying blog-posts/%s to %s/blog/%s" % (post["origin"], BUILD_DIRECTORY, post["plaintext"]))
with open(BUILD_DIRECTORY + "/blog/" + post["plaintext"], "w", encoding="utf-8") as PostHTMLFile:
PostHTMLFile.write(post["raw-content"])
sitemap.append(SITEMAP_HREF + "blog/" + post["pathname"])
def RenderPage(PageInput: str, ContentDest: str, AllowSitemap: bool = True, **kwargs):
print("Building views/%s to %s/%s" % (PageInput, BUILD_DIRECTORY, ContentDest))
if AllowSitemap:
sitemap.append(SITEMAP_HREF + ContentDest)
with open(BUILD_DIRECTORY + "/" + ContentDest, "w", encoding="utf-8") as DestLocation:
DestLocation.write(RenderTemplate(PageInput, **kwargs))
def CreateJSONFeed():
global PostList
CreatedJSON = {
"version": "https://jsonfeed.org/version/1",
"title": "Steve0Greatness' Blog",
"home_page_url": "https://steve0greatness.nekoweb.org",
"feed_url": "https://steve0greatness.nekoweb.org/blog/feed.rss",
"language": "en-US",
"favicon": "https://steve0greatness.nekoweb.org/favicon.ico",
"description": "A blog by a human being.",
"authors": [
{
"name": "Steve0Greatness",
"url": "https://steve0greatness.nekoweb.org"
}
],
"items": []
}
for post in PostList:
CreatedJSON["items"].append({
"id": "https://steve0greatness.nekoweb.org/blog/" + post["pathname"],
"title": "JSON Feed version 1.1",
"icon": "https://steve0greatness.nekoweb.org/favicon.ico",
"content_html": post["content"],
"date_published": post["atom-post-time"],
"date_modified": post["atom-update-time"],
"url": "https://steve0greatness.nekoweb.org/blog/" + post["pathname"]
})
with open(BUILD_DIRECTORY + "/blog/feed.json", "w") as JSONFeedFile:
DumpJSON(CreatedJSON, JSONFeedFile)
def RenderLists():
Lists = GetLists()
CreateDirectory(BUILD_DIRECTORY + "/list/")
ListIndex = "<ul>"
for List in Lists:
FileLocation = "/list/" + List["filename"].replace(".yml", ".html")
Title = List["title"]
print("%s -> %s" % ("lists/" + List["filename"], BUILD_DIRECTORY + FileLocation))
with open(BUILD_DIRECTORY + FileLocation, "w") as file:
file.write(RenderTemplate(
"list.html",
Content=List["content"],
Title=Title,
Location=FileLocation,
CompileTime=GetCurTime(),
SiteCompileTime=START_TIME,
ViewName="blog-post.html"
))
ListIndex += "<li><a href=\"%s\">%s</a></li>" % (FileLocation, Title)
ListIndex += "</ul>"
print("Building list index")
with open(BUILD_DIRECTORY + "/list/index.html", "w") as file:
file.write(
RenderTemplate(
"list-index.html",
Content=ListIndex,
CompileTime="",
SiteCompileTime="",
ViewName="list-index.html"
)
)
def main():
global PostList
PostList = GetBlogList()
print("Wiping directory")
WipeFinalDir()
print("Creating blog holder")
CreateDirectory(BUILD_DIRECTORY + "/blog")
print("Rendering posts")
RenderPosts()
CreateJSONFeed()
print("Copying static directory")
CopyDirectory("static", BUILD_DIRECTORY)
print("Creating lists")
RenderLists()
print("Building pages")
for file, path in PAGES.items():
AllowSitemap = file not in DISALLOWED_SITEMAP
RenderPage(
file,
path,
AllowSitemap,
PostList=PostList,
CompileTime=GetCurTime(),
SiteCompileTime=START_TIME,
ViewName=file
)
print("Building redirects")
for OldLocation, NewLocation in REDIRECTS.items():
RenderPage("redirect.html", OldLocation, False, redirect=NewLocation, old=OldLocation)
with open(BUILD_DIRECTORY + "/sitemap.txt", "w") as SitemapFile:
SitemapFile.write("\n".join(sitemap))
if __name__ == "__main__":
main()