-
Notifications
You must be signed in to change notification settings - Fork 0
/
makesite.py
406 lines (346 loc) · 14 KB
/
makesite.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
"""
Script to build a website from a bunch of markdown files.
Inspired by https://github.com/sunainapai/makesite
Tweaked for almarklein.org
Then for pygfx.org
"""
import os
import shutil
import webbrowser
import markdown
import pygments
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name
TITLE = "pygfx.org"
NAV = {
"Main": "index",
"Sponsor": "sponsor",
# "Blog": "blog",
# "Archive": "archive",
# "Social": {
# 'Twitter': 'https://twitter.com/pygfx',
# },
}
NEWS = {
"Released pygfx v0.5.0": "https://github.com/pygfx/pygfx/releases/tag/v0.5.0",
"Released wgpu-py v0.18.1": "https://github.com/pygfx/wgpu-py/releases/tag/v0.18.1",
}
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
OUT_DIR = os.path.join(THIS_DIR, "output")
STATIC_DIR = os.path.join(THIS_DIR, "static")
PAGES_DIR = os.path.join(THIS_DIR, "pages")
POSTS_DIR = os.path.join(THIS_DIR, "posts")
REDIRECT = '<html><head><meta HTTP-EQUIV="REFRESH" content="0; url=URL"></head></html>'
def create_menu(page):
""" Create the menu for the given page.
"""
menu = ""
if True:
menuitems = []
menuitems.append('<span class="header">Pages</span>')
for title, target in NAV.items():
if isinstance(target, str):
if target.startswith(("https://", "http://", "/")):
menuitems.append(f"<a href='{target}'>{title}</a>")
else:
menuitems.append(f"<a href='{target}.html'>{title}</a>")
if target == page.name:
menuitems[-1] = menuitems[-1].replace("<a ", '<a class="current" ')
elif isinstance(target, dict):
menuitems.append(f"<a href='{target.get('', '#')}.html'>{title}</a>")
if target.get("", None) == page.name:
menuitems[-1] = menuitems[-1].replace("<a ", '<a class="current" ')
if True: # any(page.name == subtarget for subtarget in target.values()):
for subtitle, subtarget in target.items():
if not subtitle:
continue
if subtarget.startswith(("https://", "http://", "/")):
menuitems.append(f"<a class='sub' href='{subtarget}'>{subtitle}</a>")
else:
menuitems.append(
f"<a class='sub' href='{subtarget}.html'>{subtitle}</a>"
)
if subtarget == page.name:
menuitems[-1] = menuitems[-1].replace("class='", "class='current ")
else:
raise RuntimeError(f"Unexpected NAV entry {type(target)}")
menu += "<div class='block1'>"
menu += "<br>".join(menuitems)
menu += "</div>"
subtitles = [title for level, title in page.headers if level == 2]
if subtitles:
menuitems = []
menuitems.append("<span class='header'>Current page</span>")
menuitems += [
f"<a class='sub' href='#{title.lower()}'>{title}</a>" for title in subtitles
]
menu += "<br>"
menu += "<div class='block2'>"
menu += "<br>".join(menuitems)
menu += "</div>"
# if NEWS:
# menuitems = []
# menuitems.append('<br /><span class="header">News</span>')
# for title, url in NEWS.items():
# # menuitems.append(f"<a class='sub' href='{url}'>{title}</a>")
# menuitems.append(f"<a href='{url}'>{title}</a>")
return menu
def create_blog_relatated_pages(posts):
""" Create blog overview page.
"""
# Filter and sort
posts = [
post for post in posts.values() if post.date and not post.name.startswith("_")
]
posts.sort(key=lambda p: p.date)
blogpages = {}
# Generate overview page
html = ["<h1>Blog</h1>"]
for page in reversed(posts):
text = page.md
if "<!-- END_SUMMARY -->" in text:
summary = text.split("<!-- START_SUMMARY -->")[-1].split(
"<!-- END_SUMMARY -->"
)[0]
else:
summary = text.split("## ")[0]
summary = summary.split("-->")[-1]
# html.append("<hr />" + page.date_and_tags_html)
html.append("<div style='border-top: 1px solid #ddd;'>" + page.date_and_tags_html + "</div>")
html.append(f'<a class="header" href="{page.name}.html"><h3>{page.title}</h3></a>')
if page.thumbnail:
html.append(f"<a href='{page.name}.html'><img src='{page.thumbnail}' class='thumb' /></a>")
# html.append(f'<h2>{page.title}</h2>')
html.append("<p>" + summary + "</p>")
html.append(f"<a href='{page.name}.html'>read more ...</a><br /><br />")
html.append("<div style='clear: both;'></div>")
blogpages["overview"] = "\n".join(html)
# Generate archive page
year = ""
html = ["<h1>Archive</h1>\n"]
for page in reversed(posts):
if page.date[:4] != year:
year = page.date[:4]
html.append(f"<h2>{year}</h2>")
html.append(f'{page.date}: <a href="{page.name}.html">{page.title}</a><br />')
blogpages["archive"] = "\n".join(html)
# todo: Generate page for each tag
return blogpages
def create_assets():
""" Returns a dict of all the assets representing the website.
"""
assets = {}
# Load all static files
for root, dirs, files in os.walk(STATIC_DIR):
for fname in files:
filename = os.path.join(root, fname)
with open(filename, "rb") as f:
assets[os.path.relpath(filename, STATIC_DIR)] = f.read()
# Collect pages
pages = {}
for fname in os.listdir(PAGES_DIR):
if fname.lower().endswith(".md"):
name = fname.split(".")[0].lower()
with open(os.path.join(PAGES_DIR, fname), "rb") as f:
md = f.read().decode()
pages[name] = Page(name, md)
# Collect blog posts
posts = {}
for fname in os.listdir(POSTS_DIR):
if fname.lower().endswith(".md"):
name = fname.split(".")[0].lower()
assert name not in pages, f"blog post slug not allowed: {name}"
with open(os.path.join(POSTS_DIR, fname), "rb") as f:
md = f.read().decode()
posts[name] = Page(name, md)
# Get template
with open(os.path.join(THIS_DIR, "template.html"), "rb") as f:
html_template = f.read().decode()
with open(os.path.join(THIS_DIR, "style.css"), "rb") as f:
css = f.read().decode()
css += "/* Pygments CSS */\n" + HtmlFormatter(style="vs").get_style_defs(
".highlight"
)
# Generate posts
for page in posts.values():
page.prepare(pages.keys())
title = page.title
menu = create_menu(page)
html = html_template.format(
title=title, style=css, body=page.to_html(), menu=menu
)
print("generating post", page.name + ".html")
assets[page.name + ".html"] = html.encode()
# Generate pages
for page in pages.values():
page.prepare(pages.keys())
title = TITLE if page.name == "index" else TITLE + " - " + page.title
menu = create_menu(page)
html = html_template.format(
title=title, style=css, body=page.to_html(), menu=menu
)
print("generating page", page.name + ".html")
assets[page.name + ".html"] = html.encode()
# Generate special pages
fake_md = "" # "##index\n## archive\n## tags"
for name, html in create_blog_relatated_pages(posts).items():
name = "blog" if name == "overview" else name
print("generating page", name + ".html")
assets[f"{name}.html"] = html_template.format(
title=TITLE, style=css, body=html, menu=create_menu(Page("", fake_md))
).encode()
# Backwards compat with previous site
for page in pages.values():
assets["pages/" + page.name + ".html"] = REDIRECT.replace(
"URL", f"/{page.name}.html"
).encode()
# Fix backslashes on Windows
for key in list(assets.keys()):
if "\\" in key:
assets[key.replace("\\", "/")] = assets.pop(key)
return assets
def main():
""" Main function that exports the page to the file system.
"""
# Create / clean output dir
if os.path.isdir(OUT_DIR):
shutil.rmtree(OUT_DIR)
os.mkdir(OUT_DIR)
# Write all assets to the directory
for fname, bb in create_assets().items():
filename = os.path.join(OUT_DIR, fname)
dirname = os.path.dirname(filename)
if not os.path.isdir(dirname):
os.makedirs(dirname)
with open(filename, "wb") as f:
f.write(bb)
class Page:
""" Representation of a page. It takes in markdown and produces HTML.
"""
def __init__(self, name, markdown):
self.name = name
self.md = markdown
self.parts = []
self.headers = []
self.title = name
if markdown.startswith("# "):
self.title = markdown.split("\n")[0][1:].strip()
self.date = None
if "<!-- DATE:" in markdown:
self.date = markdown.split("<!-- DATE:")[-1].split("-->")[0].strip() or None
if self.date is not None:
assert (
len(self.date) == 10 and self.date.count("-") == 2
), f"Weird date in {name}.md"
self.author = None
if "<!-- AURTHOR:" in markdown:
self.author = markdown.split("<!-- AURTHOR:")[-1].split("-->")[0].strip()
self.tags = []
if "<!-- TAGS:" in markdown:
self.tags = [
x.strip()
for x in markdown.split("<!-- TAGS:")[-1].split("-->")[0].split(",")
]
self.date_and_tags_html = ""
if self.date:
self.date_and_tags_html = f"<span class='post-date-tags'>{', '.join(self.tags)} - {self.date}</span>"
self.thumbnail = None
for fname in ["thumbs/" + self.name + ".jpg"]:
if os.path.isfile(os.path.join(THIS_DIR, "static", fname)):
self.thumbnail = fname
def prepare(self, page_names):
# Convert markdown to HTML
self.md = self._fix_links(self.md, page_names)
self.md = self._highlight(self.md)
self._split() # populates self.parts and self.headers
def _fix_links(self, text, page_names):
""" Fix the markdown links based on the pages that we know.
"""
for n in page_names:
text = text.replace(f"]({n})", f"]({n}.html)")
text = text.replace(f"]({n}.md)", f"]({n}.html)")
return text
def _highlight(self, text):
""" Apply syntax highlighting.
"""
lines = []
code = []
for i, line in enumerate(text.splitlines()):
if line.startswith("```"):
if code:
formatter = HtmlFormatter()
try:
lexer = get_lexer_by_name(code[0])
except Exception:
lexer = get_lexer_by_name("text")
lines.append(
pygments.highlight("\n".join(code[1:]), lexer, formatter)
)
code = []
else:
code.append(line[3:].strip()) # language
elif code:
code.append(line)
else:
lines.append(line)
return "\n".join(lines).strip()
def _split(self):
""" Split the markdown into parts based on sections.
Each part is either text or a tuple representing a section.
"""
text = self.md
self.parts = parts = []
self.headers = headers = []
lines = []
# Split in parts
for line in text.splitlines():
if line.startswith(("# ", "## ", "### ", "#### ", "##### ")):
# Finish pending lines
parts.append("\n".join(lines))
lines = []
# Process header
level = len(line.split(" ")[0])
title = line.split(" ", 1)[1]
title_short = "".join(c for c in title if ord(c) < 256).strip()
while "<i" in title_short:
i1 = title_short.find("<i")
i2 = title_short.find("</i>", i1)
title_short = title_short[:i1] + title_short[i2+4:]
title_short = title_short.split("(")[0].split("<")[0].strip().replace("`", "")
headers.append((level, title_short))
parts.append((level, title_short, title))
else:
lines.append(line)
parts.append("\n".join(lines))
# Now convert all text to html
for i in range(len(parts)):
if not isinstance(parts[i], tuple):
parts[i] = markdown.markdown(parts[i], extensions=[]) + "\n\n"
def to_html(self):
htmlparts = []
for part in self.parts:
if isinstance(part, tuple):
level, title_short, title = part
title_html = (
title.replace("``", "`")
.replace("`", "<code>", 1)
.replace("`", "</code>", 1)
)
ts = title_short.lower().replace(" ", "-")
if part[0] == 1:
htmlparts.append(self.date_and_tags_html)
htmlparts.append("<h1>%s</h1>" % title_html)
elif part[0] == 2 and title_short:
htmlparts.append(
"<a class='anch' name='{}' href='#{}'>".format(ts, ts)
)
htmlparts.append("<h%i>%s</h%i>" % (level, title_html, level))
htmlparts.append("</a>")
else:
htmlparts.append("<h%i>%s</h%i>" % (level, title_html, level))
else:
htmlparts.append(part)
return "\n".join(htmlparts)
if __name__ == "__main__":
main()
# webbrowser.open(os.path.join(OUT_DIR, "index.html"))