Skip to content

Commit 056adad

Browse files
committed
Add some type hints
1 parent bd43e3b commit 056adad

File tree

1 file changed

+50
-35
lines changed

1 file changed

+50
-35
lines changed

generate.py

+50-35
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from datetime import datetime
88
from os.path import join
9+
from typing import NotRequired, TypedDict
910

1011
import mako.template
1112
import mako.lookup
@@ -32,9 +33,34 @@
3233
)
3334

3435

35-
def copyinto(src, dst, symlinks=False, ignore=None):
36+
class Page(TypedDict):
37+
"""A page on the site."""
38+
39+
# Brief introductory comment above at the start of a page
40+
author_comment: NotRequired[str]
41+
# YYYY-MM-DD date of the page
42+
date: str
43+
# A brief summary of the page
44+
excerpt: str
45+
# The rendered HTML of the page
46+
html: NotRequired[str]
47+
# The next page in chronological series of pages
48+
next: "Page"
49+
# Flag to skip rendering the page
50+
skip: NotRequired[bool]
51+
# The URL slug of the page
52+
slug: str
53+
# The path to the source document of the page
54+
src: str
55+
# The template to use to render the page
56+
template: NotRequired[str]
57+
# The title of the page
58+
title: str
59+
60+
61+
def copyinto(src: str, dst: str, symlinks=False, ignore=None):
3662
"""
37-
Copy files and subdirectoryes from src into dst.
63+
Copy files and subdirectories from src into dst.
3864
3965
http://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth
4066
"""
@@ -47,7 +73,7 @@ def copyinto(src, dst, symlinks=False, ignore=None):
4773
shutil.copy2(s, d)
4874

4975

50-
def save_rss(pages):
76+
def save_rss(pages: list[Page]):
5177
"""Save a RSS document listing all of the pages."""
5278
rss_tmpl = TMPL_LOOKUP.get_template("rss.mako")
5379
xml = rss_tmpl.render(
@@ -61,7 +87,7 @@ def save_rss(pages):
6187
f.write(xml)
6288

6389

64-
def save_atom(pages):
90+
def save_atom(pages: list[Page]):
6591
"""Save an Atom document listing of all of the pages."""
6692
atom_tmpl = TMPL_LOOKUP.get_template("atom.mako")
6793
xml = atom_tmpl.render(
@@ -76,7 +102,7 @@ def save_atom(pages):
76102
f.write(xml)
77103

78104

79-
def save_archive(pages):
105+
def save_archive(pages: list[Page]):
80106
"""Save an HTML document listing all of the pages."""
81107
archive_tmpl = TMPL_LOOKUP.get_template("archive.mako")
82108
html = archive_tmpl.render(site_name=SITE_NAME, site_root="..", all_pages=pages)
@@ -85,7 +111,7 @@ def save_archive(pages):
85111
f.write(html)
86112

87113

88-
def save_latest(pages):
114+
def save_latest(pages: list[Page]):
89115
"""Save the latest page as index.html."""
90116
page = pages[0]
91117
tmpl_name = page.get("template", "page.mako")
@@ -100,7 +126,7 @@ def save_latest(pages):
100126
f.write(html)
101127

102128

103-
def save_html(pages):
129+
def save_html(pages: list[Page]):
104130
"""Save every page as an HTML document."""
105131
for page in pages:
106132
in_tree = page["src"]
@@ -117,11 +143,10 @@ def save_html(pages):
117143
f.write(html)
118144

119145

120-
def org_pages(pages):
146+
def org_pages(pages: list[Page]):
121147
"""Sort pages from newest to oldest.
122148
123-
Use the `date` key for sorting. Add a `next` key to link one page to the
124-
next.
149+
Use the `date` key for sorting. Add a `next` key to link one page to the next.
125150
"""
126151
for page in pages:
127152
if "date" in page:
@@ -135,23 +160,17 @@ def org_pages(pages):
135160

136161

137162
class MarkdownParser:
138-
md = markdown.Markdown(
139-
extensions=["meta", "fenced_code", "codehilite"], output_format="html"
140-
)
141-
142-
def execute(self, path, page):
143-
"""Parse an md file in the path and update the page with its
144-
contents.
163+
def __init__(self):
164+
self.md = markdown.Markdown(
165+
extensions=["meta", "fenced_code", "codehilite"], output_format="html"
166+
)
145167

146-
Use the page filename or fall back on index.md as the default.
147-
Add metadata from the extended metadata section of the document to the
148-
page along with the rendered HTML.
149-
"""
150-
fn = join(path, page.get("filename", "index.md"))
151-
if not os.path.isfile(fn) or not fn.endswith(".md"):
168+
def execute(self, path: str, page: Page):
169+
"""Parse an md file in the path and update the page with its HTML rendered content and
170+
metadata."""
171+
fn = join(path, "index.md")
172+
if not os.path.isfile(fn):
152173
return
153-
else:
154-
page.setdefault("filename", "index.md")
155174
with open(fn) as f:
156175
print("Processing", path, "as Markdown")
157176
text = f.read()
@@ -169,10 +188,9 @@ def execute(self, path, page):
169188
page["slug"] = os.path.basename(path)
170189
page["html"] = html
171190

172-
def _build_excerpt(self, text):
173-
"""Build an excerpt from the first non-blank line after the first blank
174-
line separating the metadata from the content of the doc.
175-
"""
191+
def _build_excerpt(self, text: str):
192+
"""Build an excerpt from the first non-blank line after the first blank line separating the
193+
metadata from the content of the doc."""
176194
lines = []
177195
prior = None
178196

@@ -192,21 +210,18 @@ def _build_excerpt(self, text):
192210
def load_pages():
193211
"""Parse data and metadata for all pages.
194212
195-
Iterate over the page directories. Pass the page source document and
196-
in-memory page representation to all parsers. Raise a RuntimeError if
197-
no parser emits HTML for the page.
213+
Iterate over the page directories. Pass the page source document and in-memory page
214+
representation to all parsers. Raise a RuntimeError if no parser emits HTML for the page.
198215
"""
199216
pages = []
200217
handlers = [MarkdownParser()]
201218
for path in glob.glob(join(PAGES_DIR, "*")):
202-
page = {}
219+
page: Page = {}
203220
for handler in handlers:
204221
handler.execute(path, page)
205222
if "skip" in page:
206223
continue
207224
elif "html" not in page:
208-
print("WARN: Nothing rendered HTML for", path)
209-
continue
210225
raise RuntimeError("Nothing rendered HTML for " + path)
211226
pages.append(page)
212227
return pages

0 commit comments

Comments
 (0)