# HG changeset patch # User ark # Date 1792673983 -7200 # Node ID 71dd8d58a8e5d491e031f43c588130e283a19117 cleaned up re-init from net_wobblyhead_www project tooling diff -r 000000000000 -r 71dd8d58a8e5 .hgignore --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.hgignore Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,4 @@ +.DS_Store +__pycache__ +example/www/ +example/dist/ diff -r 000000000000 -r 71dd8d58a8e5 README.md --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/README.md Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,48 @@ +# wobbly_ssg + +A small static site generator. It turns a tree of Markdown files into a tree of +HTML pages, using plain HTML templates. Images referenced from the pages are +copied or scaled down. Pages get link preview metadata and tags, and each +tag gets an index page. + +The generator is a single Python script. It needs Python 3 with +python-markdown and Pillow, and nothing else. There are no plugins and no +JavaScript toolchain. + +## Quick start + + cd example + ../tools/make_site.py -c -r + +The site in `example/` is built into `example/www/`. Open +`example/www/index.html` in a browser. + +All tools work on the site in the current directory. + +## Documents + +- [doc/design.md](doc/design.md) -- requirements and design decisions. +- [doc/format.md](doc/format.md) -- the site layout, the configuration, the + source format and the template syntax. +- [doc/build.md](doc/build.md) -- what a build does: images, link previews, + tag index pages, link checking, reporting. +- [doc/tools.md](doc/tools.md) -- the command line of every tool. +- [doc/history.md](doc/history.md) -- material removed from the documentation. + +## Tools + +- `tools/make_site.py` builds the site. +- `tools/make_dist.sh` packs the built site into an archive for a given + address. +- `tools/get_version.sh` prints the version of the site from its Mercurial + tags. +- `tools/update_index.py` rewrites the entry lists of the index pages from + the headers of the pages they list. +- `tools/update_updated.sh` sets the `updated_at` header from the file + modification time. + +## Example site + +`example/` holds a minimal site: a configuration, a few pages with an image, +a `robots.txt`, and a template set. The stylesheet keeps the browser +defaults and adjusts only spacing, line length, tables and images. diff -r 000000000000 -r 71dd8d58a8e5 doc/build.md --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/doc/build.md Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,201 @@ +# How a build works + +This document describes what `make_site.py` does. Its command line is in +[tools.md](tools.md), the formats it reads are in [format.md](format.md). + +## Order of work + +1. Read `config.txt`. Create the build directory, after emptying it if a + clean build was asked for. +2. Copy the files of `static/` and the non-HTML files of `tpl/` that are + newer than their copies in the build directory. +3. Build each selected page, by default every `.md` file below `src/`: + - Skip the page if its output exists and is not older than the source. + - Read the header block. Skip an unpublished page, unless draft mode is + on. + - Convert the Markdown body to HTML. + - Rewrite links, copy referenced files, place images and add their + dimensions, turn captioned images into figures. + - Split off the footnotes. + - Pick the link preview image and write it if needed. + - Render the template and write the page. +4. Write the tag index pages, if they are being rebuilt. +5. Check the links of all pages built in this run. + +Tag index pages are rebuilt with `--tags`, and always with `--clean`. Then +the header block of every selected page is read before the date check, so +pages that are up to date are listed too. + +Output paths mirror source paths. The build directory is `build_dir` from +`config.txt`, or the directory given with `--build-dir`. + +## Incremental builds + +Without `--clean`, the build compares modification times only: a page with +its source, a generated image with its original, a copied file with its +source. Nothing else is tracked, and nothing is removed. As a result: + +- A changed template or configuration rebuilds nothing. +- A page that is unpublished or deleted keeps its old output. +- Link preview images from earlier versions of an image stay. + +A clean build fixes all of these, and is the normal way to build for +publishing. + +## Unpublished pages + +A page without `is_published: 1` is skipped with a warning. In draft mode, +`--draft`, it is built, and the warning says so. + +## Reporting + +Messages have three severities. All of them go to standard error. + +- Error -- no correct output is possible. The build stops. Examples: a + missing `config.txt` or `site_url`, a source that does not start with a + header block, a page without a title, a missing template, a template + syntax error. +- Warning -- output is produced but is probably wrong. Examples: a broken + link, an unknown image size, an unknown or duplicate header key, an unknown + configuration key, an original smaller than the size asked for, a skipped + unpublished page, a page rendered as a draft, a page with no body, two + spellings of a tag sharing one index page, a date that is not an ISO date, + an `image` header that points nowhere or at an image that is not 1200x630, + an image that cannot be cropped for the link preview. +- Notice -- normal events. A page skipped because it is up to date, an image + copied or generated, a tag index page written with its tag and number of + pages, a link preview image generated or found up to date. + +Errors and warnings are printed by default. `--quiet` prints errors only. +`--verbose` adds notices. + +The summary counts the files created and updated, the images generated and +the warnings. When tag index pages were written, a second line lists their +tags. The summary goes to standard output, with `--report` or `--verbose`. + +The exit code is 0 on success, 1 when an error stopped the build, and 2 for +a usage error. Warnings do not change the exit code. + +## Images + +### Resolving a reference + +An image reference names either a file in the source tree or a smaller copy +to be generated: + +1. If the path exists as a source file, it is copied as it is. +2. Otherwise, for formats that can be scaled, the last dot-separated part + before the extension is taken as a size. If the name without that part + exists, the copy is generated from it. +3. Otherwise the reference is broken and produces a warning. + +A size that is neither a number nor a name from `image_sizes` produces a +warning, and the original is copied under the requested name. + +Each output file is placed once per build. Further references to it, from the +same page or another, are not checked or reported again. A broken reference +produces a warning on every page that has it. + +### Formats + +PNG and JPEG can be scaled. WebP can be scaled where the local Pillow +supports it, so the same site can build differently on another machine. An +MPO file, a JPEG with further images appended as some cameras write it, is +treated as a JPEG. + +The format is read from the content of the original. A PNG named `.gif` is +handled as a PNG, and its scaled copy is written as a PNG too, whatever the +extension says. + +### Scaled copies + +Only the width is given; the aspect ratio is kept. The image is resampled +with the Lanczos filter. + +A scaled copy keeps the colour profile of the original. The Exif orientation +is applied to the pixels first, then the Exif data is dropped. JPEG copies +are written at quality 85; other formats use the Pillow defaults. + +An original narrower than the requested width is not scaled up. It is copied +unchanged under the requested name, with all its metadata, and the build +produces a warning. + +### Dimensions + +Every local `img` in a page body, from Markdown or from HTML, gets `width` +and `height` attributes from the file that was placed. Images that already +have a `width` attribute, and images Pillow cannot open, such as SVG, are +left alone. + +## Link preview + +### The image + +The preview image of a page is picked in this order: + +1. The `image` header. An image of exactly 1200x630 is copied. Any other size + is cropped as described below, with a warning. A header that points + nowhere produces a warning, and the search goes on. +2. The first local image in the body that can be scaled and whose original is + at least 600x315. The original is used, not the scaled copy the page + shows. Its alt text becomes the alt text of the preview. +3. None. The template names a default image, or writes no image tags. + +600x315 is the smallest size Facebook still shows as a large card. + +Cropping cuts the largest centred area with an aspect ratio of 1200:630 out +of the image. If that area is larger than 1200x630, it is scaled down to that +size; it is never scaled up. A portrait photo loses its top and bottom. Where +that cuts off the subject, a prepared image in the `image` header avoids it. +The preview keeps the format and colour profile of the original and loses +its Exif data, like a scaled copy. + +The image is written next to the page output, in the directory `img`, as +`og__`. For `first_steps.md` with +a JPEG this is, for example, `img/og_first_steps_1772371200.jpg`. The +modification time is that of the original image, in whole seconds since +1970. Consumers cache preview images by address, so a changed image gets a +new address. An existing file of that name is not written again. + +### Page head + +The generator supplies the values; the templates write the tags. The example +template writes: + +- `meta name="description"` from `metaDescription` +- `link rel="canonical"` from `pageUrl` +- `og:type` (`website`), `og:site_name`, `og:title`, `og:description`, + `og:url` +- `og:image`, `og:image:width`, `og:image:height`, `og:image:alt` +- `twitter:card` (`summary_large_image`) + +The addresses are absolute and built from `site_url`. A page named +`index.html` is addressed by its directory: `src/index.md` becomes +`https://www.example.org/`, not `https://www.example.org/index.html`. A +server delivers the same page either way, but consumers treat the two +addresses as two pages. + +## Tag index pages + +There is one tag index page per tag, in the build root. It lists only pages +selected for this build and rendered: published pages, and unpublished ones in +draft mode. A build of part of the site therefore writes incomplete tag index +pages, and they replace complete ones from an earlier build. Tag index pages +are always written, without a date check. + +## Link checking + +Links are checked after all pages have been written. A link is valid if its +target exists in the build directory, so pages built later in the same run +count. + +Only internal links are checked: links in the body, image references, and +the `crossref` header. + +Unpublished pages are not built, so a link to one produces a warning, as +does a link to a file that does not exist. In draft mode these warnings +disappear. + +When only part of the site is built, only the links of the selected pages +are checked. Targets left from an earlier build count as present. Built into +a clean directory, a subset produces warnings for every link outside it. diff -r 000000000000 -r 71dd8d58a8e5 doc/design.md --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/doc/design.md Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,113 @@ +# Design notes + +## Requirements + +The generator was written for a personal site. It is mostly a gallery of +projects, with posts and links to other sites. Pages have tags, and the tags +are the navigation. Links to the site get shared, so pages need link preview +metadata. There are no comments and no other dynamic parts. The site is +updated about once a week at most. + +The toolchain avoids Node.js and npm. Python with python-markdown and Pillow +is the whole dependency list. The build runs on the author's machine, and only +the finished output goes to the server. + +The images are mostly JPEG photos from a phone, plus screenshots. They +document things; fidelity is not a goal. They do need the right orientation, +no location data in the published copies, and screenshots have to stay +legible. + +Because the site changes rarely, few moving parts matter more than build +speed. Whoever comes back to it after months has to be able to read the whole +generator. + +## Decisions + +### Clean builds + +The normal workflow is a clean build, followed by replacing the whole +published site with an archive of the output. Incremental builds are a +convenience during writing. They only compare the dates of sources and +outputs, and they never remove files. See [build.md](build.md). + +### Header blocks + +A page starts with `key: value` lines, folded like mail headers. This is not +YAML: there is no quoting, no nesting and no fence. Every value is a string. +The site configuration uses the same format. + +Unknown header keys are passed to the templates and produce a warning. The +warning catches typos. It does not restrict what keys a site may use: a key +stops warning once it is listed in the configuration. + +### Mirrored paths + +The output tree mirrors the source tree. The generator creates no directories +of its own and gives `index.md` no special role. Navigation and directory +indexes are written by hand, or kept up to date with `update_index.py`. + +### Errors and warnings + +An error stops the build. It is used only where no correct output is possible, +such as a page without a title. Everything else produces output and a +warning: broken links, unknown sizes, unknown keys. A build with warnings +still exits successfully. + +### Markdown + +python-markdown with the `extra` bundle and `sane_lists`. `smarty` is off, +so quotes and dashes stay as written. + +### Images + +Image sizes are requested in the file name of the reference, such as +`photo.800.jpg`, so the Markdown stays standard. The original is the name +without that part. + +The format of an image is decided by its content, not by its extension. A +generated image keeps the format of its original. There is no format +conversion. + +Phone photos may be stored sideways, with the rotation recorded only in the +Exif (Exchangeable Image File Format) data. Generated images have the rotation +applied to their pixels and contain no Exif data, so location and camera +details are not published. They keep the colour profile of the original, +because phone cameras record in a wider colour space than sRGB. Images are +never scaled up. + +Files referenced verbatim, including the originals behind linked thumbnails, +are copied unchanged with all their metadata. + +### Link previews + +Services that show a preview card for a shared link read tags in the page +head. There is no standard all of them follow. Most read the Open Graph tags, +X wants its own `twitter:card` tag, and search engines read the description +meta tag. Each one crops, sizes and caches the image in its own way. The +generator aims at a common set of tags that most of them understand. + +The generator supplies the values; the templates write the tags. Preview +images are cut to 1200x630, the size Facebook and LinkedIn ask for. + +Consumers fetch a page on their own, so the canonical address and the image +address are absolute. They are built from the production address in the +configuration. `make_dist.sh` replaces it in a copy of the output when an +archive is meant for another address, such as a test server. + +### Templates + +Templates are plain HTML with value markers and two kinds of block: a +condition and a loop. Blocks of the same kind cannot be nested. Values are +HTML-escaped unless a filter says otherwise. + +### Accepted limitations + +- A file name with dots can be read as a size request. A reference to + `my.photo.png` with no such file present is taken as a request for size + `photo` of `my.png`. +- Building a subset of the site into a clean directory produces link + warnings for everything outside the subset, and incomplete tag index pages. +- Files from `static/`, `tpl/` and `src/` are copied into one tree. Nothing + detects one of them overwriting another. +- A changed template or configuration does not cause a rebuild. A clean + build does. diff -r 000000000000 -r 71dd8d58a8e5 doc/format.md --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/doc/format.md Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,393 @@ +# Format + +This document describes everything a site author writes: the site layout, the +configuration, the page sources and the templates. What the generator does +with them is in [build.md](build.md). + +## Site layout + +A site is a directory. The tools are run in it. + +- `config.txt` -- the site configuration. +- `src/` -- the page sources, and the images and other files they reference. +- `static/` -- files copied to the output as they are, which no page + references: a favicon, `robots.txt`. +- `tpl/` -- the templates and their assets: stylesheets, images, fonts. +- `www/` -- the build directory, configurable. It is output, never input. +- `dist/` -- archives written by `make_dist.sh`. + +The output tree mirrors the source tree. `src/notes/first_steps.md` becomes +`www/notes/first_steps.html`, and an image next to it is placed next to the +output. + +The generator creates only the directories it needs to mirror the source. +`index.md` is an ordinary source with no special role. Where directory-style +links are wanted, they have to be written out. + +Files from `static/`, from `tpl/` (all except `.html` files) and from `src/` +all end up in the build directory. They must not overlap. + +All text files are UTF-8. The output is UTF-8. `.DS_Store` files are not +copied. + +## Site configuration + +`config.txt` uses the same format as the header block of a page, described +below. It has no body. A missing `config.txt` is an error, and an unknown key +produces a warning. + +Keys: + +- `site_url` -- required. The public address of the site, without a trailing + slash. The absolute addresses in the page head are built from it. +- `build_dir` -- the output directory. Defaults to `www`. +- `image_sizes` -- symbolic image sizes, as a comma-separated list of + `:` pairs. +- `extra_header_keys` -- a comma-separated list of page header keys that + should not produce a warning. +- `index_sections` -- the sections of the root index page that + `update_index.py` maintains. A comma-separated list of + `:` pairs. See [tools.md](tools.md). +- `index_recent` -- the number of entries in each of those sections. + Defaults to 5. + +All values are available to templates with a `site.` prefix. + +Example: + + site_url: https://www.example.org + build_dir: www + image_sizes: small:300, half:400, wide:800 + extra_header_keys: location + index_sections: notes:Recent notes + index_recent: 3 + +A change to `image_sizes` takes effect for existing images only after a clean +build. + +## Pages + +A page is a header block, a blank line and a body. A source that does not +start with a header block is an error. + +Further blank lines between the header block and the body are ignored, and so +are blank lines at the end of the file. A page with headers and no body +produces an empty page and a warning. + +### Header block + +Lines of `key: value`. The first blank line ends the block. + +A value is literal text to the end of the line. There is no quoting, nesting +or list syntax. + +Long values are folded the way mail headers are (RFC 5322). A line that starts +with a space or a tab continues the previous value, and the parts are joined +with a single space. Leading whitespace is therefore significant in the header +block: a continuation line that loses its indentation becomes an invalid +header line. + +The order of keys does not matter. A duplicate key produces a warning, and the +later value wins. + +Example: + + title: First steps + subtitle: Notes from the first week, + written down later + tags: Notes, Model making + created_at: 2026-03-01 + updated_at: 2026-03-04 + is_published: 1 + +### Header keys + +`title` is the only required key. A page without a title is an error. + +Keys the generator acts on: + +- `title` -- the page title. The template uses it for the page heading. +- `is_published` -- `1` publishes the page. Anything else, or no value, + leaves it unpublished. Unpublished pages are only built in draft mode. +- `tags` -- a comma-separated list of tags. Empty items are dropped. Each tag + links to a tag index page, see [Tag index pages](#tag-index-pages). +- `template` -- the file name of a template in `tpl/` to use instead of + `page.html`. +- `description` -- one or two sentences summarising the page, for search + results and link previews. Without it, `subtitle` is used. +- `image` -- the link preview image, as a path relative to the source. It is + expected to be 1200x630 pixels. See [build.md](build.md). +- `crossref` -- the path of a related page, relative to the source, like a + link in the body. A `.md` extension is rewritten to `.html`, and the target + is checked like a body link. A value with a scheme, such as `https:`, + produces a warning and is passed on unchanged. +- `created_at` -- an ISO date, `YYYY-MM-DD`, or an ISO date and time such as + `2026-03-01T14:30:05+01:00`. Templates get the date as `dd.mm.yyyy`. +- `updated_at` -- as `created_at`. + +The generator reads the dates only to format them and to sort tag index +pages. A time is accepted and not shown. The date is shown as written, +without converting the time zone. A value that is not a valid ISO date +produces a warning and is shown as written. The accepted forms are those of +Python's `datetime.fromisoformat`, which accepts more of them from Python 3.11 +on. + +Known keys without defined format, passed to templates as they are: + +- `subtitle` -- a one-line summary. +- `timeframe` -- a period, as free text, such as `03.2024 - 06.2025`. +- `repository` -- the address of the source repository of a project. +- `todo` -- notes for the author. + +Any other key is passed to templates as well, and produces a warning unless +it is listed in `extra_header_keys`. The warning only catches typos in keys +that are known. + +### Body + +The body is Markdown, processed by python-markdown with two extensions: + +- `extra` -- abbreviations, attribute lists, definition lists, fenced code, + footnotes, Markdown inside HTML, and tables. +- `sane_lists`. + +The top-level heading comes from the `title` header through the template. The +body usually starts at the second level. + +HTML in the body is passed through. Links and images in it are handled like +those written in Markdown, as long as attributes are in double quotes. + +### Links + +Paths are relative to the source file. + +A link to another page can use the `.md` extension, which is rewritten to +`.html`, or the `.html` extension directly. Fragments and query strings are +kept. A `.md` link that points nowhere is still rewritten. + +A link to a file that is neither a page nor an image, such as a PDF or an +archive, copies that file to the mirrored output path. + +Links with a scheme, such as `https:` or `mailto:`, and protocol-relative +links are left alone. All other links are checked, see [build.md](build.md). + +### Tables + +Standard pipe tables. Outer pipes are optional. + + | Year | Model | Scale | + |------|------------|------:| + | 2024 | Tug | 1:50 | + | 2025 | Lighthouse | 1:87 | + +Alignment markers produce an inline `text-align` style on every cell. +Attribute lists cannot be attached to tables, so all tables share one style. +Where Markdown cannot express a table, it can be written in HTML. + +### Footnotes + +A reference is `[^label]` in the text. A definition is `[^label]:` at the +start of a line, followed by the text. The label identifies the note and can +be any string without whitespace; it is not the printed number. Further +paragraphs of a note are indented by four spaces. + + The hull was planked twice.[^planks] + + [^planks]: The first planks were too thick. + +Notes are numbered in the order of their definitions, not of their +references. Putting each definition right after the paragraph that refers to +it keeps the two orders the same. + +A definition without a reference is still printed and numbered. A reference +without a definition stays in the text as written, without a warning. + +The notes are collected at the end of the body in a `div` of class +`footnote`. The generator passes them to the template separately, as +`footnotes`. The generated ids are `fn:` and `fnref:` followed by the label; +they share the id space of the page. + +### Images + +An image is standard Markdown, with the path relative to the source file: + + ![The finished hull](hull.jpg) + +The output gets `width` and `height` attributes, see [build.md](build.md). + +#### Sizes + +A smaller copy of an image is requested in the file name, by putting a size +between the name and the extension: + + ![The finished hull](hull.800.jpg) + ![The finished hull](hull.half.jpg) + +The size is either a width in pixels or a name from `image_sizes`. The height +follows from the aspect ratio. If `hull.800.jpg` exists as a file, it is +copied as it is, and no copy is generated. + +PNG and JPEG can be scaled, and WebP where Pillow supports it. Other formats, +SVG among them, are only copied. + +#### Layout classes + +An attribute list adds classes, which the stylesheet defines: + + ![The finished hull](hull.half.jpg){: .right } + +Class names are not checked. How an image without a class is shown is up to +the stylesheet. + +#### Captions + +The title of an image becomes its caption when the image is alone in its +paragraph: + + ![The finished hull](hull.800.jpg "The hull before painting") + +The paragraph becomes a `figure` with a `figcaption` below the image. The +title attribute is removed, so the caption does not also appear as a tooltip. +Classes move from the image to the figure, so a floated image takes its +caption along. An image with a title inside running text keeps the title as +a tooltip. + +#### Linking to the original + +A thumbnail linked to the original is the nested Markdown construct: + + [![The finished hull](hull.800.jpg)](hull.jpg) + +The inner reference generates the smaller copy, the outer link copies the +original. An original that is only used for smaller copies is not copied to +the output. + +An attribute list attaches to the thumbnail, and a title makes a caption as +above: + + [![The finished hull](hull.800.jpg "The hull"){: .right }](hull.jpg) + +## Templates + +`tpl/` holds the template set: one or more HTML templates and their assets, +which may be in subdirectories. Everything in `tpl/` except `.html` files is +copied to the build directory, keeping its relative path. + +- `page.html` is the default page template. The `template` header selects + another one. +- `tag.html` renders the tag index pages. + +Error pages, such as a 404 page, are ordinary pages. + +### Markers + +A marker is replaced with a value: + +

