view 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
line wrap: on
line source

#!/usr/bin/env python3
"""static site generator. builds the site in the current directory. see
doc/format.md for the source and template format, doc/build.md for how a
build works, doc/tools.md for the command line."""

import argparse
import datetime
import html
import re
import shutil
import sys
import urllib.parse
from pathlib import Path

import markdown
from PIL import Image, ImageOps, features

# the site is the current directory, so a linked copy of this script builds
# the site it is run in.
ROOT = Path.cwd().resolve()
SRC = ROOT / "src"
TPL = ROOT / "tpl"
STATIC = ROOT / "static"
CONFIG = ROOT / "config.txt"

DEFAULT_TEMPLATE = "page.html"
DEFAULT_TAGINDEX = "tag.html"
MARKDOWN_EXTENSIONS = ["extra", "sane_lists"]

CONFIG_KEYS = {"build_dir", "image_sizes", "extra_header_keys", "site_url",
               "index_sections", "index_recent"}

HEADER_KEYS = {
    "title", "subtitle", "description", "timeframe", "created_at",
    "updated_at", "todo", "is_published", "template", "tags", "image",
    "crossref", "repository",
}

# python-markdown's footnotes extension appends its notes to the body in a div
# of this class.
FOOTNOTES = '<div class="footnote">'

# pillow format names that may be resized. webp is only eligible where the
# local pillow was built with it, so the set is decided at import time.
RESIZABLE = {"PNG", "JPEG"}
if features.check("webp"):
    RESIZABLE.add("WEBP")

JPEG_QUALITY = 85


def image_format(image):
    """the pillow format name of image, with mpo reported as jpeg. mpo is a
    jpeg with further images appended, such as a camera's preview. pillow
    opens it at the first image, the photo itself, and handles it as a jpeg.
    """
    return "JPEG" if image.format == "MPO" else image.format


# link preview images. the size is what facebook and linkedin ask for, the
# minimum the smallest that facebook still shows as a large card.
OG_SIZE = (1200, 630)
OG_MINIMUM = (600, 315)

# a paragraph holding only an image, optionally linked. one with a title
# becomes a figure with that title as its caption.
FIGURE = re.compile(r"<p>((?:<a\b[^>]*>)?<img\b[^>]*>(?:</a>)?)</p>")

# one pass over the template: a complete if or loop block, a marker, or any
# other {% ... %}, which is a stray block tag. the shortest body is matched, so
# a block cannot contain a block of its own kind.
TOKEN = re.compile(
    r"\{%\s*(if|loop)\s+([A-Za-z_][A-Za-z0-9_.]*)(?:\|([A-Za-z]+))?\s*%\}"
    r"(.*?)\{%\s*end\1\s*%\}"
    r"|\{\{([A-Za-z_][A-Za-z0-9_.]*)(?:\|([A-Za-z]+))?\}\}"
    r"|\{%.*?%\}",
    re.DOTALL)

QUIET, NORMAL, VERBOSE = 0, 1, 2

_verbosity = NORMAL
_counts = {"created": 0, "updated": 0, "images": 0, "warnings": 0}


class BuildError(Exception):
    """an error stops the build; no correct output is possible."""


def error(msg):
    raise BuildError(msg)


def warn(msg):
    _counts["warnings"] += 1
    if _verbosity >= NORMAL:
        print("warning: " + msg, file=sys.stderr)


def notice(msg):
    # all three severities go to stderr so that they stay in order relative to
    # each other; only the summary is stdout.
    if _verbosity >= VERBOSE:
        print("notice: " + msg, file=sys.stderr)


# -- header blocks --------------------------------------------------------

