-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen.py
66 lines (57 loc) · 2.09 KB
/
gen.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
import os, collections
from datetime import datetime
import markdown
import urllib.parse
cwd = os.getcwd()
template_dir = os.path.join(cwd, 'templates')
source_dir = os.path.join(cwd, 'source')
post_dir = os.path.join(cwd, 'posts')
class Templates:
def __init__(self, templ_dir):
self.templates = {}
files = [os.path.join(templ_dir, f) for f in os.listdir(templ_dir)]
for fil in files:
fn = os.path.basename(fil)
with open(fil, 'r') as f:
self.templates[fn] = f.read()
def get(self, key):
return self.templates[f'{key}.html']
def __str__(self):
ret = ''
for k, v in self.templates.items():
ret += f'{k}:\n{v}\n\n'
return ret
templates = Templates(template_dir)
# Read sources and generate posts
index = []
files = [os.path.join(source_dir, f) for f in os.listdir(source_dir)]
files.sort(key=lambda x: os.path.getmtime(x), reverse=True)
for fil in files:
edited = datetime.utcfromtimestamp(os.path.getmtime(fil))
fn = os.path.basename(fil).replace('.md', '')
fn_html = f'{fn}.html'
with open(fil, 'r') as inf:
text = inf.read()
html = markdown.markdown(text, extensions=['fenced_code'])
post_path = os.path.join(post_dir, fn_html)
with open(post_path, "w") as of:
of.write(''.join(
[
templates.get('header-post').replace('[title]', fn).replace('[edited]', f'{edited}'),
html,
templates.get('footer-post')
]))
print(f'Wrote {fn_html} | updated {edited}')
index.append({
'title': fn,
'path': post_path.replace(cwd, '.'),
'edited': str(edited),
})
# Generate index page
index_html = templates.get('header')
for item in index:
row = templates.get('row').replace('[path]', urllib.parse.quote(item['path'])).replace('[title]', item['title']).replace('[edited]', item['edited'])
index_html += row
index_html += templates.get('footer')
with open('index.html', 'w') as f:
f.write(index_html)