-
Notifications
You must be signed in to change notification settings - Fork 1
/
makesite.py
executable file
·325 lines (275 loc) · 11.8 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
#!/usr/bin/env python3
# BSD 3-Clause License
#
# Copyright (c) 2021, Timothy Trippel <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permisson.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# This software is a derivative of the original makesite.py.
# The license text of the original makesite.py is included below.
#
# The MIT License (MIT)
#
# Copyright (c) 2018 Sunaina Pai
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Make static personal website with Python."""
import argparse
import calendar
import collections
import datetime
import glob
import os
import re
import shutil
import sys
import hjson
def fread(filename):
"""Read file and close the file."""
with open(filename, 'r') as f:
return f.read()
def fwrite(filename, text):
"""Write content to file and close the file."""
basedir = os.path.dirname(filename)
if not os.path.isdir(basedir):
os.makedirs(basedir)
with open(filename, 'w') as f:
f.write(text)
def log(msg, *args):
"""Log message with specified arguments."""
sys.stderr.write(msg.format(*args) + '\n')
def read_headers(text):
"""Parse headers in text and yield (key, value, end-index) tuples."""
for match in re.finditer(r'\s*<!--\s*(.+?)\s*:\s*(.+?)\s*-->\s*|.+', text):
if not match.group(1):
break
yield match.group(1), match.group(2), match.end()
def rfc_2822_format(date_str):
"""Convert yyyy-mm-dd date string to RFC 2822 format date string."""
d = datetime.datetime.strptime(date_str, '%Y-%m-%d')
return d.strftime('%a, %d %b %Y %H:%M:%S +0000')
def markdown_2_html(filename, text):
"""Convert markdown text string to an HTML text string."""
try:
import commonmark
text = commonmark.commonmark(text)
except ImportError as e:
log('WARNING: Cannot render Markdown in {}: {}', filename, str(e))
return text
def read_content(filename):
"""Read content and metadata from file into a dictionary."""
# Read file content.
text = fread(filename)
# Read metadata and save it in a dictionary.
date_slug = os.path.basename(filename).split('.')[0]
match = re.search(r'^(?:((\d\d\d\d)-(\d\d)-(\d\d))-)?(.+)$', date_slug)
content = {
'date': match.group(1) or '1970-01-01',
'date_year': int(match.group(2) or '1970'),
'date_month': int(match.group(3) or '01'),
'date_month_abbr': calendar.month_abbr[int(match.group(3) or '01')],
'date_day': int(match.group(4) or '01'),
'slug': match.group(5),
}
# Update format of month abbreviation.
if len(calendar.month_name[content["date_month"]]) > 3:
if content["date_month_abbr"] == "Sep":
content["date_month_abbr"] += "t"
content["date_month_abbr"] += "."
# Read headers.
end = 0
for key, val, end in read_headers(text):
content[key] = val
# Separate content from headers.
text = text[end:]
# Convert Markdown content to HTML.
if filename.endswith(('.md', '.mkd', '.mkdn', '.mdown', '.markdown')):
text = markdown_2_html(filename, text)
# Update the dictionary with content and RFC 2822 date.
content.update({
'content': text,
'rfc_2822_date': rfc_2822_format(content['date'])
})
return content
def render(template, **params):
"""Replace placeholders in template with values from params."""
return re.sub(r'{{\s*([^}\s]+)\s*}}',
lambda match: str(params.get(match.group(1), match.group(0))),
template)
def make_list(src, item_layout, key, params):
"""Generate HTML list string from several (HTML/Markdown) content files."""
# Extract content from content files.
items = []
for content_file in glob.glob(src):
item_params = read_content(content_file)
# render any placeholders in the content itself.
item_params["content"] = render(item_params["content"], **params)
items.append(item_params)
# Sort items by date.
if "sort_order" in items[0]:
items.sort(key=lambda x: int(x["sort_order"]))
else:
items.sort(key=lambda x: (x["date_year"], x["date_month"], x["date_day"]),
reverse=True)
# Render items and build HTML string.
html_strs = []
num_item_types = collections.defaultdict(int)
for item_params in items:
log("Rendering list item => {}-{} ...", item_params["date"],
item_params["slug"])
# Count sub-types within a list (for publications).
if "type" in item_params:
num_item_types["num_%s" % item_params["type"]] += 1
# Combine content with a pre-defined HTML layout.
if item_layout is not None:
item_html_str = render(item_layout, **item_params)
# Content is the HTML string itself.
else:
item_html_str = render(item_params["content"], **item_params)
html_strs.append(item_html_str)
params["num_list_items"] = len(items)
params.update(num_item_types)
params[key] = "".join(html_strs)
def make_page(slug, layouts, **params):
"""Generate website page from layout and content directory."""
# Create deepcopy of params.
page_params = dict(params)
# Create src and dst paths.
content_glob = os.path.join("content", slug, "*")
dst_path = os.path.join(params["base_path"], slug + ".html")
# Render page with content from the content directory.
# Content directory contains only content that will form a list.
if params.get("list_only") is True:
make_list(content_glob, None, "content", page_params)
# Content directory contains singular and listable content.
else:
for src_path in glob.glob(content_glob):
# if we encounter a sub-directory, make a list from content files.
if os.path.isdir(src_path):
param = os.path.basename(src_path)
make_list(os.path.join(src_path, "*"), layouts[param], param,
page_params)
# Otherwise, content file will fill the placeholder in the
# layout with the same name as the content file slug.
else:
content = read_content(src_path)
rendered_content = render(content["content"], **page_params)
page_params[content["slug"]] = rendered_content
# Render homepage and write to file.
log('Rendering {} page => {}.html ...', slug, slug)
output = render(layouts[slug], **page_params)
fwrite(dst_path, output)
def load_layouts(src_glob, **params):
"""Load layouts into a dictionary with slugs as a key."""
layouts = {}
for layout_file in glob.glob(os.path.join(src_glob)):
slug = os.path.basename(layout_file)[:-5]
layouts[slug] = render(fread(layout_file), **params)
return layouts
def main(argv):
# Parse CMD line args.
parser = argparse.ArgumentParser()
parser.add_argument("--site-url", default=None)
args = parser.parse_args(argv)
# Create a new _site directory from scratch.
if os.path.isdir("_site"):
shutil.rmtree("_site")
shutil.copytree("static", "_site")
shutil.copytree("third_party", "_site/third_party")
# Default parameters.
params = {
"base_path": os.path.join(os.getcwd(), "_site"),
"current_year": datetime.datetime.now().year,
}
# If params.hjson exists, load it.
if os.path.isfile('params.hjson'):
params.update(hjson.loads(fread('params.hjson')))
# Check if overloading site URL
if args.site_url is not None:
params["site_url"] = args.site_url
# Load layouts.
layouts = load_layouts("layout/*/*.html", **params)
# Load shared content.
params.update(load_layouts("content/shared/*.html", **params))
# Combine layouts to form final layouts.
# Base page layout.
layouts["page"] = render(layouts["page"], nav=layouts["nav"])
# List item layouts.
layouts["past_jobs"] = render(layouts["past_jobs"], content=layouts["jobs"])
layouts["current_jobs"] = render(layouts["current_jobs"],
content=layouts["jobs"])
# Layouts of each page.
# TODO(timothytrippel): refactor setting the class of the current page to
# highlight the correct menu-item in the navbar. This is ugly ...
layouts["index"] = render(layouts["page"],
content=layouts["index"],
menu_item_index_class="currentmenu",
menu_item_publications_class="",
menu_item_experience_class="")
layouts["publications"] = render(layouts["page"],
content=layouts["publications"],
menu_item_index_class="",
menu_item_publications_class="currentmenu",
menu_item_research_class="",
menu_item_experience_class="")
layouts["experience"] = render(layouts["page"],
content=layouts["experience"],
menu_item_index_class="",
menu_item_publications_class="",
menu_item_research_class="",
menu_item_experience_class="currentmenu")
layouts["research"] = render(layouts["page"],
content=layouts["research"],
menu_item_index_class="",
menu_item_publications_class="",
menu_item_research_class="currentmenu",
menu_item_experience_class="")
# Create site pages.
make_page("index", layouts, **params)
make_page("experience", layouts, **params)
make_page("publications", layouts, list_only=True, **params)
make_page("research", layouts, **params)
if __name__ == '__main__':
main(sys.argv[1:])