def parse_header_block(text, where):
    """split a source into its header block and its body.

    key: value lines, ended by the first blank line. a line starting with
    space or tab continues the previous value, joined with a single space,
    the way rfc 5322 folds mail headers.
    """
    lines = text.splitlines()
    if not lines or not lines[0].strip():
        error(f"{where}: does not start with a header block")

    headers = {}
    key = None
    end = len(lines)
    for i, line in enumerate(lines):
        if not line.strip():
            end = i
            break
        if line[:1] in (" ", "\t"):
            if key is None:
                error(f"{where}: line {i + 1}: continuation before any header")
            headers[key] = headers[key] + " " + line.strip()
            continue
        if ":" not in line:
            error(f"{where}: line {i + 1}: not a header line: {line.strip()!r}")
        key, _, value = line.partition(":")
        key = key.strip()
        if key in headers:
            warn(f"{where}: duplicate header key {key!r}")
        headers[key] = value.strip()

    return headers, "\n".join(lines[end + 1:])


def read_config():
    if not CONFIG.exists():
        error(f"{CONFIG.name} not found in {ROOT}")
    headers, _ = parse_header_block(CONFIG.read_text(encoding="utf-8"), CONFIG.name)
    for key in headers:
        if key not in CONFIG_KEYS:
            warn(f"{CONFIG.name}: unknown key {key!r}")
    config = {"build_dir": "www", "image_sizes": "", "extra_header_keys": "",
              "site_url": "", "index_sections": "", "index_recent": "5"}
    config.update(headers)
    config["site_url"] = config["site_url"].rstrip("/")
    if not config["site_url"]:
        error(f"{CONFIG.name}: site_url not set")
    return config


def parse_image_sizes(spec):
    sizes = {}
    for item in spec.split(","):
        item = item.strip()
        if not item:
            continue
        name, _, width = item.partition(":")
        if not width.strip().isdigit():
            error(f"{CONFIG.name}: bad image size {item!r}")
        sizes[name.strip()] = int(width)
    return sizes


# -- templating -----------------------------------------------------------

def is_empty(value):
    return value is None or value == "" or value == []


def test(values, key, cond, where):
    """evaluate an if condition. an undefined key counts as empty."""
    if cond == "isempty":
        return is_empty(values.get(key))
    if cond == "isnotempty":
        return not is_empty(values.get(key))
    error(f"{where}: unknown condition {cond!r} on {key!r}")


def render(template, values, where):
    """render blocks and markers. see doc/format.md.

    values maps keys to strings, or to lists of dictionaries for loops.
    inside a loop the item is the only scope. output is not scanned again.
    """

    def one(match):
        kind, key, cond, inner, mkey, filt = match.groups()

        if kind == "if":
            if test(values, key, cond, where):
                return render(inner, values, where)
            return ""

        if kind == "loop":
            if cond is not None:
                error(f"{where}: condition on loop {key!r}")
            if key not in values:
                warn(f"{where}: undefined template value {key!r}")
                return ""
            items = values[key]
            if not (isinstance(items, list)
                    and all(isinstance(item, dict) for item in items)):
                error(f"{where}: loop value {key!r} is not a list of dictionaries")
            return "".join(render(inner, item, where) for item in items)

        if mkey is None:
            error(f"{where}: stray or malformed block tag {match.group(0)!r}")

        if mkey in values:
            value = values[mkey]
        else:
            warn(f"{where}: undefined template value {mkey!r}")
            value = ""
        if not isinstance(value, str):
            error(f"{where}: template value {mkey!r} is not a string")
        if filt is None or filt == "htmlencode":
            return html.escape(value)
        if filt == "literal":
            return value
        if filt == "urlencode":
            return urllib.parse.quote(value, safe="")
        error(f"{where}: unknown filter {filt!r}")

    return TOKEN.sub(one, template)


# -- tags -----------------------------------------------------------------

def parse_tags(spec):
    """split the tags header on commas. empty items are dropped."""
    return [t.strip() for t in spec.split(",") if t.strip()]


def tag_file(tag):
    """tag index pages go in the build root. the name is the tag in lower
    case, with all characters other than letters and digits removed."""
    return "tag_" + re.sub(r"[^a-z0-9]+", "", tag.lower()) + ".html"


# -- dates ----------------------------------------------------------------

def format_date(value, key, where):
    """the date of an iso date or date and time, as dd.mm.yyyy. a time is
    accepted and dropped. anything else warns and is returned as it is."""
    try:
        moment = datetime.datetime.fromisoformat(value.strip())
    except ValueError:
        warn(f"{where}: {key} is not an ISO date: {value!r}")
        return value
    return moment.strftime("%d.%m.%Y")


