wobblyhead hg > wobbly_ssg
comparison tools/make_site.py @ 0:71dd8d58a8e5 default tip
cleaned up re-init from net_wobblyhead_www project tooling
| author | ark |
|---|---|
| date | 2026-10-22 14:59 +0200 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| -1:000000000000 | 0:71dd8d58a8e5 |
|---|---|
| 1 #!/usr/bin/env python3 | |
| 2 """static site generator. builds the site in the current directory. see | |
| 3 doc/format.md for the source and template format, doc/build.md for how a | |
| 4 build works, doc/tools.md for the command line.""" | |
| 5 | |
| 6 import argparse | |
| 7 import datetime | |
| 8 import html | |
| 9 import re | |
| 10 import shutil | |
| 11 import sys | |
| 12 import urllib.parse | |
| 13 from pathlib import Path | |
| 14 | |
| 15 import markdown | |
| 16 from PIL import Image, ImageOps, features | |
| 17 | |
| 18 # the site is the current directory, so a linked copy of this script builds | |
| 19 # the site it is run in. | |
| 20 ROOT = Path.cwd().resolve() | |
| 21 SRC = ROOT / "src" | |
| 22 TPL = ROOT / "tpl" | |
| 23 STATIC = ROOT / "static" | |
| 24 CONFIG = ROOT / "config.txt" | |
| 25 | |
| 26 DEFAULT_TEMPLATE = "page.html" | |
| 27 DEFAULT_TAGINDEX = "tag.html" | |
| 28 MARKDOWN_EXTENSIONS = ["extra", "sane_lists"] | |
| 29 | |
| 30 CONFIG_KEYS = {"build_dir", "image_sizes", "extra_header_keys", "site_url", | |
| 31 "index_sections", "index_recent"} | |
| 32 | |
| 33 HEADER_KEYS = { | |
| 34 "title", "subtitle", "description", "timeframe", "created_at", | |
| 35 "updated_at", "todo", "is_published", "template", "tags", "image", | |
| 36 "crossref", "repository", | |
| 37 } | |
| 38 | |
| 39 # python-markdown's footnotes extension appends its notes to the body in a div | |
| 40 # of this class. | |
| 41 FOOTNOTES = '<div class="footnote">' | |
| 42 | |
| 43 # pillow format names that may be resized. webp is only eligible where the | |
| 44 # local pillow was built with it, so the set is decided at import time. | |
| 45 RESIZABLE = {"PNG", "JPEG"} | |
| 46 if features.check("webp"): | |
| 47 RESIZABLE.add("WEBP") | |
| 48 | |
| 49 JPEG_QUALITY = 85 | |
| 50 | |
| 51 | |
| 52 def image_format(image): | |
| 53 """the pillow format name of image, with mpo reported as jpeg. mpo is a | |
| 54 jpeg with further images appended, such as a camera's preview. pillow | |
| 55 opens it at the first image, the photo itself, and handles it as a jpeg. | |
| 56 """ | |
| 57 return "JPEG" if image.format == "MPO" else image.format | |
| 58 | |
| 59 | |
| 60 # link preview images. the size is what facebook and linkedin ask for, the | |
| 61 # minimum the smallest that facebook still shows as a large card. | |
| 62 OG_SIZE = (1200, 630) | |
| 63 OG_MINIMUM = (600, 315) | |
| 64 | |
| 65 # a paragraph holding only an image, optionally linked. one with a title | |
| 66 # becomes a figure with that title as its caption. | |
| 67 FIGURE = re.compile(r"<p>((?:<a\b[^>]*>)?<img\b[^>]*>(?:</a>)?)</p>") | |
| 68 | |
| 69 # one pass over the template: a complete if or loop block, a marker, or any | |
| 70 # other {% ... %}, which is a stray block tag. the shortest body is matched, so | |
| 71 # a block cannot contain a block of its own kind. | |
| 72 TOKEN = re.compile( | |
| 73 r"\{%\s*(if|loop)\s+([A-Za-z_][A-Za-z0-9_.]*)(?:\|([A-Za-z]+))?\s*%\}" | |
| 74 r"(.*?)\{%\s*end\1\s*%\}" | |
| 75 r"|\{\{([A-Za-z_][A-Za-z0-9_.]*)(?:\|([A-Za-z]+))?\}\}" | |
| 76 r"|\{%.*?%\}", | |
| 77 re.DOTALL) | |
| 78 | |
| 79 QUIET, NORMAL, VERBOSE = 0, 1, 2 | |
| 80 | |
| 81 _verbosity = NORMAL | |
| 82 _counts = {"created": 0, "updated": 0, "images": 0, "warnings": 0} | |
| 83 | |
| 84 | |
| 85 class BuildError(Exception): | |
| 86 """an error stops the build; no correct output is possible.""" | |
| 87 | |
| 88 | |
| 89 def error(msg): | |
| 90 raise BuildError(msg) | |
| 91 | |
| 92 | |
| 93 def warn(msg): | |
| 94 _counts["warnings"] += 1 | |
| 95 if _verbosity >= NORMAL: | |
| 96 print("warning: " + msg, file=sys.stderr) | |
| 97 | |
| 98 | |
| 99 def notice(msg): | |
| 100 # all three severities go to stderr so that they stay in order relative to | |
| 101 # each other; only the summary is stdout. | |
| 102 if _verbosity >= VERBOSE: | |
| 103 print("notice: " + msg, file=sys.stderr) | |
| 104 | |
| 105 | |
| 106 # -- header blocks -------------------------------------------------------- | |
| 107 | |
| 108 def parse_header_block(text, where): | |
| 109 """split a source into its header block and its body. | |
| 110 | |
| 111 key: value lines, ended by the first blank line. a line starting with | |
| 112 space or tab continues the previous value, joined with a single space, | |
| 113 the way rfc 5322 folds mail headers. | |
| 114 """ | |
| 115 lines = text.splitlines() | |
| 116 if not lines or not lines[0].strip(): | |
| 117 error(f"{where}: does not start with a header block") | |
| 118 | |
| 119 headers = {} | |
| 120 key = None | |
| 121 end = len(lines) | |
| 122 for i, line in enumerate(lines): | |
| 123 if not line.strip(): | |
| 124 end = i | |
| 125 break | |
| 126 if line[:1] in (" ", "\t"): | |
| 127 if key is None: | |
| 128 error(f"{where}: line {i + 1}: continuation before any header") | |
| 129 headers[key] = headers[key] + " " + line.strip() | |
| 130 continue | |
| 131 if ":" not in line: | |
| 132 error(f"{where}: line {i + 1}: not a header line: {line.strip()!r}") | |
| 133 key, _, value = line.partition(":") | |
| 134 key = key.strip() | |
| 135 if key in headers: | |
| 136 warn(f"{where}: duplicate header key {key!r}") | |
| 137 headers[key] = value.strip() | |
| 138 | |
| 139 return headers, "\n".join(lines[end + 1:]) | |
| 140 | |
| 141 | |
| 142 def read_config(): | |
| 143 if not CONFIG.exists(): | |
| 144 error(f"{CONFIG.name} not found in {ROOT}") | |
| 145 headers, _ = parse_header_block(CONFIG.read_text(encoding="utf-8"), CONFIG.name) | |
| 146 for key in headers: | |
| 147 if key not in CONFIG_KEYS: | |
| 148 warn(f"{CONFIG.name}: unknown key {key!r}") | |
| 149 config = {"build_dir": "www", "image_sizes": "", "extra_header_keys": "", | |
| 150 "site_url": "", "index_sections": "", "index_recent": "5"} | |
| 151 config.update(headers) | |
| 152 config["site_url"] = config["site_url"].rstrip("/") | |
| 153 if not config["site_url"]: | |
| 154 error(f"{CONFIG.name}: site_url not set") | |
| 155 return config | |
| 156 | |
| 157 | |
| 158 def parse_image_sizes(spec): | |
| 159 sizes = {} | |
| 160 for item in spec.split(","): | |
| 161 item = item.strip() | |
| 162 if not item: | |
| 163 continue | |
| 164 name, _, width = item.partition(":") | |
| 165 if not width.strip().isdigit(): | |
| 166 error(f"{CONFIG.name}: bad image size {item!r}") | |
| 167 sizes[name.strip()] = int(width) | |
| 168 return sizes | |
| 169 | |
| 170 | |
| 171 # -- templating ----------------------------------------------------------- | |
| 172 | |
| 173 def is_empty(value): | |
| 174 return value is None or value == "" or value == [] | |
| 175 | |
| 176 | |
| 177 def test(values, key, cond, where): | |
| 178 """evaluate an if condition. an undefined key counts as empty.""" | |
| 179 if cond == "isempty": | |
| 180 return is_empty(values.get(key)) | |
| 181 if cond == "isnotempty": | |
| 182 return not is_empty(values.get(key)) | |
| 183 error(f"{where}: unknown condition {cond!r} on {key!r}") | |
| 184 | |
| 185 | |
| 186 def render(template, values, where): | |
| 187 """render blocks and markers. see doc/format.md. | |
| 188 | |
| 189 values maps keys to strings, or to lists of dictionaries for loops. | |
| 190 inside a loop the item is the only scope. output is not scanned again. | |
| 191 """ | |
| 192 | |
| 193 def one(match): | |
| 194 kind, key, cond, inner, mkey, filt = match.groups() | |
| 195 | |
| 196 if kind == "if": | |
| 197 if test(values, key, cond, where): | |
| 198 return render(inner, values, where) | |
| 199 return "" | |
| 200 | |
| 201 if kind == "loop": | |
| 202 if cond is not None: | |
| 203 error(f"{where}: condition on loop {key!r}") | |
| 204 if key not in values: | |
| 205 warn(f"{where}: undefined template value {key!r}") | |
| 206 return "" | |
| 207 items = values[key] | |
| 208 if not (isinstance(items, list) | |
| 209 and all(isinstance(item, dict) for item in items)): | |
| 210 error(f"{where}: loop value {key!r} is not a list of dictionaries") | |
| 211 return "".join(render(inner, item, where) for item in items) | |
| 212 | |
| 213 if mkey is None: | |
| 214 error(f"{where}: stray or malformed block tag {match.group(0)!r}") | |
| 215 | |
| 216 if mkey in values: | |
| 217 value = values[mkey] | |
| 218 else: | |
| 219 warn(f"{where}: undefined template value {mkey!r}") | |
| 220 value = "" | |
| 221 if not isinstance(value, str): | |
| 222 error(f"{where}: template value {mkey!r} is not a string") | |
| 223 if filt is None or filt == "htmlencode": | |
| 224 return html.escape(value) | |
| 225 if filt == "literal": | |
| 226 return value | |
| 227 if filt == "urlencode": | |
| 228 return urllib.parse.quote(value, safe="") | |
| 229 error(f"{where}: unknown filter {filt!r}") | |
| 230 | |
| 231 return TOKEN.sub(one, template) | |
| 232 | |
| 233 | |
| 234 # -- tags ----------------------------------------------------------------- | |
| 235 | |
| 236 def parse_tags(spec): | |
| 237 """split the tags header on commas. empty items are dropped.""" | |
| 238 return [t.strip() for t in spec.split(",") if t.strip()] | |
| 239 | |
| 240 | |
| 241 def tag_file(tag): | |
| 242 """tag index pages go in the build root. the name is the tag in lower | |
| 243 case, with all characters other than letters and digits removed.""" | |
| 244 return "tag_" + re.sub(r"[^a-z0-9]+", "", tag.lower()) + ".html" | |
| 245 | |
| 246 | |
| 247 # -- dates ---------------------------------------------------------------- | |
| 248 | |
| 249 def format_date(value, key, where): | |
| 250 """the date of an iso date or date and time, as dd.mm.yyyy. a time is | |
| 251 accepted and dropped. anything else warns and is returned as it is.""" | |
| 252 try: | |
| 253 moment = datetime.datetime.fromisoformat(value.strip()) | |
| 254 except ValueError: | |
| 255 warn(f"{where}: {key} is not an ISO date: {value!r}") | |
| 256 return value | |
| 257 return moment.strftime("%d.%m.%Y") | |
| 258 | |
| 259 | |
| 260 # -- files ---------------------------------------------------------------- | |
| 261 | |
| 262 def copy_if_newer(source, dest): | |
| 263 dest.parent.mkdir(parents=True, exist_ok=True) | |
| 264 if dest.exists() and dest.stat().st_mtime >= source.stat().st_mtime: | |
| 265 return False | |
| 266 _counts["updated" if dest.exists() else "created"] += 1 | |
| 267 shutil.copy2(source, dest) | |
| 268 return True | |
| 269 | |
| 270 | |
| 271 def attr(tag, name): | |
| 272 match = re.search(r'\b' + name + r'="([^"]*)"', tag) | |
| 273 return match.group(1) if match else None | |
| 274 | |
| 275 | |
| 276 def split_url(url): | |
| 277 """separate the path from the query string and fragment.""" | |
| 278 match = re.match(r"([^#?]*)(.*)", url) | |
| 279 return match.group(1), match.group(2) | |
| 280 | |
| 281 | |
| 282 def find_original(wanted): | |
| 283 """the source file behind an image reference: the file itself if it | |
| 284 exists, otherwise the same name minus its size infix. None if neither | |
| 285 exists.""" | |
| 286 if wanted.exists(): | |
| 287 return wanted | |
| 288 parts = wanted.name.split(".") | |
| 289 if len(parts) < 3: | |
| 290 return None | |
| 291 original = wanted.with_name(".".join(parts[:-2] + parts[-1:])) | |
| 292 return original if original.exists() else None | |
| 293 | |
| 294 | |
| 295 # -- the site ------------------------------------------------------------- | |
| 296 | |
| 297 class Site: | |
| 298 def __init__(self, config, build, draft, tags): | |
| 299 self.config = config | |
| 300 self.build = build | |
| 301 self.draft = draft | |
| 302 # tag index file name -> {"name": first spelling seen, "pages": [...]}, | |
| 303 # or None when tag index pages are not rebuilt. | |
| 304 self.tags = {} if tags else None | |
| 305 self.sizes = parse_image_sizes(config["image_sizes"]) | |
| 306 self.header_keys = HEADER_KEYS | { | |
| 307 k.strip() for k in config["extra_header_keys"].split(",") if k.strip() | |
| 308 } | |
| 309 self.templates = {} | |
| 310 self.links = [] | |
| 311 self.images = set() | |
| 312 | |
| 313 # -- assets ---------------------------------------------------------- | |
| 314 | |
| 315 def copy_assets(self): | |
| 316 """copy static/, which holds unlinked global files, and tpl/, which | |
| 317 holds the layout assets.""" | |
| 318 for base in (STATIC, TPL): | |
| 319 if not base.is_dir(): | |
| 320 continue | |
| 321 for item in sorted(base.rglob("*")): | |
| 322 if not item.is_file() or item.name == ".DS_Store": | |
| 323 continue | |
| 324 if base is TPL and item.suffix.lower() == ".html": | |
| 325 continue | |
| 326 copy_if_newer(item, self.build / item.relative_to(base)) | |
| 327 | |
| 328 # -- images ---------------------------------------------------------- | |
| 329 | |
| 330 def resolve_image(self, wanted, dest, where): | |
| 331 """put the referenced image in the build directory, once per run. | |
| 332 | |
| 333 a build that already placed this file says nothing about it again; | |
| 334 without that, the second reference to a derivative generated moments | |
| 335 ago reports it as up to date, which reads like a contradiction. | |
| 336 """ | |
| 337 # two references can spell the same file differently, so the key is the | |
| 338 # resolved path rather than the one built from the reference. | |
| 339 key = dest.resolve() | |
| 340 if key in self.images: | |
| 341 return True | |
| 342 placed = self.place_image(wanted, dest, where) | |
| 343 if placed: | |
| 344 self.images.add(key) | |
| 345 return placed | |
| 346 | |
| 347 def place_image(self, wanted, dest, where): | |
| 348 """a reference either names a file that exists in the source tree, or a | |
| 349 derivative to be generated from the same name minus its size infix. | |
| 350 """ | |
| 351 original = find_original(wanted) | |
| 352 if original is None: | |
| 353 warn(f"{where}: broken image reference {wanted.name!r}") | |
| 354 return False | |
| 355 if original == wanted: | |
| 356 if copy_if_newer(wanted, dest): | |
| 357 notice(f"{where}: {wanted.name} copied verbatim") | |
| 358 return True | |
| 359 | |
| 360 token = wanted.name.split(".")[-2] | |
| 361 | |
| 362 if token.isdigit(): | |
| 363 width = int(token) | |
| 364 elif token in self.sizes: | |
| 365 width = self.sizes[token] | |
| 366 else: | |
| 367 warn(f"{where}: unknown image size {token!r}, copying original") | |
| 368 copy_if_newer(original, dest) | |
| 369 return True | |
| 370 | |
| 371 if dest.exists() and dest.stat().st_mtime >= original.stat().st_mtime: | |
| 372 notice(f"{where}: {dest.name} up to date") | |
| 373 return True | |
| 374 | |
| 375 with Image.open(original) as image: | |
| 376 # the format has to be read before resizing: a resized image is a | |
| 377 # new object with no format, and pillow would then pick its writer | |
| 378 # from the extension, which is not the authority here. | |
| 379 fmt = image_format(image) | |
| 380 if fmt not in RESIZABLE: | |
| 381 warn(f"{where}: cannot resize {original.name} ({fmt})") | |
| 382 return False | |
| 383 # the derivative has no exif, so a rotation recorded there is | |
| 384 # applied to the pixels. the colour profile is kept separately. | |
| 385 icc = image.info.get("icc_profile") | |
| 386 image = ImageOps.exif_transpose(image) | |
| 387 if image.width < width: | |
| 388 warn(f"{where}: {original.name} is narrower than {width}px") | |
| 389 copy_if_newer(original, dest) | |
| 390 return True | |
| 391 height = round(image.height * width / image.width) | |
| 392 resized = image.resize((width, height), Image.LANCZOS) | |
| 393 | |
| 394 dest.parent.mkdir(parents=True, exist_ok=True) | |
| 395 options = {"icc_profile": icc} if icc else {} | |
| 396 if fmt == "JPEG": | |
| 397 options["quality"] = JPEG_QUALITY | |
| 398 resized.save(dest, format=fmt, **options) | |
| 399 _counts["images"] += 1 | |
| 400 notice(f"{where}: generated {dest.name} at {width}x{height}") | |
| 401 return True | |
| 402 | |
| 403 # -- references in the generated html -------------------------------- | |
| 404 | |
| 405 def rewrite(self, body, source, out_dir, images, where): | |
| 406 """rewrite links, copy referenced files, size referenced images. | |
| 407 | |
| 408 this runs on the markdown output rather than on the markdown, so a | |
| 409 hand-written html fragment in a source file is treated the same way. | |
| 410 it assumes double-quoted attributes, which is what python-markdown | |
| 411 emits. | |
| 412 | |
| 413 every local image reference is appended to images as a pair of the | |
| 414 referenced source path and the alt text, in page order. | |
| 415 """ | |
| 416 src_dir = source.parent | |
| 417 | |
| 418 def anchor(match): | |
| 419 tag = match.group(0) | |
| 420 href = attr(tag, "href") | |
| 421 if href is None or not local(href): | |
| 422 return tag | |
| 423 path, tail = split_url(href) | |
| 424 if not path: | |
| 425 return tag | |
| 426 if path.endswith(".md"): | |
| 427 path = path[:-3] + ".html" | |
| 428 tag = tag.replace(f'href="{href}"', f'href="{path}{tail}"', 1) | |
| 429 elif not path.endswith(".html"): | |
| 430 # a pdf, an archive, a text file: copied verbatim, no | |
| 431 # derivative logic. | |
| 432 referenced = src_dir / urllib.parse.unquote(path) | |
| 433 if referenced.is_file(): | |
| 434 copy_if_newer(referenced, out_dir / urllib.parse.unquote(path)) | |
| 435 self.links.append((where, out_dir / urllib.parse.unquote(path), path)) | |
| 436 return tag | |
| 437 | |
| 438 def image(match): | |
| 439 tag = match.group(0) | |
| 440 src = attr(tag, "src") | |
| 441 if src is None or not local(src): | |
| 442 return tag | |
| 443 path, _ = split_url(src) | |
| 444 if not path: | |
| 445 return tag | |
| 446 name = urllib.parse.unquote(path) | |
| 447 dest = out_dir / name | |
| 448 images.append((src_dir / name, html.unescape(attr(tag, "alt") or ""))) | |
| 449 self.links.append((where, dest, path)) | |
| 450 if not self.resolve_image(src_dir / name, dest, where): | |
| 451 return tag | |
| 452 return add_dimensions(tag, dest) | |
| 453 | |
| 454 body = re.sub(r"<a\b[^>]*>", anchor, body) | |
| 455 body = re.sub(r"<img\b[^>]*?>", image, body) | |
| 456 return FIGURE.sub(figure, body) | |
| 457 | |
| 458 # -- link preview image ----------------------------------------------- | |
| 459 | |
| 460 def preview_image(self, headers, source, out_dir, images, where): | |
| 461 """pick and generate the link preview image of a page. see | |
| 462 doc/build.md. | |
| 463 | |
| 464 returns the template values ogImage, ogImageWidth, ogImageHeight and | |
| 465 ogImageAlt, or no values when the template default applies. | |
| 466 """ | |
| 467 name = headers.get("image") | |
| 468 if name: | |
| 469 path = source.parent / name | |
| 470 if path.is_file(): | |
| 471 values = self.write_preview(path, "", source, out_dir, True, where) | |
| 472 if values: | |
| 473 return values | |
| 474 else: | |
| 475 warn(f"{where}: broken image reference {name!r} in image header") | |
| 476 | |
| 477 # the first body image that can be processed and is large enough | |
| 478 for wanted, alt in images: | |
| 479 original = find_original(wanted) | |
| 480 if original is None: | |
| 481 continue | |
| 482 try: | |
| 483 with Image.open(original) as image: | |
| 484 fmt = image_format(image) | |
| 485 size = ImageOps.exif_transpose(image).size | |
| 486 except OSError: | |
| 487 continue # svg and anything else pillow cannot open | |
| 488 if (fmt in RESIZABLE and size[0] >= OG_MINIMUM[0] | |
| 489 and size[1] >= OG_MINIMUM[1]): | |
| 490 return self.write_preview(original, alt, source, out_dir, | |
| 491 False, where) | |
| 492 return {} | |
| 493 | |
| 494 def write_preview(self, original, alt, source, out_dir, explicit, where): | |
| 495 """crop the original to the preview aspect ratio and scale it down to | |
| 496 the preview size, never up. an original of exactly that size is | |
| 497 copied. the file name contains the modification time of the original, | |
| 498 so a changed image gets a new address and consumers fetch it again. | |
| 499 an existing file is not written again. | |
| 500 """ | |
| 501 stamp = int(original.stat().st_mtime) | |
| 502 dest = out_dir / "img" / f"og_{source.stem}_{stamp}{original.suffix}" | |
| 503 | |
| 504 if dest.exists(): | |
| 505 notice(f"{where}: {dest.name} up to date") | |
| 506 else: | |
| 507 with Image.open(original) as image: | |
| 508 fmt = image_format(image) | |
| 509 if fmt not in RESIZABLE: | |
| 510 warn(f"{where}: cannot crop {original.name} ({fmt}) " | |
| 511 "for the link preview") | |
| 512 return {} | |
| 513 icc = image.info.get("icc_profile") | |
| 514 image = ImageOps.exif_transpose(image) | |
| 515 if image.size == OG_SIZE: | |
| 516 copy_if_newer(original, dest) | |
| 517 notice(f"{where}: {dest.name} copied verbatim") | |
| 518 image = None | |
| 519 else: | |
| 520 if explicit: | |
| 521 warn(f"{where}: image {original.name} is " | |
| 522 f"{image.width}x{image.height}, cropped to " | |
| 523 f"{OG_SIZE[0]}x{OG_SIZE[1]}") | |
| 524 image = crop_preview(image) | |
| 525 | |
| 526 if image is not None: | |
| 527 dest.parent.mkdir(parents=True, exist_ok=True) | |
| 528 options = {"icc_profile": icc} if icc else {} | |
| 529 if fmt == "JPEG": | |
| 530 options["quality"] = JPEG_QUALITY | |
| 531 image.save(dest, format=fmt, **options) | |
| 532 _counts["images"] += 1 | |
| 533 notice(f"{where}: generated {dest.name} at " | |
| 534 f"{image.width}x{image.height}") | |
| 535 | |
| 536 with Image.open(dest) as image: | |
| 537 width, height = image.size | |
| 538 rel = dest.relative_to(self.build).as_posix() | |
| 539 return { | |
| 540 "ogImage": self.config["site_url"] + "/" + urllib.parse.quote(rel), | |
| 541 "ogImageWidth": str(width), | |
| 542 "ogImageHeight": str(height), | |
| 543 "ogImageAlt": alt, | |
| 544 } | |
| 545 | |
| 546 # -- pages ----------------------------------------------------------- | |
| 547 | |
| 548 def template(self, name): | |
| 549 if name not in self.templates: | |
| 550 path = TPL / name | |
| 551 if not path.is_file(): | |
| 552 error(f"template {name!r} not found in {TPL.name}/") | |
| 553 self.templates[name] = path.read_text(encoding="utf-8") | |
| 554 return self.templates[name] | |
| 555 | |
| 556 def page(self, source): | |
| 557 rel = source.relative_to(SRC) | |
| 558 out_file = self.build / rel.with_suffix(".html") | |
| 559 where = str(rel) | |
| 560 | |
| 561 # an up-to-date page still goes into the tag index, so its headers | |
| 562 # are read before the date check when tag index pages are rebuilt. | |
| 563 headers = None | |
| 564 if self.tags is not None: | |
| 565 headers, body_md = self.read(source, where) | |
| 566 if headers is None: | |
| 567 return | |
| 568 self.index_tags(headers, rel, where) | |
| 569 | |
| 570 if out_file.exists() and out_file.stat().st_mtime >= source.stat().st_mtime: | |
| 571 notice(f"{where}: up to date") | |
| 572 return | |
| 573 | |
| 574 if headers is None: | |
| 575 headers, body_md = self.read(source, where) | |
| 576 if headers is None: | |
| 577 return | |
| 578 | |
| 579 body = markdown.markdown(body_md, extensions=MARKDOWN_EXTENSIONS) | |
| 580 images = [] | |
| 581 body = self.rewrite(body, source, out_file.parent, images, where) | |
| 582 # the footnotes are split off so that the template can put the | |
| 583 # repository and crossref links between the text and the notes. | |
| 584 cut = body.rfind(FOOTNOTES) | |
| 585 footnotes = body[cut:] if cut >= 0 else "" | |
| 586 body = body[:cut] if cut >= 0 else body | |
| 587 | |
| 588 depth = len(rel.parent.parts) | |
| 589 values = {f"site.{k}": v for k, v in self.config.items()} | |
| 590 values.update(headers) | |
| 591 values["body"] = body | |
| 592 values["footnotes"] = footnotes | |
| 593 values["crossrefUrl"] = self.crossref(headers.get("crossref", ""), | |
| 594 out_file.parent, where) | |
| 595 values["relRoot"] = "../" * depth if depth else "./" | |
| 596 values["absRoot"] = "/" | |
| 597 values["tags"] = [ | |
| 598 {"name": t, "url": values["relRoot"] + tag_file(t)} | |
| 599 for t in parse_tags(headers.get("tags", "")) | |
| 600 ] | |
| 601 values["pageUrl"] = self.page_url(rel.with_suffix(".html").as_posix()) | |
| 602 values["metaDescription"] = (headers.get("description") | |
| 603 or headers.get("subtitle") or "") | |
| 604 values.update(self.dates(headers, where)) | |
| 605 values.update(self.preview_image(headers, source, out_file.parent, | |
| 606 images, where)) | |
| 607 | |
| 608 name = headers.get("template") or DEFAULT_TEMPLATE | |
| 609 page = render(self.template(name), values, where) | |
| 610 | |
| 611 out_file.parent.mkdir(parents=True, exist_ok=True) | |
| 612 _counts["updated" if out_file.exists() else "created"] += 1 | |
| 613 out_file.write_text(page, encoding="utf-8") | |
| 614 | |
| 615 def crossref(self, value, out_dir, where): | |
| 616 """the address of the page named in the crossref header, relative to | |
| 617 the page, with .md rewritten to .html like a body link. the target is | |
| 618 checked like a body link. empty when the header is not set.""" | |
| 619 value = value.strip() | |
| 620 if not value: | |
| 621 return "" | |
| 622 if not local(value): | |
| 623 warn(f"{where}: crossref is not an internal reference: {value!r}") | |
| 624 return value | |
| 625 path, tail = split_url(value) | |
| 626 if path.endswith(".md"): | |
| 627 path = path[:-3] + ".html" | |
| 628 self.links.append((where, out_dir / urllib.parse.unquote(path), path)) | |
| 629 return path + tail | |
| 630 | |
| 631 def page_url(self, path): | |
| 632 """the absolute address of a page, given its path relative to the | |
| 633 build root. an index.html is addressed by its directory.""" | |
| 634 if path == "index.html" or path.endswith("/index.html"): | |
| 635 path = path[:-len("index.html")] | |
| 636 return self.config["site_url"] + "/" + urllib.parse.quote(path) | |
| 637 | |
| 638 def dates(self, headers, where): | |
| 639 """createdDate and updatedDate for display. updatedDate is empty when | |
| 640 it shows the same date as createdDate, whatever the times.""" | |
| 641 created = headers.get("created_at", "").strip() | |
| 642 updated = headers.get("updated_at", "").strip() | |
| 643 created = format_date(created, "created_at", where) if created else "" | |
| 644 updated = format_date(updated, "updated_at", where) if updated else "" | |
| 645 return { | |
| 646 "createdDate": created, | |
| 647 "updatedDate": "" if updated == created else updated, | |
| 648 } | |
| 649 | |
| 650 def read(self, source, where): | |
| 651 """read and check a source. returns its headers and markdown body, or | |
| 652 None twice when the page is unpublished and draft mode is off.""" | |
| 653 headers, body_md = parse_header_block( | |
| 654 source.read_text(encoding="utf-8"), where) | |
| 655 | |
| 656 if headers.get("is_published", "").strip() != "1": | |
| 657 if not self.draft: | |
| 658 warn(f"{where}: unpublished, skipped") | |
| 659 return None, None | |
| 660 warn(f"{where}: unpublished, rendered as draft") | |
| 661 | |
| 662 if not headers.get("title"): | |
| 663 error(f"{where}: missing title") | |
| 664 for key in headers: | |
| 665 if key not in self.header_keys: | |
| 666 warn(f"{where}: unknown header key {key!r}") | |
| 667 if not body_md.strip(): | |
| 668 warn(f"{where}: no body") | |
| 669 return headers, body_md | |
| 670 | |
| 671 # -- tag index pages -------------------------------------------------- | |
| 672 | |
| 673 def index_tags(self, headers, rel, where): | |
| 674 entry = {k: v for k, v in headers.items() if k != "tags"} | |
| 675 entry["url"] = rel.with_suffix(".html").as_posix() | |
| 676 entry["descOrSubtitle"] = (headers.get("description") | |
| 677 or headers.get("subtitle") or "") | |
| 678 for tag in parse_tags(headers.get("tags", "")): | |
| 679 index = self.tags.setdefault(tag_file(tag), {"name": tag, "pages": []}) | |
| 680 if index["name"] != tag: | |
| 681 warn(f"{where}: tag {tag!r} shares its index page with " | |
| 682 f"{index['name']!r}") | |
| 683 index["pages"].append(entry) | |
| 684 | |
| 685 def write_tags(self): | |
| 686 """write one index page per tag into the build root. pages are listed | |
| 687 newest first by created_at, then by title. pages without created_at | |
| 688 come last.""" | |
| 689 for file, index in sorted(self.tags.items()): | |
| 690 pages = sorted(index["pages"], key=lambda p: p["title"]) | |
| 691 pages.sort(key=lambda p: p.get("created_at", ""), reverse=True) | |
| 692 notice(f"{file}: tag {index['name']!r}, pages: {len(pages)}") | |
| 693 | |
| 694 values = {f"site.{k}": v for k, v in self.config.items()} | |
| 695 values["tag"] = index["name"] | |
| 696 values["pages"] = pages | |
| 697 values["relRoot"] = "./" | |
| 698 values["absRoot"] = "/" | |
| 699 values["pageUrl"] = self.page_url(file) | |
| 700 page = render(self.template(DEFAULT_TAGINDEX), values, file) | |
| 701 | |
| 702 out_file = self.build / file | |
| 703 _counts["updated" if out_file.exists() else "created"] += 1 | |
| 704 out_file.write_text(page, encoding="utf-8") | |
| 705 | |
| 706 def check_links(self): | |
| 707 for where, target, raw in self.links: | |
| 708 if not target.exists(): | |
| 709 warn(f"{where}: broken link {raw!r}") | |
| 710 | |
| 711 | |
| 712 def local(url): | |
| 713 """a reference is local unless it has a scheme or is protocol-relative.""" | |
| 714 return not urllib.parse.urlsplit(url).scheme and not url.startswith("//") | |
| 715 | |
| 716 | |
| 717 def add_dimensions(tag, path): | |
| 718 """images are referenced with their width and height; templates rely on it.""" | |
| 719 if attr(tag, "width") is not None: | |
| 720 return tag | |
| 721 try: | |
| 722 with Image.open(path) as image: | |
| 723 width, height = image.size | |
| 724 except OSError: | |
| 725 return tag # svg and anything else pillow cannot open | |
| 726 close = "/>" if tag.endswith("/>") else ">" | |
| 727 return re.sub(r"\s*/?>$", f' width="{width}" height="{height}"{close}', tag) | |
| 728 | |
| 729 | |
| 730 def crop_preview(image): | |
| 731 """cut the largest centred area with the preview aspect ratio out of | |
| 732 image, then scale it down to the preview size if it is larger.""" | |
| 733 width, height = image.size | |
| 734 ratio = OG_SIZE[0] / OG_SIZE[1] | |
| 735 if width / height > ratio: | |
| 736 crop = (round(height * ratio), height) | |
| 737 else: | |
| 738 crop = (width, round(width / ratio)) | |
| 739 left = (width - crop[0]) // 2 | |
| 740 top = (height - crop[1]) // 2 | |
| 741 image = image.crop((left, top, left + crop[0], top + crop[1])) | |
| 742 if image.width > OG_SIZE[0]: | |
| 743 image = image.resize(OG_SIZE, Image.LANCZOS) | |
| 744 return image | |
| 745 | |
| 746 | |
| 747 def figure(match): | |
| 748 """turn a FIGURE match into a figure with a caption, if the image has a | |
| 749 title. the title becomes the caption and the image's classes move to the | |
| 750 figure, so layout classes place the whole figure. | |
| 751 """ | |
| 752 content = match.group(1) | |
| 753 img = re.search(r"<img\b[^>]*>", content).group(0) | |
| 754 caption = attr(img, "title") | |
| 755 if caption is None: | |
| 756 return match.group(0) | |
| 757 classes = attr(img, "class") | |
| 758 bare = re.sub(r'\s+(?:title|class)="[^"]*"', "", img) | |
| 759 content = content.replace(img, bare, 1) | |
| 760 opening = f'<figure class="{classes}">' if classes else "<figure>" | |
| 761 return f"{opening}{content}<figcaption>{caption}</figcaption></figure>" | |
| 762 | |
| 763 | |
| 764 # -- command line --------------------------------------------------------- | |
| 765 | |
| 766 def collect(paths): | |
| 767 if not paths: | |
| 768 return sorted(SRC.rglob("*.md")) | |
| 769 sources = [] | |
| 770 for raw in paths: | |
| 771 given = Path(raw) | |
| 772 if not given.exists(): | |
| 773 given = SRC / raw | |
| 774 if not given.exists(): | |
| 775 error(f"no such source: {raw}") | |
| 776 given = given.resolve() | |
| 777 if not given.is_relative_to(SRC): | |
| 778 error(f"not under {SRC.name}/: {raw}") | |
| 779 sources += sorted(given.rglob("*.md")) if given.is_dir() else [given] | |
| 780 return sources | |
| 781 | |
| 782 | |
| 783 def main(argv): | |
| 784 global _verbosity | |
| 785 | |
| 786 parser = argparse.ArgumentParser( | |
| 787 description="generate the site from src/ into the build directory.") | |
| 788 parser.add_argument("path", nargs="*", | |
| 789 help="source files or directories. default: all of src/") | |
| 790 parser.add_argument("-c", "--clean", action="store_true", | |
| 791 help="empty the build directory before building") | |
| 792 parser.add_argument("-d", "--draft", action="store_true", | |
| 793 help="also render unpublished pages") | |
| 794 parser.add_argument("-b", "--build-dir", metavar="DIR", | |
| 795 help="override build_dir from config.txt") | |
| 796 parser.add_argument("-r", "--report", action="store_true", | |
| 797 help="print the summary without raising verbosity") | |
| 798 parser.add_argument("-t", "--tags", action="store_true", | |
| 799 help="rebuild tag index pages") | |
| 800 loudness = parser.add_mutually_exclusive_group() | |
| 801 loudness.add_argument("-q", "--quiet", action="store_true", | |
| 802 help="errors only") | |
| 803 loudness.add_argument("-v", "--verbose", action="store_true", | |
| 804 help="errors, warnings and notices; includes the summary") | |
| 805 args = parser.parse_args(argv) | |
| 806 | |
| 807 if args.quiet: | |
| 808 _verbosity = QUIET | |
| 809 elif args.verbose: | |
| 810 _verbosity = VERBOSE | |
| 811 | |
| 812 config = read_config() | |
| 813 build = Path(args.build_dir or config["build_dir"]) | |
| 814 if not build.is_absolute(): | |
| 815 build = ROOT / build | |
| 816 | |
| 817 # --clean empties the whole directory whatever paths were selected. | |
| 818 if args.clean and build.exists(): | |
| 819 shutil.rmtree(build) | |
| 820 build.mkdir(parents=True, exist_ok=True) | |
| 821 | |
| 822 site = Site(config, build, args.draft, args.tags or args.clean) | |
| 823 site.copy_assets() | |
| 824 for source in collect(args.path): | |
| 825 site.page(source) | |
| 826 if site.tags is not None: | |
| 827 site.write_tags() | |
| 828 site.check_links() | |
| 829 | |
| 830 if args.report or _verbosity >= VERBOSE: | |
| 831 print("created {created}, updated {updated}, images {images}, " | |
| 832 "warnings {warnings}".format(**_counts)) | |
| 833 if site.tags: | |
| 834 print("tag indexes: " + ", ".join( | |
| 835 index["name"] for _, index in sorted(site.tags.items()))) | |
| 836 return 0 | |
| 837 | |
| 838 | |
| 839 if __name__ == "__main__": | |
| 840 try: | |
| 841 sys.exit(main(sys.argv[1:])) | |
| 842 except BuildError as failure: | |
| 843 print("error: " + str(failure), file=sys.stderr) | |
| 844 sys.exit(1) |