{{title}}

+

{{site.site_url}}

+ +A marker is `{{`, a key, optionally a `|` and a filter name, and `}}`, with no +spaces. Anything else is left as it is, including a stray `{{`. There is no +way to escape a well-formed marker. + +Rendered values are not scanned for markers or blocks again. + +A marker for an undefined value renders as an empty string and produces a +warning. A marker with an unknown filter, and a marker for a list value, are +errors. + +### Filters + +Values are HTML-escaped by default. + +- `{{key|htmlencode}}` -- HTML-escaped. This is the default, written out. +- `{{key|literal}}` -- not escaped. Needed for `body` and `footnotes`. +- `{{key|urlencode}}` -- URL-encoded, including `/`. + +### Blocks + +A condition renders its content only when the condition holds: + + {% if subtitle|isnotempty %}

{{subtitle}}

{% endif %} + +Conditions: + +- `isempty` -- the value is undefined, an empty string or an empty list. +- `isnotempty` -- the opposite. + +An unknown condition is an error. A condition on an undefined value does not +produce a warning. + +A loop renders its content once for every item in a list: + + {% loop tags %}
  • {{name}}
  • {% endloop %} + +The list has to be a list of dictionaries. Inside the loop only the keys of +the current item are available; page values such as `relRoot` are not. A loop +over an undefined value renders nothing and produces a warning. A loop over +anything other than a list of dictionaries is an error, and so is a condition +on a loop. + +A block cannot contain another block of its own kind, at any depth: the +inner end tag would close the outer block. A condition inside a loop, or a +loop inside a condition, works. A block tag that is not part of a complete +block is an error. + +### Page values + +- `site.` -- every key of the site configuration. +- Every header of the page, under its own name. Headers the page does not set + are undefined. +- `body` -- the HTML of the body, without the footnotes. Use with `literal`. +- `footnotes` -- the footnotes `div`, or empty. Use with `literal`. A template + without it drops the footnotes. +- `tags` -- the tags of the page, as a list of items with `name` and `url`. + The address is relative to the page. Empty for a page without tags. +- `crossrefUrl` -- the `crossref` header as an address relative to the page, + with `.md` rewritten to `.html`. Empty without the header. +- `relRoot` -- the relative path from the page to the site root, ending in a + slash. `./` at the top level. For links to assets and other pages. +- `absRoot` -- `/`. For error pages, which the server delivers at other + addresses than their own. +- `pageUrl` -- the absolute address of the page. An `index.html` is + addressed by its directory, ending in a slash. +- `metaDescription` -- the `description` header, or `subtitle` without one, + or empty. +- `createdDate`, `updatedDate` -- the dates of `created_at` and `updated_at` + as `dd.mm.yyyy`. Empty without the header. `updatedDate` is also empty when + it is the same date as `createdDate`. +- `ogImage`, `ogImageWidth`, `ogImageHeight`, `ogImageAlt` -- the link + preview image: its absolute address, its size in pixels, and the alt text of + the image it was cut from. Undefined when there is no preview image; the + template then names its own default or none. See [build.md](build.md). + +### Tag index pages + +Tag index pages have no source. They are written to the build root as +`tag_.html`. The name is the tag in lower case, with everything other +than the letters a to z and digits removed: "Model making" becomes +`tag_modelmaking.html`. Tags that differ only in case, spaces or punctuation +share one page. A source with the same name as a tag index page collides +with it. + +Values for `tag.html`: + +- `site.` -- as for pages. +- `tag` -- the tag. Where several spellings share a page, the first one found. +- `relRoot` -- always `./`. `absRoot` -- `/`. +- `pageUrl` -- the absolute address of the tag index page. +- `pages` -- the pages with this tag, newest first by `created_at`, then by + title. Pages without `created_at` come last. Each item has the headers of + its page except `tags`, plus: + - `url` -- the address of the page, relative to the build root. It + replaces a header of the same name. + - `descOrSubtitle` -- the `description` header, or `subtitle` without + one, or empty. + +A header that a page does not set is undefined in its item, and a marker for +it produces a warning. Optional headers belong in a condition. + +### Stylesheets + +Every local image in the output has `width` and `height` attributes. A +stylesheet that limits the width of images has to set `height: auto`. diff -r 000000000000 -r 71dd8d58a8e5 doc/tools.md --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/doc/tools.md Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,146 @@ +# Tools + +All tools work on the site in the current directory. Run them from the site +root, the directory with `config.txt`. Each tool prints its usage with `-h`. + +## make_site.py + +Builds the site. See [build.md](build.md) for what a build does. + + make_site.py [options] [path ...] + + path source files or directories to build. + default: all of src/ + -b, --build-dir DIR + build into DIR instead of build_dir from config.txt + -c, --clean empty the build directory first; implies --tags + -d, --draft also build unpublished pages + -q, --quiet print errors only + -r, --report print the summary + -t, --tags rebuild the tag index pages + -v, --verbose print errors, warnings and notices, and the summary + -h, --help + +`--quiet` and `--verbose` exclude each other. + +A path can be given relative to the current directory or to `src/`, and must +be below `src/`. `--clean` empties the whole build directory, whatever paths +are given. + +To build for publishing: + + make_site.py -c + +During writing, without `-c`, only changed pages are rebuilt. + +Requires Python 3.9 or later with python-markdown and Pillow. + +## make_dist.sh + +Packs the build directory into an archive for one target address. + + make_dist.sh [-m] + + -m, --make run make_site.py -c first + name symbolic name of the target, such as test or prod + url public address of the target + +The archive is written to `dist/` as `--.tar.gz`, +for example `dist/www-test-1.2.tar.gz`, and its path is printed. It holds the +build directory under its own name. The version comes from `get_version.sh +-f`. + +The pages contain absolute addresses built from `site_url`. When `url` is a +different address, the archive gets a copy of the build directory in which +`site_url` is replaced with `url` in every HTML file. The build directory is +not changed. + +## get_version.sh + +Prints the version of the site, from the Mercurial repository it is in. + + get_version.sh [-f] + + -f print a version even if the revision is not tagged or + the working directory has changes + +The version is the latest tag, if the working directory is at the tagged +revision or at the revision that added the tag, and has no changes. +Otherwise it is an error. With `-f` the script warns instead and prints the +latest tag with a timestamp appended, such as `1.2.20260301_1430`. + +## update_index.py + +Rewrites the entry lists of the index pages from the headers of the pages +they list. + + update_index.py [-n] + + -n, --dry-run print the changes as a diff, write nothing + +### Directory index pages + +Every `index.md` below `src/`, except the root one, lists the published pages +in its own directory. An entry is a link to a `.md` file with an optional +date, followed by a definition line with the `subtitle` of the page, or its +`description` if there is no subtitle: + + [First steps](first_steps.md) 01.03.2026 + : Notes from the first week + +The tool replaces the run of entries and keeps all text before and after it. +A link to anything other than a `.md` file, such as `[More](notes/)`, is not +an entry. +The first date in the existing entries decides which header is shown: + +- A full date, `dd.mm.yyyy`, shows `created_at`. +- Anything else shows `timeframe`. + +An index without any dated entry is skipped with a warning, because the tool +cannot tell which header to use. The first entry has to be written by hand. + +Entries are sorted newest first: by `created_at`, or by the start of +`timeframe` (`mm.yyyy` or `yyyy`), then by `updated_at`, then by file +modification time, and then by title. A page without a valid date goes last, +with a warning. + +### Root index page + +`src/index.md` gets one section per item of `index_sections` in +`config.txt`. Each section lists the newest entries of a directory, as many +as `index_recent` says. The links get the directory as a prefix. With + + index_sections: notes:Recent notes, models:Recent models + index_recent: 3 + +the section under the heading "Recent notes" lists the three newest entries +of `src/notes/index.md`. Headings match regardless of case and level. A +section runs from its heading to the next heading. The entries are replaced, +or inserted at the start of the section, and other text such as a "more" link +is kept. + +Without `index_sections` the root index is left alone. + +### Updated date + +A changed index gets today's date as `updated_at`. + +## update_updated.sh + +Sets the `updated_at` header of pages to the date of their last +modification. + + update_updated.sh [-n] [ ...] + + -n, --dry-run report only, change nothing + filespec files and directories to check, directories + recursively. default: src + +For each `.md` file, the tool compares `updated_at` with the date of the +file's modification time and prints each difference. Unless `-n` is given, +it sets `updated_at` to that date, as an ISO date such as `2026-03-01`. The +modification time is kept, so a second run finds nothing to change. + +A value with a time counts as different. A page without `updated_at` gets one +as its last header. A file without a `title` header is skipped with a warning. +Files that are not `.md` are ignored. diff -r 000000000000 -r 71dd8d58a8e5 example/config.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/example/config.txt Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,6 @@ +site_url: https://www.example.org +build_dir: www +image_sizes: half:400, wide:800 +extra_header_keys: +index_sections: notes:Recent notes +index_recent: 5 diff -r 000000000000 -r 71dd8d58a8e5 example/src/about.md --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/example/src/about.md Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,17 @@ +title: About +subtitle: What the example pages show +is_published: 1 + +- [Example site](index.md) is the root index. The section "Recent notes" is + maintained by `update_index.py`, set up by `index_sections` in + `config.txt`. +- [Notes](notes/index.md) is a directory index, also maintained by + `update_index.py`. +- [First steps](notes/first_steps.md) has tags, an image with a caption, a + linked thumbnail, a table and a footnote. Its image is also the link + preview image. +- [The workshop](notes/workshop.md) has a definition list and a + cross-reference. + +The tags link to tag index pages, which the generator writes into the site +root. diff -r 000000000000 -r 71dd8d58a8e5 example/src/index.md --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/example/src/index.md Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,19 @@ +title: Example site +subtitle: A minimal site built with wobbly_ssg +description: A minimal site that shows the source format and a plain + template. +is_published: 1 + +This site shows the source format of wobbly_ssg and a plain template. The +sources are in `src/`, the templates in `tpl/`. See [About](about.md) for +what each page shows. + +## Recent notes + +[First steps](notes/first_steps.md) 01.03.2026 +: Notes from the first week + +[The workshop](notes/workshop.md) 20.02.2026 +: A bench, a lamp and a vice + +[All notes](notes/) diff -r 000000000000 -r 71dd8d58a8e5 example/src/notes/first_steps.md --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/example/src/notes/first_steps.md Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,31 @@ +title: First steps +subtitle: Notes from the first week +description: How the hull of the first model came together. +tags: Notes, Model making +created_at: 2026-03-01 +updated_at: 2026-03-04 +is_published: 1 + +![The hull on the slipway](hull.half.jpg "The hull before painting"){: .right } + +The first model is a harbour tug at 1:50. The hull is built on twelve frames +and planked in lime. + +The hull was planked twice.[^planks] The second layer went on in two +evenings. + +[^planks]: The first planks were too thick to follow the bow. + +## Parts + +| Part | Material | Count | +|--------|----------|------:| +| Frames | Plywood | 12 | +| Planks | Lime | 40 | +| Keel | Beech | 1 | + +## The whole picture + +The image below links to the original. + +[![The hull on the slipway](hull.wide.jpg)](hull.jpg) diff -r 000000000000 -r 71dd8d58a8e5 example/src/notes/hull.jpg Binary file example/src/notes/hull.jpg has changed diff -r 000000000000 -r 71dd8d58a8e5 example/src/notes/index.md --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/example/src/notes/index.md Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,9 @@ +title: Notes +subtitle: All notes, newest first +is_published: 1 + +[First steps](first_steps.md) 01.03.2026 +: Notes from the first week + +[The workshop](workshop.md) 20.02.2026 +: A bench, a lamp and a vice diff -r 000000000000 -r 71dd8d58a8e5 example/src/notes/workshop.md --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/example/src/notes/workshop.md Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,19 @@ +title: The workshop +subtitle: A bench, a lamp and a vice +tags: Notes +created_at: 2026-02-20 +crossref: first_steps.md +is_published: 1 + +The workshop is a corner of the spare room. + +Bench +: A kitchen worktop on two trestles. + +Lamp +: An adjustable desk lamp with a daylight bulb. + +Vice +: A small one, clamped to the bench. + +The first model built here is described in [First steps](first_steps.md). diff -r 000000000000 -r 71dd8d58a8e5 example/static/robots.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/example/static/robots.txt Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,2 @@ +User-agent: * +Disallow: diff -r 000000000000 -r 71dd8d58a8e5 example/tpl/page.html --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/example/tpl/page.html Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,67 @@ + + + + + +{{title}} - Example site +{% if metaDescription|isnotempty %} +{% endif %} + + + +{% if metaDescription|isnotempty %} +{% endif %} +{% if ogImage|isnotempty %} + + + +{% endif %}{% if ogImageAlt|isnotempty %} +{% endif %}{% if ogImage|isempty %} +{% endif %} + + + +
    +

    Example site

    + +
    + +
    +{% if tags|isnotempty %} +
      +{% loop tags %}
    • {{name}}
    • +{% endloop %}
    +{% endif %} +{% if createdDate|isnotempty %} +

    +{% endif %} +

    {{title}}

    +{% if subtitle|isnotempty %} +

    {{subtitle}}

    +{% endif %} +{% if timeframe|isnotempty %} +

    {{timeframe}}

    +{% endif %} + +{{body|literal}} +{% if repository|isnotempty %} + +{% endif %} +{% if crossrefUrl|isnotempty %} + +{% endif %} +{{footnotes|literal}} +{% if updatedDate|isnotempty %} +

    Last updated

    +{% endif %} +
    + + + + + diff -r 000000000000 -r 71dd8d58a8e5 example/tpl/style.css --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/example/tpl/style.css Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,220 @@ +/* browser defaults, adjusted only where prose, tables and images need it. + light and dark schemes come from the browser; all shades are derived from + the text colour. */ + +:root { + color-scheme: light dark; + + --rule: color-mix(in srgb, currentColor 30%, transparent); + --muted: color-mix(in srgb, currentColor 65%, transparent); + --wash: color-mix(in srgb, currentColor 6%, transparent); + --measure: 42em; +} + +body { + max-width: var(--measure); + margin: 0 auto; + padding: 2em 1em 3em; + line-height: 1.5; + /* keep long urls from widening the column */ + overflow-wrap: break-word; +} + +/* masthead ---------------------------------------------------------------- */ + +.site-head { + padding-bottom: 0.6em; + border-bottom: 1px solid var(--rule); +} + +.site-title { + margin: 0; + font-weight: bold; +} + +.site-title a { + color: inherit; + text-decoration: none; +} + +.site-nav { + margin: 0; + padding: 0; + list-style: none; +} + +.site-nav li { + display: inline; +} + +.site-nav li + li::before { + content: " | "; +} + +/* page head --------------------------------------------------------------- */ + +h1 { + line-height: 1.2; + margin: 1.2em 0 0; +} + +.subtitle { + margin: 0.3em 0 0; + font-style: italic; +} + +.timeframe { + margin: 0.3em 0 0; + color: var(--muted); +} + +/* tags and the creation date sit above the title, aligned right */ +.tags, .created { + margin: 1.6em 0 0; + padding: 0; + list-style: none; + font-size: 0.85em; + text-align: right; +} + +.tags + .created, +.tags + h1, +.created + h1 { + margin-top: 0.2em; +} + +.tags li { + display: inline; +} + +.tags li:not(:last-child)::after { + content: ","; +} + +/* repository and crossref links, below the text and any floated image */ +.page-link { + clear: both; +} + +.updated { + clear: both; + margin-top: 2em; + font-size: 0.85em; + text-align: right; + color: var(--muted); +} + +/* body -------------------------------------------------------------------- */ + +dt { font-weight: bold; } +dd { margin-bottom: 0.6em; } + +pre { + overflow-x: auto; + padding: 0.6em 0.8em; + background: var(--wash); +} + +blockquote { + margin-left: 0; + padding-left: 1em; + border-left: 2px solid var(--rule); +} + +/* tables shrink and wrap; the generator emits no wrapper to scroll in */ +table { + width: 100%; + border-collapse: collapse; +} + +th, td { + padding: 0.3em 0.6em 0.3em 0; + text-align: left; + vertical-align: top; + border-bottom: 1px solid var(--rule); +} + +th { border-bottom-width: 2px; } + +/* images ------------------------------------------------------------------ */ + +/* local images have width and height attributes */ +img { + max-width: 100%; + height: auto; +} + +/* floats excluded: this rule would reset their side margins */ +p > img:only-child:not(.left):not(.right) { + display: block; + margin: 1.4em 0; +} + +.right, .left { + max-width: 50%; + margin-bottom: 0.6em; +} + +.right { float: right; margin-left: 1.4em; } +.left { float: left; margin-right: 1.4em; } + +figure { + margin: 0; +} + +figure:not(.left):not(.right) { + margin: 1.4em 0; +} + +figure img { + display: block; +} + +figcaption { + margin-top: 0.4em; + font-size: 0.9em; + color: var(--muted); +} + +/* footnotes --------------------------------------------------------------- */ + +.footnote { + clear: both; + font-size: 0.9em; + color: var(--muted); +} + +.footnote hr { + border: 0; + border-top: 1px solid var(--rule); + margin: 2.5em 0 0.6em; +} + +.footnote-backref { text-decoration: none; } + +/* footer ------------------------------------------------------------------ */ + +.site-foot { + margin-top: 3em; + padding-top: 0.6em; + border-top: 1px solid var(--rule); + clear: both; + font-size: 0.9em; + color: var(--muted); +} + +.site-foot p { + margin: 0; +} + +/* narrow screens ---------------------------------------------------------- */ + +@media (max-width: 30em) { + /* images stop floating and take block spacing */ + .right, .left { + display: block; + float: none; + max-width: 100%; + margin: 1.4em 0; + } +} diff -r 000000000000 -r 71dd8d58a8e5 example/tpl/tag.html --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/example/tpl/tag.html Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,41 @@ + + + + + +{{tag}} - Example site + + + + + + + + + + + + +
    +

    Example site

    + +
    + +
    +

    Pages tagged {{tag}}

    + +
    +{% loop pages %}
    {{title}}
    +{% if descOrSubtitle|isnotempty %}
    {{descOrSubtitle}}
    +{% endif %}{% endloop %}
    +
    + + + + + diff -r 000000000000 -r 71dd8d58a8e5 tools/get_version.sh --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/get_version.sh Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,65 @@ +#!/bin/sh +USAGE="$0 [-f] + +parses tags, status and summary of current repository, prints current version. + +if the current repo revision is the tagging revision, the tag is the version. + +otherwise the script aborts with an error, unless forced with -f flag. in that +case the version is the latest tag with - appended. + +options: + -f force version output even if not on tagged revision or dirty repo + +" + +VERBOSE=1 +FORCE=0 +TIMESTAMP=$(date "+%Y%m%d_%H%M") + +while [ $# != 0 ] +do + case $1 in + -f) + FORCE=1 + ;; + *) + echo "unrecognized option '$1'" + echo "$USAGE" + exit 1 + esac + shift +done + +# parse hg su, hg tags +SUMMARY=$(LC_ALL=C hg su) +PARENT=$(echo "$SUMMARY" | grep "parent:" | cut -b 9- | cut -d : -f 1) +LATESTTAG=$(hg log -r$PARENT -T "{latesttag}") +TAGGEDREV=$(hg tags -T "{rev},{tag}\n"| grep ",$LATESTTAG" | cut -d , -f 1) +TAGGINGREV=$(( $TAGGEDREV + 1 )) +CLEAN=$(echo "$SUMMARY" | grep -c "commit: (clean)") + +VERSION=$LATESTTAG + +if [ "$PARENT" != "$TAGGEDREV" ] && [ "$PARENT" != "$TAGGINGREV" ] ; then + if [ $FORCE = 1 ] ; then + (>&2 echo "warning: not a tagged revision") + VERSION="${LATESTTAG}.${TIMESTAMP}" + else + (>&2 echo "error: not a tagged revision") + exit 1 + fi +fi + +if [ $CLEAN = 0 ] ; then + if [ $FORCE = 1 ] ; then + (>&2 echo "warning: working directory not clean") + VERSION="${LATESTTAG}.${TIMESTAMP}" + else + (>&2 echo "error: working directory not clean") + exit 1 + fi +fi + +echo $VERSION + diff -r 000000000000 -r 71dd8d58a8e5 tools/make_dist.sh --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/make_dist.sh Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,112 @@ +#!/bin/sh + +USAGE="$0 [-m] + +pack the build directory into an archive for the site address and +print the path of the archive. run from the site root. + +the archive is written to dist/ as --.tar.gz. it +holds the build directory under its own name. the version comes from +get_version.sh -f. + +the generated pages contain absolute urls built from site_url in config.txt. +when is a different address, site_url is replaced with in every +html file of a copy of the build directory. the build directory itself is +not changed. + +options: + -m, --make run make_site.py -c first + -h, --help print this help + +positional: + name symbolic name of the target, such as test or prod + url public address of the target, without a trailing slash +" + +MAKE=0 +NAME= +URL= + +while [ "$#" != 0 ] +do + case $1 in + -m|--make) MAKE=1 ;; + -h|--help) echo "$USAGE"; exit 0 ;; + -*) echo "unrecognized option '$1'" >&2; exit 1 ;; + *) + if [ -z "$NAME" ] ; then + NAME="$1" + elif [ -z "$URL" ] ; then + URL="$1" + else + echo "unrecognized argument '$1'" >&2 + exit 1 + fi + ;; + esac + shift +done + +if [ -z "$NAME" ] || [ -z "$URL" ] ; then + echo "missing name or url" >&2 + exit 1 +fi + +if [ ! -f config.txt ] ; then + echo "no config.txt in the current directory" >&2 + exit 1 +fi + +TROOT="$(dirname "$0")" +URL="${URL%/}" + +if [ "$MAKE" = 1 ] ; then + "$TROOT"/make_site.py -c || exit 1 +fi + +# values from config.txt, without surrounding whitespace or trailing slashes +SITE_URL=$(sed -n 's/^site_url:[[:space:]]*//p' config.txt | + sed 's|[/[:space:]]*$||') && +if [ -z "$SITE_URL" ] ; then + echo "no site_url in config.txt" >&2 + exit 1 +fi + +BUILD_DIR=$(sed -n 's/^build_dir:[[:space:]]*//p' config.txt | + sed 's|[/[:space:]]*$||') +: "${BUILD_DIR:=www}" +BUILD_NAME=$(basename "$BUILD_DIR") + +if [ ! -d "$BUILD_DIR" ] ; then + echo "no build directory '$BUILD_DIR', build first or use -m" >&2 + exit 1 +fi + +VERSION=$("$TROOT"/get_version.sh -f) && +ARCHIVE="dist/$BUILD_NAME-$NAME-$VERSION.tar.gz" && +mkdir -p dist && + +STAGE=$(mktemp -d) || exit 1 +trap 'rm -rf "$STAGE"' EXIT + +cp -Rp "$BUILD_DIR" "$STAGE/$BUILD_NAME" && + +if [ "$URL" != "$SITE_URL" ] +then + # dots in the url are literal, not sed wildcards + PATTERN=$(printf '%s' "$SITE_URL" | sed 's/[.]/\\./g') && + find "$STAGE" -type f -name '*.html' | + while IFS= read -r FILE + do + sed "s|$PATTERN|$URL|g" "$FILE" > "$FILE.tmp" && + mv "$FILE.tmp" "$FILE" || + exit 1 + done +fi && + +tar -czf "$ARCHIVE" \ + --no-xattrs --no-mac-metadata \ + --exclude='.DS_Store' \ + -C "$STAGE" "$BUILD_NAME" && + +echo "$ARCHIVE" diff -r 000000000000 -r 71dd8d58a8e5 tools/make_site.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/make_site.py Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,844 @@ +#!/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 = '
    ' + +# 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"

    ((?:]*>)?]*>(?:)?)

    ") + +# 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"]*>", anchor, body) + body = re.sub(r"]*?>", 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"]*>", 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'
    ' if classes else "
    " + return f"{opening}{content}
    {caption}
    " + + +# -- 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) diff -r 000000000000 -r 71dd8d58a8e5 tools/update_index.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/update_index.py Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,342 @@ +#!/usr/bin/env python3 +"""rewrite the entry lists of the index pages in src/ from the headers of the +sources they list. + +an index.md below src/ lists the published sources in its own directory. an +entry is a link line to a .md file, optionally followed by a date, then a +definition line with the subtitle, or the description if there is no +subtitle. the date in the existing entries decides which header is shown: a +full date (dd.mm.yyyy) means created_at, anything else means timeframe. +entries are sorted newest first, by created_at or by the start of the +timeframe, then by updated_at, then by file modification time, and finally by +title. + +the root index.md has one section per entry in the index_sections setting of +config.txt, each listing the newest entries of a directory, as many as +index_recent says. a section runs from its heading to the next heading; text +around the entries, such as a "more" link, is kept. without index_sections the +root index.md is left alone. + +a changed index gets today's date as updated_at.""" + +import argparse +import datetime +import difflib +import re +import sys + +from make_site import (CONFIG, SRC, BuildError, error, parse_header_block, + read_config, warn) + +# an entry starts with a link to a .md file and an optional date beginning +# with a digit. links to anything else, such as a directory, are not entries. +ENTRY = re.compile(r"\[[^\]]*\]\([^)\s]+\.md\)(?:[ \t]+(\d.*?))?[ \t]*$") +DEFINITION = re.compile(r":[ \t]") +CONTINUATION = re.compile(r"[ \t]+\S") +FULL_DATE = re.compile(r"\d{2}\.\d{2}\.\d{4}$") +# the start of a timeframe: mm.yyyy or yyyy +TIMEFRAME_START = re.compile(r"\s*(?:(\d{1,2})\.)?(\d{4})") +HEADING = re.compile(r"#+[ \t]+(.*?)[ \t]*$") + + +def header_end(lines): + """the index of the blank line that ends the header block.""" + for i, line in enumerate(lines): + if not line.strip(): + return i + return len(lines) + + +def find_entries(lines, start, end): + """the run of entries in lines[start:end] as (first line, line after the + last entry, dates of the entries), or None when there is no entry. the + run may contain other lines between entries; they are part of the run.""" + first = None + stop = None + dates = [] + i = start + while i < end: + match = ENTRY.match(lines[i]) + if not match: + i += 1 + continue + if first is None: + first = i + dates.append(match.group(1) or "") + # the definition and its folded lines belong to the entry + i += 1 + if i < end and DEFINITION.match(lines[i]): + i += 1 + while i < end and CONTINUATION.match(lines[i]): + i += 1 + stop = i + if first is None: + return None + return first, stop, dates + + +def sort_key(value, mode): + """a sortable form of a created_at or timeframe value, or None if the + value is empty or not understood.""" + if mode == "created_at": + try: + return datetime.datetime.fromisoformat(value).date() + except ValueError: + return None + match = TIMEFRAME_START.match(value) + if not match: + return None + return int(match.group(2)), int(match.group(1) or 0) + + +def read_entries(directory, mode): + """the published sources in directory except index.md, newest first. + each entry has the file name, title, date as shown and text.""" + entries = [] + for source in sorted(directory.glob("*.md")): + if source.name == "index.md": + continue + where = source.relative_to(SRC).as_posix() + try: + headers, _ = parse_header_block( + source.read_text(encoding="utf-8"), where) + except BuildError as failure: + warn(f"{failure}, not listed") + continue + if headers.get("is_published", "").strip() != "1": + continue + if not headers.get("title"): + warn(f"{where}: missing title, not listed") + continue + + value = headers.get(mode, "") + key = sort_key(value, mode) + if key is None: + warn(f"{where}: no valid {mode}, listed last") + shown = value + if mode == "created_at" and key is not None: + shown = key.strftime("%d.%m.%Y") + + text = headers.get("subtitle") or headers.get("description") or "" + if not text: + warn(f"{where}: no subtitle or description") + + entries.append({ + "file": source.name, + "title": headers["title"], + "date": shown, + "text": text, + "key": key, + "updated": sort_key(headers.get("updated_at", ""), "created_at"), + "mtime": source.stat().st_mtime, + }) + + # by title, then newest first by date, updated_at and modification time; + # entries without a date or updated_at go last among their equals + entries.sort(key=lambda e: e["title"]) + entries.sort(key=lambda e: (e["key"] is not None, e["key"] or 0, + e["updated"] is not None, e["updated"] or 0, + e["mtime"]), + reverse=True) + return entries + + +def render(entries, prefix=""): + """entries as definition list lines, separated by blank lines. prefix is + put before each link target.""" + lines = [] + for entry in entries: + if lines: + lines.append("") + link = f"[{entry['title']}]({prefix}{entry['file']})" + lines.append(f"{link} {entry['date']}" if entry["date"] else link) + if entry["text"]: + lines.append(": " + entry["text"]) + return lines + + +def set_updated(lines, stamp): + """set the updated_at header to stamp, dropping folded continuations of + the old value. without updated_at, add it as the last header.""" + end = header_end(lines) + for i in range(end): + if re.match(r"updated_at[ \t]*:", lines[i]): + j = i + 1 + while j < end and lines[j][:1] in (" ", "\t"): + j += 1 + lines[i:j] = ["updated_at: " + stamp] + return + lines.insert(end, "updated_at: " + stamp) + + +def save(path, old, new, dry_run): + """write new lines to path if they differ from old, with updated_at set + to today. a dry run prints the difference instead. returns whether the + file differs.""" + if new == old: + return False + set_updated(new, datetime.date.today().isoformat()) + where = path.relative_to(SRC.parent).as_posix() + if dry_run: + for line in difflib.unified_diff(old, new, where, where, lineterm=""): + print(line) + else: + path.write_text("\n".join(new), encoding="utf-8") + print(f"{where}: updated") + return True + + +def read_index(path): + """the lines of an index and the index of its first body line, or None + if it has no valid header block with a title.""" + where = path.relative_to(SRC).as_posix() + text = path.read_text(encoding="utf-8") + try: + headers, _ = parse_header_block(text, where) + except BuildError as failure: + warn(f"{failure}, skipped") + return None + if not headers.get("title"): + warn(f"{where}: missing title, skipped") + return None + lines = text.split("\n") + return lines, header_end(lines) + 1 + + +def update_directory(index, dry_run): + """rewrite the entry list of a directory index. returns (changed, sorted + entries), or None if the index is skipped.""" + where = index.relative_to(SRC).as_posix() + read = read_index(index) + if read is None: + return None + old, body = read + + run = find_entries(old, body, len(old)) + if run is None: + warn(f"{where}: no entry list, skipped") + return None + first, stop, dates = run + + dates = [date for date in dates if date] + if not dates: + warn(f"{where}: no dates in the entry list, cannot tell created_at " + "from timeframe, skipped") + return None + mode = "created_at" if FULL_DATE.match(dates[0]) else "timeframe" + + entries = read_entries(index.parent, mode) + if not entries: + warn(f"{where}: no published sources, list left alone") + return None + + new = old[:first] + render(entries) + old[stop:] + return save(index, old, new, dry_run), entries + + +def parse_sections(spec): + """the index_sections setting as a list of (heading, directory) pairs. the + setting is a comma-separated list of : items.""" + sections = [] + for item in spec.split(","): + item = item.strip() + if not item: + continue + directory, _, heading = item.partition(":") + if not directory.strip() or not heading.strip(): + error(f"{CONFIG.name}: bad index section {item!r}") + sections.append((heading.strip(), directory.strip().strip("/"))) + return sections + + +def update_root(index, lists, sections, recent, dry_run): + """rewrite the sections of the root index from the sorted entries of the + directory indexes. sections is a list of (heading, directory) pairs, recent + the number of entries per section. returns whether the file changed, or + None if it is skipped.""" + read = read_index(index) + if read is None: + return None + old, body = read + new = list(old) + + for heading, directory in sections: + if directory not in lists: + warn(f"index.md: no entries for {directory}/, section " + f"{heading!r} left alone") + continue + + start = None + for i in range(body, len(new)): + match = HEADING.match(new[i]) + if match and match.group(1).lower() == heading.lower(): + start = i + 1 + break + if start is None: + warn(f"index.md: no section {heading!r}") + continue + end = start + while end < len(new) and not HEADING.match(new[end]): + end += 1 + + lines = render(lists[directory][:recent], directory + "/") + run = find_entries(new, start, end) + if run is None: + new[start:start] = [""] + lines + else: + first, stop, _ = run + new[first:stop] = lines + + return save(index, old, new, dry_run) + + +def main(argv): + parser = argparse.ArgumentParser( + description="rewrite the entry lists of the index pages in src/ from " + "the headers of the sources they list. a changed index " + "gets today's date as updated_at.") + parser.add_argument("-n", "--dry-run", action="store_true", + help="print the changes, write nothing") + args = parser.parse_args(argv) + + config = read_config() + sections = parse_sections(config["index_sections"]) + if not config["index_recent"].strip().isdigit(): + error(f"{CONFIG.name}: index_recent is not a number") + recent = int(config["index_recent"]) + + checked = 0 + changed = 0 + lists = {} + for index in sorted(SRC.rglob("index.md")): + if index.parent == SRC: + continue + checked += 1 + result = update_directory(index, args.dry_run) + if result is None: + continue + differs, entries = result + changed += differs + lists[index.parent.relative_to(SRC).as_posix()] = entries + + root = SRC / "index.md" + if sections and root.exists(): + checked += 1 + changed += bool(update_root(root, lists, sections, recent, + args.dry_run)) + elif sections: + warn("index.md: not found") + + if args.dry_run: + print(f"checked {checked} index files, {changed} would be modified") + else: + print(f"checked {checked} index files, modified {changed}") + 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) diff -r 000000000000 -r 71dd8d58a8e5 tools/update_updated.sh --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/update_updated.sh Thu Oct 22 14:59:43 2026 +0200 @@ -0,0 +1,156 @@ +#!/bin/sh + +USAGE="$0 [-n] [ ...] + +compare the updated_at header of markdown sources with the file modification +time. print each difference and, unless -n is given, set updated_at to the +date of the modification time as an ISO date, for example 2026-10-22. the +modification time itself is kept, so a second run finds nothing to change. + +a value with a time counts as different. a source without updated_at gets +one as the last header. a markdown file without a title header warns and is +left alone. files that are not .md are ignored. + +options: + -n, --dry-run report only, change nothing + -h, --help print this help + +positional: + filespec files and directories to check, directories recursively. + default: src +" + +DRY_RUN=0 +SPECS= +NL=' +' + +while [ "$#" != 0 ] +do + case $1 in + -n|--dry-run) DRY_RUN=1 ;; + -h|--help) echo "$USAGE"; exit 0 ;; + -*) echo "unrecognized option '$1'" >&2; exit 1 ;; + *) SPECS="$SPECS$NL$1" ;; + esac + shift +done + +if [ -z "$SPECS" ] ; then + SPECS=src +fi + +# print 1 or 0 for a title header, the line number of the last updated_at +# header or 0 if there is none, and its value. the first blank line ends the +# header block; folded continuation lines are skipped. +READ_AWK=' + /^[ \t]*$/ { exit } + /^[ \t]/ { next } + /^title[ \t]*:/ { has_title = 1 } + /^updated_at[ \t]*:/ { + line = NR + value = $0 + sub(/^[^:]*:[ \t]*/, "", value) + sub(/[ \t]+$/, "", value) + } + END { printf "%d %d %s\n", has_title, line, value } +' + +# replace the updated_at header on the given line with the stamp, dropping +# folded continuations of the old value. with line 0, add updated_at as the +# last header instead. +WRITE_AWK=' + BEGIN { in_header = 1 } + in_header && /^[ \t]*$/ { + if (line == 0) print "updated_at: " stamp + in_header = 0 + } + in_header && dropping && /^[ \t]/ { next } + { dropping = 0 } + NR == line { + print "updated_at: " stamp + dropping = 1 + next + } + { print } + END { if (in_header && line == 0) print "updated_at: " stamp } +' + +# expand directories to the markdown files below them, drop other files +FILES=$( + while IFS= read -r SPEC + do + if [ -z "$SPEC" ] ; then + continue + elif [ -d "$SPEC" ] ; then + find "$SPEC" -type f -name '*.md' + elif [ -f "$SPEC" ] ; then + # the opening parenthesis keeps the pattern from closing $( ) + # in older shells + case $SPEC in (*.md) echo "$SPEC" ;; esac + else + echo "warning: $SPEC: not found" >&2 + fi + done <&2 + continue + fi + + MTIME=$(date -r "$FILE" "+%Y-%m-%d") + + if [ "$LINE" != 0 ] && [ "$VALUE" = "$MTIME" ] ; then + continue + fi + + if [ "$LINE" = 0 ] ; then + echo "$FILE: updated_at missing -> $MTIME" + else + echo "$FILE: updated_at '$VALUE' -> $MTIME" + fi + CHANGED=$((CHANGED + 1)) + + if [ "$DRY_RUN" = 1 ] ; then + continue + fi + + # rewrite in place, so the file keeps its permissions, then put back the + # modification time the stamp was taken from + awk -v line="$LINE" -v stamp="$MTIME" "$WRITE_AWK" "$FILE" > "$TMP" && + touch -r "$FILE" "$TMP" && + cat "$TMP" > "$FILE" && + touch -r "$TMP" "$FILE" || + { + echo "error: $FILE: update failed" >&2 + exit 1 + } +done <