# -- files ----------------------------------------------------------------

def copy_if_newer(source, dest):
    dest.parent.mkdir(parents=True, exist_ok=True)
    if dest.exists() and dest.stat().st_mtime >= source.stat().st_mtime:
        return False
    _counts["updated" if dest.exists() else "created"] += 1
    shutil.copy2(source, dest)
    return True


def attr(tag, name):
    match = re.search(r'\b' + name + r'="([^"]*)"', tag)
    return match.group(1) if match else None


def split_url(url):
    """separate the path from the query string and fragment."""
    match = re.match(r"([^#?]*)(.*)", url)
    return match.group(1), match.group(2)


def find_original(wanted):
    """the source file behind an image reference: the file itself if it
    exists, otherwise the same name minus its size infix. None if neither
    exists."""
    if wanted.exists():
        return wanted
    parts = wanted.name.split(".")
    if len(parts) < 3:
        return None
    original = wanted.with_name(".".join(parts[:-2] + parts[-1:]))
    return original if original.exists() else None


# -- the site -------------------------------------------------------------

class Site:
    def __init__(self, config, build, draft, tags):
        self.config = config
        self.build = build
        self.draft = draft
        # tag index file name -> {"name": first spelling seen, "pages": [...]},
        # or None when tag index pages are not rebuilt.
        self.tags = {} if tags else None
        self.sizes = parse_image_sizes(config["image_sizes"])
        self.header_keys = HEADER_KEYS | {
            k.strip() for k in config["extra_header_keys"].split(",") if k.strip()
        }
        self.templates = {}
        self.links = []
        self.images = set()

    # -- assets ----------------------------------------------------------

    def copy_assets(self):
        """copy static/, which holds unlinked global files, and tpl/, which
        holds the layout assets."""
        for base in (STATIC, TPL):
            if not base.is_dir():
                continue
            for item in sorted(base.rglob("*")):
                if not item.is_file() or item.name == ".DS_Store":
                    continue
                if base is TPL and item.suffix.lower() == ".html":
                    continue
                copy_if_newer(item, self.build / item.relative_to(base))

    # -- images ----------------------------------------------------------

    def resolve_image(self, wanted, dest, where):
        """put the referenced image in the build directory, once per run.

        a build that already placed this file says nothing about it again;
        without that, the second reference to a derivative generated moments
        ago reports it as up to date, which reads like a contradiction.
        """
        # two references can spell the same file differently, so the key is the
        # resolved path rather than the one built from the reference.
        key = dest.resolve()
        if key in self.images:
            return True
        placed = self.place_image(wanted, dest, where)
        if placed:
            self.images.add(key)
        return placed

    def place_image(self, wanted, dest, where):
        """a reference either names a file that exists in the source tree, or a
        derivative to be generated from the same name minus its size infix.
        """
        original = find_original(wanted)
        if original is None:
            warn(f"{where}: broken image reference {wanted.name!r}")
            return False
        if original == wanted:
            if copy_if_newer(wanted, dest):
                notice(f"{where}: {wanted.name} copied verbatim")
            return True

        token = wanted.name.split(".")[-2]

        if token.isdigit():
            width = int(token)
        elif token in self.sizes:
            width = self.sizes[token]
        else:
            warn(f"{where}: unknown image size {token!r}, copying original")
            copy_if_newer(original, dest)
            return True

        if dest.exists() and dest.stat().st_mtime >= original.stat().st_mtime:
            notice(f"{where}: {dest.name} up to date")
            return True

        with Image.open(original) as image:
            # the format has to be read before resizing: a resized image is a
            # new object with no format, and pillow would then pick its writer
            # from the extension, which is not the authority here.
            fmt = image_format(image)
            if fmt not in RESIZABLE:
                warn(f"{where}: cannot resize {original.name} ({fmt})")
                return False
            # the derivative has no exif, so a rotation recorded there is
            # applied to the pixels. the colour profile is kept separately.
            icc = image.info.get("icc_profile")
            image = ImageOps.exif_transpose(image)
            if image.width < width:
                warn(f"{where}: {original.name} is narrower than {width}px")
                copy_if_newer(original, dest)
                return True
            height = round(image.height * width / image.width)
            resized = image.resize((width, height), Image.LANCZOS)

        dest.parent.mkdir(parents=True, exist_ok=True)
        options = {"icc_profile": icc} if icc else {}
        if fmt == "JPEG":
            options["quality"] = JPEG_QUALITY
        resized.save(dest, format=fmt, **options)
        _counts["images"] += 1
        notice(f"{where}: generated {dest.name} at {width}x{height}")
        return True

    # -- references in the generated html --------------------------------

    def rewrite(self, body, source, out_dir, images, where):
        """rewrite links, copy referenced files, size referenced images.

        this runs on the markdown output rather than on the markdown, so a
        hand-written html fragment in a source file is treated the same way.
        it assumes double-quoted attributes, which is what python-markdown
        emits.

        every local image reference is appended to images as a pair of the
        referenced source path and the alt text, in page order.
        """
        src_dir = source.parent

        def anchor(match):
            tag = match.group(0)
            href = attr(tag, "href")
            if href is None or not local(href):
                return tag
            path, tail = split_url(href)
            if not path:
                return tag
            if path.endswith(".md"):
                path = path[:-3] + ".html"
                tag = tag.replace(f'href="{href}"', f'href="{path}{tail}"', 1)
            elif not path.endswith(".html"):
                # a pdf, an archive, a text file: copied verbatim, no
                # derivative logic.
                referenced = src_dir / urllib.parse.unquote(path)
                if referenced.is_file():
                    copy_if_newer(referenced, out_dir / urllib.parse.unquote(path))
            self.links.append((where, out_dir / urllib.parse.unquote(path), path))
            return tag

        def image(match):
            tag = match.group(0)
            src = attr(tag, "src")
            if src is None or not local(src):
                return tag
            path, _ = split_url(src)
            if not path:
                return tag
            name = urllib.parse.unquote(path)
            dest = out_dir / name
            images.append((src_dir / name, html.unescape(attr(tag, "alt") or "")))
            self.links.append((where, dest, path))
            if not self.resolve_image(src_dir / name, dest, where):
                return tag
            return add_dimensions(tag, dest)

        body = re.sub(r"<a\b[^>]*>", anchor, body)
        body = re.sub(r"<img\b[^>]*?>", image, body)
        return FIGURE.sub(figure, body)

    # -- link preview image -----------------------------------------------

    def preview_image(self, headers, source, out_dir, images, where):
        """pick and generate the link preview image of a page. see
        doc/build.md.

        returns the template values ogImage, ogImageWidth, ogImageHeight and
        ogImageAlt, or no values when the template default applies.
        """
        name = headers.get("image")
        if name:
            path = source.parent / name
            if path.is_file():
                values = self.write_preview(path, "", source, out_dir, True, where)
                if values:
                    return values
            else:
                warn(f"{where}: broken image reference {name!r} in image header")

        # the first body image that can be processed and is large enough
        for wanted, alt in images:
            original = find_original(wanted)
            if original is None:
                continue
            try:
                with Image.open(original) as image:
                    fmt = image_format(image)
                    size = ImageOps.exif_transpose(image).size
            except OSError:
                continue  # svg and anything else pillow cannot open
            if (fmt in RESIZABLE and size[0] >= OG_MINIMUM[0]
                    and size[1] >= OG_MINIMUM[1]):
                return self.write_preview(original, alt, source, out_dir,
                                          False, where)
        return {}

    def write_preview(self, original, alt, source, out_dir, explicit, where):
        """crop the original to the preview aspect ratio and scale it down to
        the preview size, never up. an original of exactly that size is
        copied. the file name contains the modification time of the original,
        so a changed image gets a new address and consumers fetch it again.
        an existing file is not written again.
        """
        stamp = int(original.stat().st_mtime)
        dest = out_dir / "img" / f"og_{source.stem}_{stamp}{original.suffix}"

        if dest.exists():
            notice(f"{where}: {dest.name} up to date")
        else:
            with Image.open(original) as image:
                fmt = image_format(image)
                if fmt not in RESIZABLE:
                    warn(f"{where}: cannot crop {original.name} ({fmt}) "
                         "for the link preview")
                    return {}
                icc = image.info.get("icc_profile")
                image = ImageOps.exif_transpose(image)
                if image.size == OG_SIZE:
                    copy_if_newer(original, dest)
                    notice(f"{where}: {dest.name} copied verbatim")
                    image = None
                else:
                    if explicit:
                        warn(f"{where}: image {original.name} is "
                             f"{image.width}x{image.height}, cropped to "
                             f"{OG_SIZE[0]}x{OG_SIZE[1]}")
                    image = crop_preview(image)

            if image is not None:
                dest.parent.mkdir(parents=True, exist_ok=True)
                options = {"icc_profile": icc} if icc else {}
                if fmt == "JPEG":
                    options["quality"] = JPEG_QUALITY
                image.save(dest, format=fmt, **options)
                _counts["images"] += 1
                notice(f"{where}: generated {dest.name} at "
                       f"{image.width}x{image.height}")

        with Image.open(dest) as image:
            width, height = image.size
        rel = dest.relative_to(self.build).as_posix()
        return {
            "ogImage": self.config["site_url"] + "/" + urllib.parse.quote(rel),
            "ogImageWidth": str(width),
            "ogImageHeight": str(height),
            "ogImageAlt": alt,
        }

    # -- pages -----------------------------------------------------------

    def template(self, name):
        if name not in self.templates:
            path = TPL / name
            if not path.is_file():
                error(f"template {name!r} not found in {TPL.name}/")
            self.templates[name] = path.read_text(encoding="utf-8")
        return self.templates[name]

    def page(self, source):
        rel = source.relative_to(SRC)
        out_file = self.build / rel.with_suffix(".html")
        where = str(rel)

        # an up-to-date page still goes into the tag index, so its headers
        # are read before the date check when tag index pages are rebuilt.
        headers = None
        if self.tags is not None:
            headers, body_md = self.read(source, where)
            if headers is None:
                return
            self.index_tags(headers, rel, where)

        if out_file.exists() and out_file.stat().st_mtime >= source.stat().st_mtime:
            notice(f"{where}: up to date")
            return

        if headers is None:
            headers, body_md = self.read(source, where)
            if headers is None:
                return

        body = markdown.markdown(body_md, extensions=MARKDOWN_EXTENSIONS)
        images = []
        body = self.rewrite(body, source, out_file.parent, images, where)
        # the footnotes are split off so that the template can put the
        # repository and crossref links between the text and the notes.
        cut = body.rfind(FOOTNOTES)
        footnotes = body[cut:] if cut >= 0 else ""
        body = body[:cut] if cut >= 0 else body

        depth = len(rel.parent.parts)
        values = {f"site.{k}": v for k, v in self.config.items()}
        values.update(headers)
        values["body"] = body
        values["footnotes"] = footnotes
        values["crossrefUrl"] = self.crossref(headers.get("crossref", ""),
                                              out_file.parent, where)
        values["relRoot"] = "../" * depth if depth else "./"
        values["absRoot"] = "/"
        values["tags"] = [
            {"name": t, "url": values["relRoot"] + tag_file(t)}
            for t in parse_tags(headers.get("tags", ""))
        ]
        values["pageUrl"] = self.page_url(rel.with_suffix(".html").as_posix())
        values["metaDescription"] = (headers.get("description")
                                     or headers.get("subtitle") or "")
        values.update(self.dates(headers, where))
        values.update(self.preview_image(headers, source, out_file.parent,
                                         images, where))

        name = headers.get("template") or DEFAULT_TEMPLATE
        page = render(self.template(name), values, where)

        out_file.parent.mkdir(parents=True, exist_ok=True)
        _counts["updated" if out_file.exists() else "created"] += 1
        out_file.write_text(page, encoding="utf-8")

    def crossref(self, value, out_dir, where):
        """the address of the page named in the crossref header, relative to
        the page, with .md rewritten to .html like a body link. the target is
        checked like a body link. empty when the header is not set."""
        value = value.strip()
        if not value:
            return ""
        if not local(value):
            warn(f"{where}: crossref is not an internal reference: {value!r}")
            return value
        path, tail = split_url(value)
        if path.endswith(".md"):
            path = path[:-3] + ".html"
        self.links.append((where, out_dir / urllib.parse.unquote(path), path))
        return path + tail

    def page_url(self, path):
        """the absolute address of a page, given its path relative to the
        build root. an index.html is addressed by its directory."""
        if path == "index.html" or path.endswith("/index.html"):
            path = path[:-len("index.html")]
        return self.config["site_url"] + "/" + urllib.parse.quote(path)

    def dates(self, headers, where):
        """createdDate and updatedDate for display. updatedDate is empty when
        it shows the same date as createdDate, whatever the times."""
        created = headers.get("created_at", "").strip()
        updated = headers.get("updated_at", "").strip()
        created = format_date(created, "created_at", where) if created else ""
        updated = format_date(updated, "updated_at", where) if updated else ""
        return {
            "createdDate": created,
            "updatedDate": "" if updated == created else updated,
        }

    def read(self, source, where):
        """read and check a source. returns its headers and markdown body, or
        None twice when the page is unpublished and draft mode is off."""
        headers, body_md = parse_header_block(
            source.read_text(encoding="utf-8"), where)

        if headers.get("is_published", "").strip() != "1":
            if not self.draft:
                warn(f"{where}: unpublished, skipped")
                return None, None
            warn(f"{where}: unpublished, rendered as draft")

        if not headers.get("title"):
            error(f"{where}: missing title")
        for key in headers:
            if key not in self.header_keys:
                warn(f"{where}: unknown header key {key!r}")
        if not body_md.strip():
            warn(f"{where}: no body")
        return headers, body_md

    # -- tag index pages --------------------------------------------------

    def index_tags(self, headers, rel, where):
        entry = {k: v for k, v in headers.items() if k != "tags"}
        entry["url"] = rel.with_suffix(".html").as_posix()
        entry["descOrSubtitle"] = (headers.get("description")
                                   or headers.get("subtitle") or "")
        for tag in parse_tags(headers.get("tags", "")):
            index = self.tags.setdefault(tag_file(tag), {"name": tag, "pages": []})
            if index["name"] != tag:
                warn(f"{where}: tag {tag!r} shares its index page with "
                     f"{index['name']!r}")
            index["pages"].append(entry)

    def write_tags(self):
        """write one index page per tag into the build root. pages are listed
        newest first by created_at, then by title. pages without created_at
        come last."""
        for file, index in sorted(self.tags.items()):
            pages = sorted(index["pages"], key=lambda p: p["title"])
            pages.sort(key=lambda p: p.get("created_at", ""), reverse=True)
            notice(f"{file}: tag {index['name']!r}, pages: {len(pages)}")

            values = {f"site.{k}": v for k, v in self.config.items()}
            values["tag"] = index["name"]
            values["pages"] = pages
            values["relRoot"] = "./"
            values["absRoot"] = "/"
            values["pageUrl"] = self.page_url(file)
            page = render(self.template(DEFAULT_TAGINDEX), values, file)

            out_file = self.build / file
            _counts["updated" if out_file.exists() else "created"] += 1
            out_file.write_text(page, encoding="utf-8")

    def check_links(self):
        for where, target, raw in self.links:
            if not target.exists():
                warn(f"{where}: broken link {raw!r}")


