bin/update_index.py (view raw)
1#!/usr/bin/env python3
2
3from markdown2 import markdown_path
4import os
5import fileinput
6import sys
7
8# change our cwd
9os.chdir("bin")
10
11blog = "../pages/blog/"
12
13# order files by recency
14def getrecents(path):
15 files = [path + f for f in os.listdir(blog) if f not in ["_index.md", "feed.xml"]]
16 files.sort(
17 key=lambda f: markdown_path(f, extras=["metadata"]).metadata["date"],
18 reverse=True,
19 )
20 return files
21
22
23def update_index(posts):
24 path = "../pages/_index.md"
25 with open(path, "r") as f:
26 md = f.readlines()
27 ruler = md.index("| :-- | --: |\n")
28 for post, i in zip(posts, range(5)):
29 md[ruler + i + 1] = post + "\n"
30
31 with open(path, "w") as f:
32 f.writelines(md)
33
34
35def update_blog(s):
36 path = "../pages/blog/_index.md"
37 s = s + "\n"
38 for l in fileinput.FileInput(path, inplace=1):
39 if "--:" in l:
40 l = l.replace(l, l + s)
41 print(l, end=""),
42
43
44top_five = []
45metas = []
46lines = []
47fnames = []
48
49for i in range(5):
50 top_five.append(getrecents(blog)[i])
51 metas.append(markdown_path(getrecents(blog)[i], extras=["metadata"]).metadata)
52 fnames.append(os.path.basename(os.path.splitext(getrecents(blog)[i])[0]))
53
54for meta, fname in zip(metas, fnames):
55 url = "/blog/" + fname
56 lines.append(f"| [{meta['title']}]({url}) | `{meta['date']}` |")
57
58update_index(lines)
59update_blog(lines[0])