bb0eb114021cc3dc9dcde76442bd8fcad92665c6
[books.alexwlchan.net] / scripts / render_html.py
1 #!/usr/bin/env python
2
3 import datetime
4 import os
5 import pathlib
6 import re
7 import subprocess
8 import sys
9
10 import attr
11 import frontmatter
12 import markdown
13 from markdown.extensions.smarty import SmartyExtension
14 from jinja2 import Environment, FileSystemLoader, select_autoescape
15
16
17 def rsync(dir1, dir2):
18     subprocess.check_call(["rsync", "--recursive", "--delete", dir1, dir2])
19
20
21 @attr.s
22 class Book:
23     title = attr.ib()
24     author = attr.ib()
25     publication_year = attr.ib()
26     cover_image = attr.ib()
27     cover_desc = attr.ib(default="")
28
29     isbn10 = attr.ib(default="")
30     isbn13 = attr.ib(default="")
31
32
33 @attr.s
34 class Review:
35     date_read = attr.ib()
36     rating = attr.ib()
37     text = attr.ib()
38     format = attr.ib()
39
40
41 @attr.s
42 class ReviewEntry:
43     path = attr.ib()
44     book = attr.ib()
45     review = attr.ib()
46
47     def out_path(self):
48         return self.path.relative_to("src").with_suffix("")
49
50
51 def get_review_entry_from_path(path):
52     post = frontmatter.load(path)
53
54     book = Book(**post["book"])
55     review = Review(**post["review"], text=post.content)
56
57     return ReviewEntry(path=path, book=book, review=review)
58
59
60 @attr.s
61 class CurrentlyReading:
62     text = attr.ib()
63
64
65 @attr.s
66 class CurrentlyReadingEntry:
67     path = attr.ib()
68     book = attr.ib()
69     reading = attr.ib()
70
71     def out_path(self):
72         return self.path.relative_to("src").with_suffix("")
73
74
75 def get_reading_entry_from_path(path):
76     post = frontmatter.load(path)
77
78     book = Book(**post["book"])
79     reading = CurrentlyReading(text=post.content)
80
81     return CurrentlyReadingEntry(path=path, book=book, reading=reading)
82
83
84 def get_reviews(dirpath, constructor):
85     for dirpath, _, filenames in os.walk(dirpath):
86         for f in filenames:
87             if not f.endswith(".md"):
88                 continue
89
90             path = pathlib.Path(dirpath) / f
91
92             try:
93                 yield constructor(path)
94             except Exception:
95                 print(f"Error parsing {path}", file=sys.stderr)
96                 raise
97
98
99 def render_markdown(text):
100     return markdown.markdown(text, extensions=[SmartyExtension()])
101
102
103 def render_date(date_value):
104     if isinstance(date_value, datetime.date):
105         return date_value.strftime("%d %B %Y")
106
107     date_match = re.match(
108         r"^(?P<year>\d{4})-(?P<month>\d{2})(?:-(?P<day>\d{2}))?$", date_value
109     )
110     assert date_match is not None, date_value
111
112     date_obj = datetime.datetime(
113         year=int(date_match.group("year")),
114         month=int(date_match.group("month")),
115         day=int(date_match.group("day") or "1"),
116     )
117
118     if date_match.group("day"):
119         return date_obj.strftime("%-d %B %Y")
120     else:
121         return date_obj.strftime("%B %Y")
122
123
124 def render_individual_review(env, *, review_entry):
125     template = env.get_template("review.html")
126     html = template.render(review_entry=review_entry)
127
128     out_name = review_entry.out_path() / "index.html"
129     out_path = pathlib.Path("_html") / out_name
130     out_path.parent.mkdir(exist_ok=True, parents=True)
131     out_path.write_text(html)
132
133
134 if __name__ == "__main__":
135     env = Environment(
136         loader=FileSystemLoader("templates"),
137         autoescape=select_autoescape(["html", "xml"]),
138     )
139
140     env.filters["render_markdown"] = render_markdown
141     env.filters["render_date"] = render_date
142
143     rsync("src/covers/", "_html/covers/")
144     rsync("static/", "_html/static/")
145
146     # Render the "all reviews page"
147
148     all_reviews = list(
149         get_reviews(dirpath="src/reviews", constructor=get_review_entry_from_path)
150     )
151     all_reviews = sorted(
152         all_reviews, key=lambda rev: str(rev.review.date_read), reverse=True
153     )
154
155     for review_entry in all_reviews:
156         render_individual_review(env, review_entry=review_entry)
157
158     template = env.get_template("list_reviews.html")
159     html = template.render(all_reviews=all_reviews)
160
161     out_path = pathlib.Path("_html") / "reviews/index.html"
162     out_path.write_text(html)
163
164     # Render the "currently reading" page
165
166     all_reading = list(
167         get_reviews(dirpath="src/currently_reading", constructor=get_reading_entry_from_path)
168     )
169
170     template = env.get_template("list_reading.html")
171     html = template.render(all_reading=all_reading)
172
173     out_path = pathlib.Path("_html") / "reading/index.html"
174     out_path.parent.mkdir(exist_ok=True, parents=True)
175     out_path.write_text(html)
176
177     # Render the front page
178
179     index_template = env.get_template("index.html")
180     html = index_template.render(text=open("src/index.md").read())
181
182     index_path = pathlib.Path("_html") / "index.html"
183     index_path.write_text(html)