def local(url):
    """a reference is local unless it has a scheme or is protocol-relative."""
    return not urllib.parse.urlsplit(url).scheme and not url.startswith("//")


def add_dimensions(tag, path):
    """images are referenced with their width and height; templates rely on it."""
    if attr(tag, "width") is not None:
        return tag
    try:
        with Image.open(path) as image:
            width, height = image.size
    except OSError:
        return tag  # svg and anything else pillow cannot open
    close = "/>" if tag.endswith("/>") else ">"
    return re.sub(r"\s*/?>$", f' width="{width}" height="{height}"{close}', tag)


def crop_preview(image):
    """cut the largest centred area with the preview aspect ratio out of
    image, then scale it down to the preview size if it is larger."""
    width, height = image.size
    ratio = OG_SIZE[0] / OG_SIZE[1]
    if width / height > ratio:
        crop = (round(height * ratio), height)
    else:
        crop = (width, round(width / ratio))
    left = (width - crop[0]) // 2
    top = (height - crop[1]) // 2
    image = image.crop((left, top, left + crop[0], top + crop[1]))
    if image.width > OG_SIZE[0]:
        image = image.resize(OG_SIZE, Image.LANCZOS)
    return image


def figure(match):
    """turn a FIGURE match into a figure with a caption, if the image has a
    title. the title becomes the caption and the image's classes move to the
    figure, so layout classes place the whole figure.
    """
    content = match.group(1)
    img = re.search(r"<img\b[^>]*>", content).group(0)
    caption = attr(img, "title")
    if caption is None:
        return match.group(0)
    classes = attr(img, "class")
    bare = re.sub(r'\s+(?:title|class)="[^"]*"', "", img)
    content = content.replace(img, bare, 1)
    opening = f'<figure class="{classes}">' if classes else "<figure>"
    return f"{opening}{content}<figcaption>{caption}</figcaption></figure>"


# -- command line ---------------------------------------------------------

def collect(paths):
    if not paths:
        return sorted(SRC.rglob("*.md"))
    sources = []
    for raw in paths:
        given = Path(raw)
        if not given.exists():
            given = SRC / raw
        if not given.exists():
            error(f"no such source: {raw}")
        given = given.resolve()
        if not given.is_relative_to(SRC):
            error(f"not under {SRC.name}/: {raw}")
        sources += sorted(given.rglob("*.md")) if given.is_dir() else [given]
    return sources


def main(argv):
    global _verbosity

    parser = argparse.ArgumentParser(
        description="generate the site from src/ into the build directory.")
    parser.add_argument("path", nargs="*",
                        help="source files or directories. default: all of src/")
    parser.add_argument("-c", "--clean", action="store_true",
                        help="empty the build directory before building")
    parser.add_argument("-d", "--draft", action="store_true",
                        help="also render unpublished pages")
    parser.add_argument("-b", "--build-dir", metavar="DIR",
                        help="override build_dir from config.txt")
    parser.add_argument("-r", "--report", action="store_true",
                        help="print the summary without raising verbosity")
    parser.add_argument("-t", "--tags", action="store_true",
                        help="rebuild tag index pages")
    loudness = parser.add_mutually_exclusive_group()
    loudness.add_argument("-q", "--quiet", action="store_true",
                          help="errors only")
    loudness.add_argument("-v", "--verbose", action="store_true",
                          help="errors, warnings and notices; includes the summary")
    args = parser.parse_args(argv)

    if args.quiet:
        _verbosity = QUIET
    elif args.verbose:
        _verbosity = VERBOSE

    config = read_config()
    build = Path(args.build_dir or config["build_dir"])
    if not build.is_absolute():
        build = ROOT / build

    # --clean empties the whole directory whatever paths were selected.
    if args.clean and build.exists():
        shutil.rmtree(build)
    build.mkdir(parents=True, exist_ok=True)

    site = Site(config, build, args.draft, args.tags or args.clean)
    site.copy_assets()
    for source in collect(args.path):
        site.page(source)
    if site.tags is not None:
        site.write_tags()
    site.check_links()

    if args.report or _verbosity >= VERBOSE:
        print("created {created}, updated {updated}, images {images}, "
              "warnings {warnings}".format(**_counts))
        if site.tags:
            print("tag indexes: " + ", ".join(
                index["name"] for _, index in sorted(site.tags.items())))
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1:]))
    except BuildError as failure:
        print("error: " + str(failure), file=sys.stderr)
        sys.exit(1)