diff --git a/README.md b/README.md
index 06b5921..d0cbb14 100644
--- a/README.md
+++ b/README.md
@@ -8,11 +8,16 @@ Licence: GPL-3.0-or-later, see `LICENSE`.
```
motorino build -site DIR -out DIR build the site in DIR into the output folder (defaults: . and public)
+motorino build -drafts ... the same, with the drafts and the posts dated in the future, for a preview
+motorino build -clean ... empty the output folder first, if it is new, empty or holds .motorino-out
+motorino new -site DIR "A title" write news/a-title.md, a draft with the header ready, and print its path
motorino version print the version
```
The binary is a single static Go program. The version comes from semantic-release.
+A build writes the files it makes and leaves the others in the output folder, so the pages of a list that got shorter (`news/page/3/`) stay behind. When that happens the command prints a warning that names the old files. The deploy never has them: it builds into a new folder and publishes it with `rsync --delete`. For a folder you reuse, `-clean` empties it first. It does that only for a folder that is new, empty or holds the `.motorino-out` file that an earlier `-clean` left, never for any other folder with files in it and never for the folder of the site or one that holds it. A build without `-clean` writes no extra file.
+
## What a site looks like
```
@@ -38,11 +43,36 @@ Author: Matteo Bini
Date: 2026-09-18T17:00:45+0200
Categories: Linux Day, FLUG
Description: An optional one-line summary.
+Mastodon: https://social.kmalloc.org/@squid/115000000000000000
+Language: it
+Draft: true
-
The text of the news.
```
-A news file `news/name.md` is published as `/news/YYYY/MM/name.html`, with the year and the month of `Date` as written. Every category gets a page, `/news/category/.html`.
+A news file `news/name.md` is published as `/news/YYYY/MM/name.html`, with the year and the month of `Date` as written. Every category gets a page, `/news/category/.html`. The optional keys:
+
+- `Description`: the summary of the post. When it is written the post page shows it under the title; when it is not, the first sentence of the text is used for the meta description and the lists, and the page does not repeat it.
+- `Mastodon`: an `https` address, the post on Mastodon. The post page then has a link to reply there (the language needs `reply_mastodon`).
+- `Language`: the language the post is written in; the default is the language of the news (below).
+- `Draft`: `true` or `yes` keeps the post out of the site. So does a `Date` in the future, until that moment. `motorino build -drafts` publishes both, for a preview.
+
+#### The news and their language
+
+The news exist once, not once per language. Their language is `news_language` in `site.json`, else `en` when the site has it, else the default language. The news index page (`content//news/index.md`, ID `news`) must be in that language; the posts, the lists, the archive, the categories and the feed are all in it, with the interface strings of its language file. A post can say another language with `Language`; its page then uses that language file. The other languages of the site link to the news from their home.
+
+#### The blog
+
+Everything below is opt in, so a site that does not use it builds as it did.
+
+- **The post page** (`templates/post.html`) has, besides `post_title`, `date`, `post_body` and `post_byline`: `date_long` (such as "14 November 2026"), `post_summary` (the written description as a lead paragraph), `post_meta` (a line with the date, the author, the category links and the reading time), `post_reading`, `post_mastodon` (the reply link) and `post_nav` (the newer post, the older post and all the news). `og_type` is `article` there and `website` on every other page, and `article_meta` holds the published time and a tag for each category, for the head of `base.html`.
+- **The blog list**: a paragraph with only `{{news_blog}}` on the news index lists the posts as note panels (`
`: a small line with the long date and the categories, the title in bold with a full stop unless it ends with `.`, `?` or `!`, the description, and a read more link named after the post), 10 to a page. The other pages are written under the index, at `page/2/`, `page/3/`, with a pager. The block needs an index page.
+- **The archive**: when `templates/archive.html` exists, every year and month with posts gets a page, `/news/2026/` and `/news/2026/11/`, with `archive_name`, `archive_nav` and `archive_posts`. The posts of an archive page, of a category page and of the blog list are the same panels; where the language has no `read_more` the title is the link instead, except on the blog list, where it is an error. `{{news_list}}` and the latest news of the home page stay plain lists. `{{news_archive}}` lists the years and the months with their counts, and needs the template.
+- **The feed** (`/news/feed.xml`) has the summary in `description` and the full text, with absolute links, in `content:encoded`, plus the categories and the author.
+
+The strings come from the language files. These are required when the feature is used: `read_more`, `pager_label`, `pager_newer`, `pager_older` and `pager_page` (`Page {n} of {total}`) for the blog list, and `reply_mastodon` for a post with a Mastodon address. These are optional, and without them the feature is left out: `date_long` (`{d} {month} {y}`) and `month_01` to `month_12` (without them the date is `2026-11-14`), `date_month_year` (`{month} {y}`), `reading_time` (`{n} min read`), and `post_older`, `post_newer` and `post_nav` for the links between posts. The archive uses `archive_h` in its template and, optionally, `archive_up`.
+
+A new post is a draft: `motorino new "A title"` writes `news/a-title.md` with the date of now and `Draft: true`, and the author from the `author` key of `site.json` when there is one.
Pages: `Title`, `ID` (the same in every language, it links the translations), `Description`, and optionally `Layout` (`page`, `bare` or `manifesto`), `Note`, `Switch` (`lang=/path, lang=/path`, overrides the language links) and `ManifestoVersion` and `ManifestoDate` (a translation of an older manifesto says which version it translates).
diff --git a/cmd/motorino/main.go b/cmd/motorino/main.go
index a1997f1..7443176 100644
--- a/cmd/motorino/main.go
+++ b/cmd/motorino/main.go
@@ -5,7 +5,8 @@
//
// Usage:
//
-// motorino build [-site DIR] [-out DIR]
+// motorino build [-site DIR] [-out DIR] [-drafts] [-clean]
+// motorino new [-site DIR] "title"
// motorino version
package main
@@ -16,13 +17,16 @@ import (
"io"
"os"
"strings"
+ "time"
"git.kmalloc.org/squid/motorino/internal/build"
+ "git.kmalloc.org/squid/motorino/internal/content"
+ "git.kmalloc.org/squid/motorino/internal/site"
"git.kmalloc.org/squid/motorino/internal/version"
)
// usage is the text printed for a missing or unknown command.
-const usage = "usage: motorino build [-site DIR] [-out DIR] | motorino version"
+const usage = "usage: motorino build [-site DIR] [-out DIR] [-drafts] [-clean] | motorino new [-site DIR] \"title\" | motorino version"
// main runs the command line and exits with its status code.
func main() {
@@ -42,6 +46,8 @@ func run(args []string, stdout, stderr io.Writer) int {
return 0
case "build":
return runBuild(args[1:], stdout, stderr)
+ case "new":
+ return runNew(args[1:], stdout, stderr)
default:
fmt.Fprintf(stderr, "motorino: unknown command %q\n%s\n", args[0], usage)
return 2
@@ -54,6 +60,8 @@ func runBuild(args []string, stdout, stderr io.Writer) int {
flags.SetOutput(stderr)
site := flags.String("site", ".", "the folder of the site")
out := flags.String("out", "public", "the folder the HTML is written to")
+ drafts := flags.Bool("drafts", false, "publish the drafts and the posts dated in the future, for a preview")
+ clean := flags.Bool("clean", false, "empty the output folder first, if it is new, empty or was emptied this way before")
if err := flags.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
return 0
@@ -64,11 +72,54 @@ func runBuild(args []string, stdout, stderr io.Writer) int {
fmt.Fprintf(stderr, "motorino: unexpected arguments: %s\n%s\n", strings.Join(flags.Args(), " "), usage)
return 2
}
- result, err := build.Build(build.Options{SiteDir: *site, OutDir: *out, Version: version.String()})
+ result, err := build.Build(build.Options{SiteDir: *site, OutDir: *out, Version: version.String(), Drafts: *drafts, Clean: *clean})
if err != nil {
fmt.Fprintf(stderr, "motorino: %v\n", err)
return 1
}
fmt.Fprintf(stdout, "built %d pages into %s\n", result.Pages, *out)
+ warnStale(stderr, *out, result.Stale)
+ return 0
+}
+
+// warnStale tells the files of the output folder that the build did not write,
+// which stay there unless -clean is used.
+func warnStale(stderr io.Writer, out string, stale []string) {
+ if len(stale) == 0 {
+ return
+ }
+ noun := "files"
+ if len(stale) == 1 {
+ noun = "file"
+ }
+ fmt.Fprintf(stderr, "motorino: warning: %d %s in %s were not written by this build, such as %s; build into a new folder or use -clean\n", len(stale), noun, out, stale[0])
+}
+
+// runNew parses the flags of the new command and writes the file of a new post.
+// The author is the author key of site.json, when it has one.
+func runNew(args []string, stdout, stderr io.Writer) int {
+ flags := flag.NewFlagSet("new", flag.ContinueOnError)
+ flags.SetOutput(stderr)
+ dir := flags.String("site", ".", "the folder of the site")
+ if err := flags.Parse(args); err != nil {
+ if errors.Is(err, flag.ErrHelp) {
+ return 0
+ }
+ return 2
+ }
+ if flags.NArg() != 1 {
+ fmt.Fprintf(stderr, "motorino: new takes one title\n%s\n", usage)
+ return 2
+ }
+ author := ""
+ if cfg, _, err := site.Load(*dir); err == nil {
+ author = cfg.Strings["author"]
+ }
+ rel, err := content.NewPost(*dir, flags.Arg(0), author, time.Now())
+ if err != nil {
+ fmt.Fprintf(stderr, "motorino: %v\n", err)
+ return 1
+ }
+ fmt.Fprintln(stdout, rel)
return 0
}
diff --git a/cmd/motorino/main_test.go b/cmd/motorino/main_test.go
index cd8f08a..6ecd765 100644
--- a/cmd/motorino/main_test.go
+++ b/cmd/motorino/main_test.go
@@ -122,3 +122,122 @@ func TestRunBuildBadFlag(t *testing.T) {
t.Errorf("run(build -nope) = %d, want 2", code)
}
}
+
+// TestRunNewCreatesADraft checks the new command: it prints the file, writes a draft and
+// takes the author from site.json.
+func TestRunNewCreatesADraft(t *testing.T) {
+ dir := miniSite(t)
+ site := filepath.Join(dir, "site.json")
+ if err := os.WriteFile(site, []byte(`{"base_url": "https://x.org", "languages": ["en"], "mastodon_url": "m", "motorino_url": "u", "author": "squid"}`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ var out, errOut bytes.Buffer
+ if code := run([]string{"new", "-site", dir, "My first post"}, &out, &errOut); code != 0 {
+ t.Fatalf("run(new) = %d, stderr %q", code, errOut.String())
+ }
+ if got := strings.TrimSpace(out.String()); got != "news/my-first-post.md" {
+ t.Errorf("stdout = %q, want news/my-first-post.md", got)
+ }
+ data, err := os.ReadFile(filepath.Join(dir, "news", "my-first-post.md"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{"Title: My first post\n", "Author: squid\n", "Draft: true\n"} {
+ if !strings.Contains(string(data), want) {
+ t.Errorf("the file does not contain %q\n%s", want, data)
+ }
+ }
+ if code := run([]string{"new", "-site", dir, "My first post"}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), "already exists") {
+ t.Errorf("the same title again: code %d, stderr %q, want 1 and an error", code, errOut.String())
+ }
+}
+
+// TestRunNewNeedsATitle checks the usage mistakes of the new command.
+func TestRunNewNeedsATitle(t *testing.T) {
+ for _, args := range [][]string{{"new"}, {"new", "-site", t.TempDir()}, {"new", "one", "two"}} {
+ var out, errOut bytes.Buffer
+ if code := run(args, &out, &errOut); code != 2 || !strings.Contains(errOut.String(), "usage") {
+ t.Errorf("run(%v) = %d, stderr %q, want 2 and the usage", args, code, errOut.String())
+ }
+ }
+}
+
+// TestRunBuildDraftsFlag checks that a draft is only published with -drafts.
+func TestRunBuildDraftsFlag(t *testing.T) {
+ dir := miniSite(t)
+ if err := os.MkdirAll(filepath.Join(dir, "news"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "news", "wip.md"), []byte("Title: Work in progress\nDate: 2026-01-01T12:00:00+0100\nDraft: true\n-\nSoon.\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ var out, errOut bytes.Buffer
+ plain := filepath.Join(t.TempDir(), "plain")
+ if code := run([]string{"build", "-site", dir, "-out", plain}, &out, &errOut); code != 0 {
+ t.Fatalf("build = %d, stderr %q", code, errOut.String())
+ }
+ if _, err := os.Stat(filepath.Join(plain, "news", "2026", "01", "wip.html")); err == nil {
+ t.Error("a draft is published without -drafts")
+ }
+ preview := filepath.Join(t.TempDir(), "preview")
+ if code := run([]string{"build", "-drafts", "-site", dir, "-out", preview}, &out, &errOut); code != 0 {
+ t.Fatalf("build -drafts = %d, stderr %q", code, errOut.String())
+ }
+ if _, err := os.Stat(filepath.Join(preview, "news", "2026", "01", "wip.html")); err != nil {
+ t.Errorf("a draft is missing from the build with -drafts: %v", err)
+ }
+}
+
+// TestRunBuildWarnsAboutOldFiles checks that old files in the output folder are named in a warning and left alone.
+func TestRunBuildWarnsAboutOldFiles(t *testing.T) {
+ site := miniSite(t)
+ outDir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(outDir, "old.html"), []byte("old"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ var out, errOut bytes.Buffer
+ if code := run([]string{"build", "-site", site, "-out", outDir}, &out, &errOut); code != 0 {
+ t.Fatalf("run(build) = %d, stderr %q", code, errOut.String())
+ }
+ for _, want := range []string{"warning", "1 file", "old.html", "-clean"} {
+ if !strings.Contains(errOut.String(), want) {
+ t.Errorf("stderr %q does not contain %q", errOut.String(), want)
+ }
+ }
+ if _, err := os.Stat(filepath.Join(outDir, "old.html")); err != nil {
+ t.Error("a build without -clean removed the old file")
+ }
+ errOut.Reset()
+ if code := run([]string{"build", "-site", site, "-out", filepath.Join(t.TempDir(), "new")}, &out, &errOut); code != 0 || errOut.Len() != 0 {
+ t.Errorf("a build into a new folder: code %d, stderr %q, want 0 and nothing", code, errOut.String())
+ }
+}
+
+// TestRunBuildClean checks -clean on a folder that is marked and on one that is not.
+func TestRunBuildClean(t *testing.T) {
+ site := miniSite(t)
+ var out, errOut bytes.Buffer
+ outDir := filepath.Join(t.TempDir(), "public")
+ if code := run([]string{"build", "-clean", "-site", site, "-out", outDir}, &out, &errOut); code != 0 {
+ t.Fatalf("run(build -clean) into a new folder = %d, stderr %q", code, errOut.String())
+ }
+ if err := os.WriteFile(filepath.Join(outDir, "old.html"), []byte("old"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if code := run([]string{"build", "-clean", "-site", site, "-out", outDir}, &out, &errOut); code != 0 || errOut.Len() != 0 {
+ t.Fatalf("run(build -clean) again = %d, stderr %q", code, errOut.String())
+ }
+ if _, err := os.Stat(filepath.Join(outDir, "old.html")); err == nil {
+ t.Error("-clean left the old file")
+ }
+ other := t.TempDir()
+ if err := os.WriteFile(filepath.Join(other, "mine.txt"), []byte("mine"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if code := run([]string{"build", "-clean", "-site", site, "-out", other}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), ".motorino-out") {
+ t.Errorf("run(build -clean) into a folder that is not motorino's = %d, stderr %q, want 1 and the marker named", code, errOut.String())
+ }
+ if _, err := os.Stat(filepath.Join(other, "mine.txt")); err != nil {
+ t.Error("-clean removed a file of a folder that is not motorino's")
+ }
+}
diff --git a/internal/build/blog.go b/internal/build/blog.go
new file mode 100644
index 0000000..0a8a7a5
--- /dev/null
+++ b/internal/build/blog.go
@@ -0,0 +1,239 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package build
+
+import (
+ "fmt"
+ "sort"
+ "strconv"
+ "strings"
+
+ "git.kmalloc.org/squid/motorino/internal/content"
+ "git.kmalloc.org/squid/motorino/internal/render"
+)
+
+// newsPerPage is how many posts one page of the blog list has.
+const newsPerPage = 10
+
+// pageCount returns how many pages n posts make: at least one.
+func pageCount(n int) int {
+ if n <= newsPerPage {
+ return 1
+ }
+ return (n + newsPerPage - 1) / newsPerPage
+}
+
+// pagePath returns the address of page n of an index: the index itself for the
+// first page, then base + "page/2/", "page/3/" and so on. base ends with "/".
+func pagePath(base string, n int) string {
+ if n <= 1 {
+ return base
+ }
+ return base + "page/" + strconv.Itoa(n) + "/"
+}
+
+// pageLabel is "Page 2 of 3" in the language lang, from the string pager_page.
+func (b *builder) pageLabel(lang string, n, total int) (string, error) {
+ text := b.langs[lang].Strings["pager_page"]
+ if text == "" {
+ return "", fmt.Errorf("lang/%s.json: the language has no pager_page string, which the pages of the blog list need", lang)
+ }
+ return strings.NewReplacer("{n}", strconv.Itoa(n), "{total}", strconv.Itoa(total)).Replace(text), nil
+}
+
+// newsBlog returns the page n of the blog list of the language lang, with the
+// pager when the list has more than one page. A site without posts gets the
+// news_empty text.
+func (b *builder) newsBlog(lang string, n int, ctx map[string]string) (string, error) {
+ if len(b.posts) == 0 {
+ return "
\n" + ctx["news_empty"] + "\n
", nil
+ }
+ total := pageCount(len(b.posts))
+ if n < 1 || n > total {
+ n = 1
+ }
+ end := n * newsPerPage
+ if end > len(b.posts) {
+ end = len(b.posts)
+ }
+ entries := make([]string, 0, newsPerPage)
+ for _, p := range b.posts[(n-1)*newsPerPage : end] {
+ entry, err := b.newsPanel(p, lang, true)
+ if err != nil {
+ return "", err
+ }
+ entries = append(entries, entry)
+ }
+ html := strings.Join(entries, "\n")
+ if total == 1 {
+ return html, nil
+ }
+ pager, err := b.pager(lang, n, total)
+ if err != nil {
+ return "", err
+ }
+ return html + "\n" + pager, nil
+}
+
+// pager returns the navigation between the pages of the blog list.
+func (b *builder) pager(lang string, n, total int) (string, error) {
+ l := b.langs[lang]
+ label, newer, older := l.Strings["pager_label"], l.Strings["pager_newer"], l.Strings["pager_older"]
+ if label == "" || newer == "" || older == "" {
+ return "", fmt.Errorf("lang/%s.json: the language lacks pager_label, pager_newer or pager_older, which the pages of the blog list need", lang)
+ }
+ page, err := b.pageLabel(lang, n, total)
+ if err != nil {
+ return "", err
+ }
+ var parts []string
+ if n > 1 {
+ parts = append(parts, fmt.Sprintf(`%s`, pagePath(b.newsPath, n-1), render.Escape(newer)))
+ }
+ parts = append(parts, render.Escape(page))
+ if n < total {
+ parts = append(parts, fmt.Sprintf(`%s`, pagePath(b.newsPath, n+1), render.Escape(older)))
+ }
+ return fmt.Sprintf("", render.EscapeAttr(label), strings.Join(parts, "\n·\n")), nil
+}
+
+// archiveMonth is the posts of one month; archiveYear the posts of one year.
+type (
+ archiveMonth struct {
+ year, month int
+ posts []content.Post
+ }
+ archiveYear struct {
+ year int
+ posts []content.Post
+ months []archiveMonth
+ }
+)
+
+// groupArchive groups posts by year and by month, as written in their dates.
+// The years and the months are newest first, and the posts of a group keep the
+// order they were given. A post is put in its group by its own year and month,
+// not by the group before it: two posts near midnight at the end of a month,
+// written with different offsets, can be in the order of their instants and in
+// the opposite order of their months.
+func groupArchive(posts []content.Post) []archiveYear {
+ type key struct{ year, month int }
+ years := map[int]*archiveYear{}
+ months := map[key]*archiveMonth{}
+ for _, p := range posts {
+ y, m := p.Date.Year(), int(p.Date.Month())
+ year := years[y]
+ if year == nil {
+ year = &archiveYear{year: y}
+ years[y] = year
+ }
+ year.posts = append(year.posts, p)
+ month := months[key{y, m}]
+ if month == nil {
+ month = &archiveMonth{year: y, month: m}
+ months[key{y, m}] = month
+ }
+ month.posts = append(month.posts, p)
+ }
+ var out []archiveYear
+ for _, year := range years {
+ for k, month := range months {
+ if k.year == year.year {
+ year.months = append(year.months, *month)
+ }
+ }
+ sort.Slice(year.months, func(i, j int) bool { return year.months[i].month > year.months[j].month })
+ out = append(out, *year)
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].year > out[j].year })
+ return out
+}
+
+// yearPath and monthPath are the addresses of an archive year and month.
+func (b *builder) yearPath(year int) string { return fmt.Sprintf("%s%04d/", b.newsPath, year) }
+func (b *builder) monthPath(year, month int) string {
+ return fmt.Sprintf("%s%04d/%02d/", b.newsPath, year, month)
+}
+
+// hasArchive reports whether the site has the template of an archive page.
+func (b *builder) hasArchive() bool {
+ _, ok := b.templates["archive"]
+ return ok
+}
+
+// monthList returns the list of the months of a year, each with its posts.
+func (b *builder) monthList(y archiveYear, lang string) string {
+ items := make([]string, len(y.months))
+ for i, m := range y.months {
+ items[i] = fmt.Sprintf(`
"
+}
+
+// newsArchive returns the nested list of the years and the months that have
+// posts, or nothing when there are none: the blog list says there is no news. It
+// needs the archive pages.
+func (b *builder) newsArchive(lang string, ctx map[string]string) (string, error) {
+ if _, err := b.template("archive"); err != nil {
+ return "", fmt.Errorf("the {{news_archive}} block needs the archive pages: %w", err)
+ }
+ years := groupArchive(b.posts)
+ if len(years) == 0 {
+ return "", nil
+ }
+ items := make([]string, len(years))
+ for i, y := range years {
+ items[i] = fmt.Sprintf("
", b.yearPath(y.year), render.Escape(text), year)
+ }
+ for _, m := range y.months {
+ name := monthYear(m.year, m.month, l)
+ if err := page(b.monthPath(m.year, m.month), name, up, m.posts, "the archive of "+name); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
diff --git a/internal/build/blog_test.go b/internal/build/blog_test.go
new file mode 100644
index 0000000..fe21863
--- /dev/null
+++ b/internal/build/blog_test.go
@@ -0,0 +1,706 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package build
+
+import (
+ "encoding/xml"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// fixedNow is the moment the blog tests build at, so that drafts and future
+// dates do not depend on the clock.
+var fixedNow = time.Date(2026, 11, 15, 12, 0, 0, 0, time.FixedZone("CET", 3600))
+
+// withFiles returns the base site with files added or replaced; an empty value removes the file.
+func withFiles(extra map[string]string) map[string]string {
+ files := baseFiles()
+ for name, content := range extra {
+ if content == "" {
+ delete(files, name)
+ continue
+ }
+ files[name] = content
+ }
+ return files
+}
+
+// buildWith builds the site made of files with the options changed by tune.
+func buildWith(t *testing.T, files map[string]string, tune func(*Options)) (string, error) {
+ t.Helper()
+ out := filepath.Join(t.TempDir(), "public")
+ opts := Options{SiteDir: writeFiles(t, files), OutDir: out, Version: "1.2.3", Now: fixedNow}
+ if tune != nil {
+ tune(&opts)
+ }
+ _, err := Build(opts)
+ return out, err
+}
+
+// exists reports whether the output has the file rel.
+func exists(t *testing.T, out, rel string) bool {
+ t.Helper()
+ _, err := readOutMaybe(out, rel)
+ return err == nil
+}
+
+// postNews returns the news files used by the draft and future tests.
+func postNews() map[string]string {
+ return map[string]string{
+ "news/a-draft.md": "Title: A draft\nDate: 2026-11-10T12:00:00+0100\nCategories: Secret\nDraft: true\n-\nNot yet.\n",
+ "news/in-future.md": "Title: In the future\nDate: 2026-12-24T12:00:00+0100\nCategories: Later\n-\nSoon.\n",
+ }
+}
+
+// TestDraftsAndFutureStayHidden checks that a draft and a post dated in the
+// future are not published anywhere, and that no category exists only for them.
+func TestDraftsAndFutureStayHidden(t *testing.T) {
+ out, err := buildWith(t, withFiles(postNews()), nil)
+ if err != nil {
+ t.Fatalf("Build() error = %v", err)
+ }
+ for _, rel := range []string{"news/2026/11/a-draft.html", "news/2026/12/in-future.html", "news/category/secret.html", "news/category/later.html"} {
+ if exists(t, out, rel) {
+ t.Errorf("%s is published, but the post is hidden", rel)
+ }
+ }
+ for _, rel := range []string{"news/index.html", "news/feed.xml", "index.html"} {
+ got := readOut(t, out, rel)
+ for _, hidden := range []string{"A draft", "In the future", "Secret", "Later"} {
+ if strings.Contains(got, hidden) {
+ t.Errorf("%s mentions %q, but the post is hidden", rel, hidden)
+ }
+ }
+ }
+ mustContain(t, "news index", readOut(t, out, "news/index.html"), "Status page")
+}
+
+// TestDraftsFlagShowsHiddenPosts checks the preview build.
+func TestDraftsFlagShowsHiddenPosts(t *testing.T) {
+ out, err := buildWith(t, withFiles(postNews()), func(o *Options) { o.Drafts = true })
+ if err != nil {
+ t.Fatalf("Build() error = %v", err)
+ }
+ for _, rel := range []string{"news/2026/11/a-draft.html", "news/2026/12/in-future.html", "news/category/secret.html"} {
+ if !exists(t, out, rel) {
+ t.Errorf("%s is missing from a build with drafts", rel)
+ }
+ }
+}
+
+// TestFuturePostAppearsWhenItsDateComes checks the moment of publication.
+func TestFuturePostAppearsWhenItsDateComes(t *testing.T) {
+ later := time.Date(2026, 12, 24, 12, 0, 0, 0, time.FixedZone("CET", 3600))
+ out, err := buildWith(t, withFiles(postNews()), func(o *Options) { o.Now = later })
+ if err != nil {
+ t.Fatalf("Build() error = %v", err)
+ }
+ if !exists(t, out, "news/2026/12/in-future.html") {
+ t.Error("a post is published from the moment of its date")
+ }
+ if exists(t, out, "news/2026/11/a-draft.html") {
+ t.Error("a draft stays hidden whatever the date")
+ }
+}
+
+// TestNewsLanguage checks the language of the news and its errors.
+func TestNewsLanguage(t *testing.T) {
+ tests := []struct {
+ name string
+ extra map[string]string
+ want string
+ }{
+ {"unknown language in site.json", map[string]string{
+ "site.json": strings.Replace(baseFiles()["site.json"], `"languages"`, `"news_language": "xx", "languages"`, 1)}, `news_language "xx"`},
+ {"no news page in that language", map[string]string{
+ "site.json": strings.Replace(baseFiles()["site.json"], `"languages"`, `"news_language": "it", "languages"`, 1)}, `content/it`},
+ {"post in a language the site does not have", map[string]string{
+ "news/tedesco.md": "Title: Deutsch\nDate: 2026-11-01T12:00:00+0100\nLanguage: de\n-\nText.\n"}, `Language "de"`},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ _, err := buildWith(t, withFiles(tt.extra), nil)
+ if err == nil || !strings.Contains(err.Error(), tt.want) {
+ t.Errorf("error = %v, want one that contains %q", err, tt.want)
+ }
+ })
+ }
+}
+
+// monthsJSON writes the month_01..month_12 strings of a test language.
+func monthsJSON(names ...string) string {
+ var b strings.Builder
+ for i, n := range names {
+ b.WriteString(`"month_` + string(rune('0'+(i+1)/10)) + string(rune('0'+(i+1)%10)) + `": "` + n + `", `)
+ }
+ return b.String()
+}
+
+// blogLangEn and blogLangIt are the English and Italian language files with the strings the blog features need.
+var (
+ blogLangEn = `{"lang_name": "English", "sections": "Sections", "home_link": "/", "nojs": "No JavaScript.",
+ "powered_by": "Powered by", "back": "kmalloc.org", "version": "Version", "toc": "Contents", "history_a": "Manifesto history",
+ "news_p": "What is new.", "news_all": "All news", "news_empty": "No news yet.", "category_h": "Category",
+ "date_long": "{d} {month} {y}", "date_month_year": "{month} {y}", "reading_time": "{n} min read",
+ ` + monthsJSON("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") + `
+ "post_older": "Older", "post_newer": "Newer", "post_nav": "Other news", "reply_mastodon": "Reply on Mastodon",
+ "read_more": "Read more", "pager_label": "News pages", "pager_newer": "Newer news", "pager_older": "Older news", "pager_page": "Page {n} of {total}",
+ "archive_h": "Archive", "archive_year_h": "Year", "archive_up": "Archive of the year",
+ "nav": {"manifesto": "Manifesto", "people": "People", "services": "Services", "news": "News"}}`
+ blogLangIt = `{"lang_name": "Italiano", "sections": "Sezioni", "home_link": "/it/", "nojs": "Niente JavaScript.",
+ "powered_by": "Powered by", "back": "kmalloc.org", "version": "Versione", "toc": "Indice", "history_a": "Cronologia",
+ "news_p": "Le novita.", "news_all": "Tutte le news", "news_empty": "Nessuna news.", "category_h": "Categoria",
+ "date_long": "{d} {month} {y}", "date_month_year": "{month} {y}", "reading_time": "{n} min di lettura",
+ ` + monthsJSON("gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre") + `
+ "post_older": "Piu vecchia", "post_newer": "Piu recente", "post_nav": "Altre news", "reply_mastodon": "Rispondi su Mastodon",
+ "read_more": "Leggi tutto", "pager_label": "Pagine delle news", "pager_newer": "News piu recenti", "pager_older": "News piu vecchie", "pager_page": "Pagina {n} di {total}",
+ "archive_h": "Archivio", "archive_year_h": "Anno", "archive_up": "Archivio dell'anno",
+ "nav": {"manifesto": "Manifesto", "people": "Persone", "services": "Servizi", "news": "News"}}`
+)
+
+// blogPostTemplate is a post page that uses every placeholder of the blog.
+const blogPostTemplate = `
{{post_title}}
+
+{{post_summary}}
+{{post_meta}}
+{{post_body}}
+{{post_mastodon}}
+{{post_nav}}
+`
+
+// blogBaseTemplate is the base template with the Open Graph placeholders.
+const blogBaseTemplate = `
+
+
+
+{{title_html}}
+
+
+{{article_meta}}
+
+{{alt_links}}
+
+
+
+{{header}}
+
+{{content}}
+{{footer}}
+
+
+`
+
+// blogSite is the base site with the blog language strings and templates.
+func blogSite(extra map[string]string) map[string]string {
+ files := map[string]string{
+ "lang/en.json": blogLangEn, "lang/it.json": blogLangIt,
+ "templates/post.html": blogPostTemplate, "templates/base.html": blogBaseTemplate,
+ "news/shop.md": "Title: A shop\nAuthor: squid\nDate: 2026-11-14T12:00:00+0100\nCategories: FLUG\nDescription: About the shop.\nMastodon: https://social.kmalloc.org/@squid/115\n-\nThere is a shop.\n",
+ }
+ for k, v := range extra {
+ files[k] = v
+ }
+ return withFiles(files)
+}
+
+// TestPostPageHasTheBlogFields checks the long date, the byline, the summary,
+// the reading time, the Mastodon link and the links to the other news.
+func TestPostPageHasTheBlogFields(t *testing.T) {
+ out, err := buildWith(t, blogSite(nil), nil)
+ if err != nil {
+ t.Fatalf("Build() error = %v", err)
+ }
+ shop := readOut(t, out, "news/2026/11/shop.html")
+ mustContain(t, "shop post", shop,
+ `
")
+ if strings.Contains(got, "aria-label") || strings.Contains(got, "Read more") {
+ t.Errorf("%s has a read more link without the string", rel)
+ }
+ }
+ _, err = buildWith(t, blogSite(map[string]string{"lang/en.json": withoutMore, "content/en/news/index.md": blogIndex, "templates/archive.html": archiveTemplate}), nil)
+ if err == nil || !strings.Contains(err.Error(), "read_more") {
+ t.Errorf("error = %v, want one that names read_more", err)
+ }
+}
+
+// TestPanelOfAPostInAnotherLanguage checks that the link of a panel says the language of a post that is not in the language of the page.
+func TestPanelOfAPostInAnotherLanguage(t *testing.T) {
+ out, err := buildWith(t, blogSite(map[string]string{"content/en/news/index.md": blogIndex, "templates/archive.html": archiveTemplate,
+ "news/ciao.md": "Title: Ciao\nDate: 2026-11-05T09:00:00+0100\nLanguage: it\n-\nUn testo.\n"}), nil)
+ if err != nil {
+ t.Fatalf("Build() error = %v", err)
+ }
+ index := readOut(t, out, "news/index.html")
+ mustContain(t, "news index", index, `Read more.`)
+ if strings.Count(index, `hreflang="it" lang="it">Read more`) != 1 {
+ t.Error("an English post is marked as written in Italian")
+ }
+}
+
+// TestArchiveGroupsByTheDateAsWritten checks that two posts either side of midnight, written with different
+// offsets, land in their own months and that no month is listed twice, whatever the order of the instants.
+func TestArchiveGroupsByTheDateAsWritten(t *testing.T) {
+ files := blogSite(map[string]string{"content/en/news/index.md": blogIndex, "templates/archive.html": archiveTemplate,
+ "news/late.md": "Title: Late\nDate: 2026-11-30T23:45:00+0000\n-\nText.\n",
+ "news/early.md": "Title: Early\nDate: 2026-12-01T00:30:00+0100\n-\nText.\n",
+ "news/mid.md": "Title: Mid\nDate: 2026-11-29T12:00:00+0100\n-\nText.\n"})
+ out, err := buildWith(t, files, func(o *Options) { o.Now = time.Date(2026, 12, 20, 12, 0, 0, 0, time.UTC) })
+ if err != nil {
+ t.Fatalf("Build() error = %v", err)
+ }
+ index := readOut(t, out, "news/index.html")
+ mustContain(t, "news index", index, `2026 (6)`)
+ dec, nov, sep := strings.Index(index, ">December 2026 (1)"), strings.Index(index, ">November 2026 (4)"), strings.Index(index, ">September 2026 (1)")
+ if dec < 0 || nov < dec || sep < nov {
+ t.Errorf("the months are not December, November, September, one each:\n%s", index)
+ }
+ if strings.Count(index, "November 2026") != 1 {
+ t.Error("November is listed more than once")
+ }
+ month := readOut(t, out, "news/2026/11/index.html")
+ late, mid, shop := strings.Index(month, "Late."), strings.Index(month, "Mid."), strings.Index(month, "A shop.")
+ if late < 0 || mid < late || shop < mid || strings.Contains(month, "Early.") {
+ t.Errorf("the month of November is wrong:\n%s", month)
+ }
+ mustContain(t, "month of December", readOut(t, out, "news/2026/12/index.html"), "Early.")
+}
+
+// TestNoNewsAtAll checks that a site without posts says so once, and that the empty lists take their headings with them.
+func TestNoNewsAtAll(t *testing.T) {
+ index := "Title: News\nID: news\nDescription: About News.\n-\n# News\n\n{{news_blog}}\n\n## Categories\n\n{{categories_list}}\n\n## Archive\n\n{{news_archive}}\n"
+ files := blogSite(map[string]string{"content/en/news/index.md": index, "templates/archive.html": archiveTemplate,
+ "news/shop.md": "", "news/gnu-linux-day-2026.md": "", "news/status.md": ""})
+ out, err := buildWith(t, files, nil)
+ if err != nil {
+ t.Fatalf("Build() error = %v", err)
+ }
+ got := readOut(t, out, "news/index.html")
+ if n := strings.Count(got, "No news yet."); n != 1 {
+ t.Errorf("the index says there is no news %d times, want once:\n%s", n, got)
+ }
+ for _, heading := range []string{">Categories", ">Archive"} {
+ if strings.Contains(got, heading) {
+ t.Errorf("the index keeps the heading %q of an empty list", heading)
+ }
+ }
+ mustContain(t, "news index", got, "
News
")
+}
+
+// TestHomeKeepsItsHeadingWithoutNews checks that the heading before the latest news is the page's own and stays.
+func TestHomeKeepsItsHeadingWithoutNews(t *testing.T) {
+ files := blogSite(map[string]string{"news/shop.md": "", "news/gnu-linux-day-2026.md": "", "news/status.md": ""})
+ out, err := buildWith(t, files, nil)
+ if err != nil {
+ t.Fatalf("Build() error = %v", err)
+ }
+ mustContain(t, "home", readOut(t, out, "index.html"), `
Technology.
`)
+}
+
+// TestHeadingStaysWithAListThatHasItems checks that the heading of a generated list is dropped only when the list is empty.
+func TestHeadingStaysWithAListThatHasItems(t *testing.T) {
+ index := "Title: News\nID: news\nDescription: About News.\n-\n# News\n\n## Categories\n\n{{categories_list}}\n\n## Archive\n\n{{news_archive}}\n"
+ out, err := buildWith(t, blogSite(map[string]string{"content/en/news/index.md": index, "templates/archive.html": archiveTemplate}), nil)
+ if err != nil {
+ t.Fatalf("Build() error = %v", err)
+ }
+ mustContain(t, "news index", readOut(t, out, "news/index.html"), ">Categories", ">Archive")
+}
+
+// listFiles returns the site of the pagination tests: the three base posts and extra ones, so that n posts in all.
+func listFiles(t *testing.T, n int) map[string]string {
+ t.Helper()
+ files := blogSite(map[string]string{"content/en/news/index.md": blogIndex, "templates/archive.html": archiveTemplate})
+ return manyPosts(files, n-3)
+}
+
+// TestExactlyOnePageOfPosts checks that ten posts make one page with no pager and no second page.
+func TestExactlyOnePageOfPosts(t *testing.T) {
+ out, err := buildWith(t, listFiles(t, 10), nil)
+ if err != nil {
+ t.Fatalf("Build() error = %v", err)
+ }
+ index := readOut(t, out, "news/index.html")
+ if n := strings.Count(index, `role="note"`); n != 10 {
+ t.Errorf("the index has %d panels, want 10", n)
+ }
+ if strings.Contains(index, "News pages") || strings.Contains(index, "Page 1 of") || exists(t, out, "news/page/2/index.html") {
+ t.Error("ten posts have a pager or a second page")
+ }
+}
+
+// TestEleventhPostIsAloneOnPageTwo checks the page that holds the one post that does not fit.
+func TestEleventhPostIsAloneOnPageTwo(t *testing.T) {
+ out, err := buildWith(t, listFiles(t, 11), nil)
+ if err != nil {
+ t.Fatalf("Build() error = %v", err)
+ }
+ first := readOut(t, out, "news/index.html")
+ mustContain(t, "page 1", first, "Page 1 of 2", `Older news`)
+ if n := strings.Count(first, `role="note"`); n != 10 || strings.Contains(first, "GNU/Linux Day 2026.") {
+ t.Errorf("page 1 has %d panels or the oldest post", n)
+ }
+ second := readOut(t, out, "news/page/2/index.html")
+ mustContain(t, "page 2", second, "Page 2 of 2", `Newer news`, "GNU/Linux Day 2026.")
+ if n := strings.Count(second, `role="note"`); n != 1 || strings.Contains(second, `rel="next"`) {
+ t.Errorf("page 2 has %d panels or a link to a third page", n)
+ }
+ if exists(t, out, "news/page/3/index.html") {
+ t.Error("eleven posts have a third page")
+ }
+}
+
+// TestOnlyOnePost checks that the one post has no link to a newer or an older post anywhere, and no pager.
+func TestOnlyOnePost(t *testing.T) {
+ files := blogSite(map[string]string{"content/en/news/index.md": blogIndex, "templates/archive.html": archiveTemplate,
+ "news/gnu-linux-day-2026.md": "", "news/status.md": ""})
+ out, err := buildWith(t, files, nil)
+ if err != nil {
+ t.Fatalf("Build() error = %v", err)
+ }
+ for _, rel := range []string{"news/2026/11/shop.html", "news/index.html", "news/2026/11/index.html"} {
+ got := readOut(t, out, rel)
+ for _, absent := range []string{"Older", "Newer", `rel="prev"`, `rel="next"`, "News pages"} {
+ if strings.Contains(got, absent) {
+ t.Errorf("%s has %q, but there is one post", rel, absent)
+ }
+ }
+ }
+ mustContain(t, "the post", readOut(t, out, "news/2026/11/shop.html"), `
`)
+}
+
+// TestUnusualTitle checks that a title with quotes, an ampersand, a tag and non Latin letters is escaped everywhere.
+func TestUnusualTitle(t *testing.T) {
+ title := `Say "hi" & go ünï 日本語`
+ files := blogSite(map[string]string{"content/en/news/index.md": blogIndex, "templates/archive.html": archiveTemplate,
+ "news/odd.md": "Title: " + title + "\nDate: 2026-11-15T09:00:00+0100\nCategories: Odd\n-\nText.\n"})
+ out, err := buildWith(t, files, nil)
+ if err != nil {
+ t.Fatalf("Build() error = %v", err)
+ }
+ escaped := `Say "hi" & <b>go</b> ünï 日本語`
+ attr := `Say "hi" & <b>go</b> ünï 日本語`
+ for _, rel := range []string{"news/index.html", "news/category/odd.html", "news/2026/11/index.html"} {
+ mustContain(t, rel, readOut(t, out, rel), ""+escaped+".", `aria-label="Read more: `+attr+`"`)
+ }
+ mustContain(t, "the post", readOut(t, out, "news/2026/11/odd.html"), "
"+escaped+"
")
+ mustContain(t, "the post below", readOut(t, out, "news/2026/11/shop.html"), `Newer: `+escaped)
+ for _, rel := range []string{"news/index.html", "news/category/odd.html", "news/2026/11/odd.html", "news/feed.xml"} {
+ if strings.Contains(readOut(t, out, rel), "go") {
+ t.Errorf("%s has the tag of the title as markup", rel)
+ }
+ }
+ var feed struct {
+ Channel struct {
+ Items []struct {
+ Title string `xml:"title"`
+ } `xml:"item"`
+ } `xml:"channel"`
+ }
+ if err := xml.Unmarshal([]byte(readOut(t, out, "news/feed.xml")), &feed); err != nil {
+ t.Fatalf("the feed is not well formed: %v", err)
+ }
+ if len(feed.Channel.Items) == 0 || feed.Channel.Items[0].Title != title {
+ t.Errorf("the first item of the feed is %+v, want the title %q", feed.Channel.Items, title)
+ }
+}
+
+// TestNeighbourInAnotherLanguageIsMarked checks that the link to an older post in another language names the language.
+func TestNeighbourInAnotherLanguageIsMarked(t *testing.T) {
+ out, err := buildWith(t, blogSite(map[string]string{"news/ciao.md": "Title: Ciao\nDate: 2026-11-05T09:00:00+0100\nLanguage: it\n-\nUn testo.\n"}), nil)
+ if err != nil {
+ t.Fatalf("Build() error = %v", err)
+ }
+ mustContain(t, "status post", readOut(t, out, "news/2026/11/status.html"), `rel="prev">Older: Ciao`)
+ mustContain(t, "italian post", readOut(t, out, "news/2026/11/ciao.html"), `rel="next">Piu recente: Status page`)
+}
diff --git a/internal/build/build.go b/internal/build/build.go
index a38c938..f38ea46 100644
--- a/internal/build/build.go
+++ b/internal/build/build.go
@@ -9,6 +9,7 @@ import (
"path/filepath"
"sort"
"strings"
+ "time"
"git.kmalloc.org/squid/motorino/internal/content"
"git.kmalloc.org/squid/motorino/internal/site"
@@ -24,12 +25,23 @@ type Options struct {
OutDir string
// Version is the version of motorino, shown in the generator meta.
Version string
+ // Now is the moment the site is built at: a post dated later is not
+ // published yet. The zero value means the current time.
+ Now time.Time
+ // Drafts publishes the drafts and the posts dated in the future too, for a
+ // preview of the site.
+ Drafts bool
+ // Clean empties OutDir before the site is written, when it is new, empty or
+ // was emptied this way before (it holds the file .motorino-out); any other
+ // folder with files in it is an error. Without it old files stay.
+ Clean bool
}
-// requiredPages are the IDs every site must have in its default language,
-// because motorino builds the home page and the news section itself. The
-// other pages, and the menu that links to them, are the site's own: a template
-// can link to any page with url_ and mark it with cur_.
+// requiredPages are the IDs every site must have, because motorino builds the
+// home page and the news section itself: the home in the default language and
+// the news page in the language of the news. The other pages, and the menu
+// that links to them, are the site's own: a template can link to any page with
+// url_ and mark it with cur_.
var requiredPages = []string{"home", "news"}
// newsOnHome is how many news the home page lists; feedLimit is how many the feed has.
@@ -47,12 +59,20 @@ type builder struct {
cfg site.Config
langs map[string]site.Lang
defaultLang string
- pages []content.Page
- posts []content.Post
- categories []categoryEntry
- templates map[string]string
- css string
- byKey map[pageKey]content.Page
+ // newsLang is the language the news are written in, and so the language of
+ // the news pages: the posts, the index, the archives, the categories and
+ // the feed exist once, in this language. A post can say another one.
+ newsLang string
+ // newsPath is the address of the news index, such as "/news/".
+ newsPath string
+ // now is the moment the site is built at.
+ now time.Time
+ pages []content.Page
+ posts []content.Post
+ categories []categoryEntry
+ templates map[string]string
+ css string
+ byKey map[pageKey]content.Page
// pageIDs lists the ID of every page, once, whatever the language.
pageIDs []string
// files holds the rendered output: relative path to content.
@@ -77,13 +97,18 @@ type categoryEntry struct {
type Result struct {
// Pages is the number of HTML pages written: pages, news and categories.
Pages int
+ // Stale lists the files that were already in the output folder and that this
+ // build did not write, such as the pages of a list that got shorter. They are
+ // left alone unless Clean is set, which removes them first.
+ Stale []string
}
// Build reads the site in opts.SiteDir and writes it to opts.OutDir. It renders
// everything in memory first, so a failure in the content leaves the output
// folder untouched. Writing the files is not atomic, and files of an earlier
-// build that are no longer produced are not removed: build into a fresh folder
-// when that matters, as the deploy does.
+// build that are no longer produced are not removed, but listed in Result.Stale:
+// build into a fresh folder when that matters, as the deploy does (it publishes
+// the new folder with rsync --delete), or set Options.Clean.
func Build(opts Options) (Result, error) {
b, err := load(opts)
if err != nil {
@@ -98,6 +123,9 @@ func Build(opts Options) (Result, error) {
if err := b.renderCategories(); err != nil {
return Result{}, err
}
+ if err := b.renderArchives(); err != nil {
+ return Result{}, err
+ }
if err := b.renderFeed(); err != nil {
return Result{}, err
}
@@ -108,10 +136,18 @@ func Build(opts Options) (Result, error) {
if err != nil {
return Result{}, err
}
- if err := b.write(assets); err != nil {
+ files := make(map[string][]byte, len(b.files)+len(assets))
+ for rel, text := range b.files {
+ files[rel] = []byte(text)
+ }
+ for rel, data := range assets {
+ files[rel] = data
+ }
+ stale, err := writeOutput(opts.OutDir, opts.SiteDir, opts.Clean, files)
+ if err != nil {
return Result{}, err
}
- return Result{Pages: len(b.indexable)}, nil
+ return Result{Pages: len(b.indexable), Stale: stale}, nil
}
// load reads the configuration, the content, the templates and the style.
@@ -121,14 +157,24 @@ func load(opts Options) (*builder, error) {
return nil, err
}
b := &builder{
- opts: opts, cfg: cfg, langs: langs, defaultLang: cfg.Languages[0],
+ opts: opts, cfg: cfg, langs: langs, defaultLang: cfg.Languages[0], now: opts.Now,
byKey: map[pageKey]content.Page{}, files: map[string]string{}, owners: map[string]string{},
langCtx: map[string]map[string]string{},
}
+ if b.now.IsZero() {
+ b.now = time.Now()
+ }
+ if b.newsLang, err = newsLanguage(cfg); err != nil {
+ return nil, err
+ }
if b.pages, err = content.LoadPages(opts.SiteDir, cfg.Languages); err != nil {
return nil, err
}
- if b.posts, err = content.LoadPosts(opts.SiteDir); err != nil {
+ all, err := content.LoadPosts(opts.SiteDir)
+ if err != nil {
+ return nil, err
+ }
+ if b.posts, err = b.publishedPosts(all); err != nil {
return nil, err
}
seenID := map[string]bool{}
@@ -145,13 +191,19 @@ func load(opts Options) (*builder, error) {
}
}
for _, id := range requiredPages {
- if _, ok := b.byKey[pageKey{id, b.defaultLang}]; !ok {
- return nil, fmt.Errorf("content/%s: there is no page with ID %q", b.defaultLang, id)
+ lang := b.defaultLang
+ if id == "news" {
+ lang = b.newsLang
+ }
+ if _, ok := b.byKey[pageKey{id, lang}]; !ok {
+ return nil, fmt.Errorf("content/%s: there is no page with ID %q", lang, id)
}
}
- if news := b.byKey[pageKey{"news", b.defaultLang}]; !strings.HasSuffix(news.Path, "/") {
+ news := b.byKey[pageKey{"news", b.newsLang}]
+ if !strings.HasSuffix(news.Path, "/") {
return nil, fmt.Errorf("%s: the news page must be an index (news/index.md), so that the feed has an address next to it", news.Source)
}
+ b.newsPath = news.Path
if b.templates, err = readTemplates(opts.SiteDir); err != nil {
return nil, err
}
@@ -164,6 +216,49 @@ func load(opts Options) (*builder, error) {
return b, nil
}
+// newsLanguage returns the language of the news: news_language in site.json,
+// else English when the site has it, else the default language.
+func newsLanguage(cfg site.Config) (string, error) {
+ listed := func(code string) bool {
+ for _, l := range cfg.Languages {
+ if l == code {
+ return true
+ }
+ }
+ return false
+ }
+ switch code := cfg.Strings["news_language"]; {
+ case code == "" && listed("en"):
+ return "en", nil
+ case code == "":
+ return cfg.Languages[0], nil
+ case !listed(code):
+ return "", fmt.Errorf("site.json: news_language %q is not one of the languages of the site", code)
+ default:
+ return code, nil
+ }
+}
+
+// publishedPosts gives every post the language of the news when it names none,
+// checks that the language is one of the site, and keeps the posts that are
+// published at the moment of the build: not a draft and not dated in the
+// future, unless the build is a preview with drafts.
+func (b *builder) publishedPosts(all []content.Post) ([]content.Post, error) {
+ var out []content.Post
+ for _, p := range all {
+ if p.Language == "" {
+ p.Language = b.newsLang
+ }
+ if _, ok := b.langs[p.Language]; !ok {
+ return nil, fmt.Errorf("%s: Language %q is not one of the languages of site.json", p.Source, p.Language)
+ }
+ if b.opts.Drafts || p.Visible(b.now) {
+ out = append(out, p)
+ }
+ }
+ return out, nil
+}
+
// groupCategories lists the categories of the posts, sorted by name, each with
// its posts.
func groupCategories(posts []content.Post) []categoryEntry {
@@ -253,21 +348,6 @@ func (b *builder) readAssets() (map[string][]byte, error) {
return out, nil
}
-// write creates the output folder and writes the pages and the assets.
-func (b *builder) write(assets map[string][]byte) error {
- for rel, text := range b.files {
- if err := writeFile(b.opts.OutDir, rel, []byte(text)); err != nil {
- return err
- }
- }
- for rel, data := range assets {
- if err := writeFile(b.opts.OutDir, rel, data); err != nil {
- return err
- }
- }
- return nil
-}
-
// writeFile writes data to rel under dir, creating the folders.
func writeFile(dir, rel string, data []byte) error {
path := filepath.Join(dir, filepath.FromSlash(rel))
diff --git a/internal/build/build_test.go b/internal/build/build_test.go
index 2d750ba..a0b48f8 100644
--- a/internal/build/build_test.go
+++ b/internal/build/build_test.go
@@ -454,7 +454,7 @@ func TestBuildFeed(t *testing.T) {
feed := readOut(t, out, "news/feed.xml")
mustContain(t, "feed", feed,
"https://kmalloc.org/news/2026/11/shop.html",
- `<a href="https://kmalloc.org/people.html">people</a>`)
+ `The programme is out. See people.`)
}
// TestBuildErrorsOnMissingTemplate checks that a missing layout template is named.
diff --git a/internal/build/context.go b/internal/build/context.go
index 1ab2e25..3708e26 100644
--- a/internal/build/context.go
+++ b/internal/build/context.go
@@ -11,7 +11,7 @@ import (
// blockNames are the placeholders that expand to generated HTML. Until they
// are expanded they stand for themselves, so a page can hold them.
-var blockNames = []string{"news_list", "latest_news", "categories_list"}
+var blockNames = []string{"news_list", "latest_news", "categories_list", "news_blog", "news_archive"}
// document describes one output page for the shared page frame.
type document struct {
@@ -106,6 +106,8 @@ func (b *builder) documentContext(d document) map[string]string {
ctx["title_html"] = render.EscapeAttr(title)
ctx["page_title"] = render.Escape(d.title)
ctx["description_attr"] = render.EscapeAttr(d.description)
+ ctx["og_type"] = "website"
+ ctx["article_meta"] = ""
for _, id := range b.pageIDs {
ctx["cur_"+id] = ""
if d.nav == id {
diff --git a/internal/build/date.go b/internal/build/date.go
new file mode 100644
index 0000000..cdf9173
--- /dev/null
+++ b/internal/build/date.go
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package build
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+
+ "git.kmalloc.org/squid/motorino/internal/site"
+)
+
+// longDate writes a date for a reader, in the language l, from the strings
+// date_long (a layout with {d}, {month} and {y}) and month_01 to month_12. The
+// day, the month and the year are those of the date as written, not converted
+// to another time zone. A language without the layout, or without the name of
+// the month, gets the ISO date.
+func longDate(date time.Time, l site.Lang) string {
+ layout := l.Strings["date_long"]
+ month := l.Strings[fmt.Sprintf("month_%02d", int(date.Month()))]
+ if layout == "" || month == "" {
+ return date.Format(dateOnly)
+ }
+ return strings.NewReplacer(
+ "{d}", strconv.Itoa(date.Day()), "{month}", month, "{y}", strconv.Itoa(date.Year()),
+ ).Replace(layout)
+}
+
+// monthYear is the label of an archive month in the language l, from the
+// strings date_month_year (a layout with {month} and {y}) and month_01 to
+// month_12; without them it is the year and the month, "2026-11".
+func monthYear(year, month int, l site.Lang) string {
+ layout := l.Strings["date_month_year"]
+ name := l.Strings[fmt.Sprintf("month_%02d", month)]
+ if layout == "" || name == "" {
+ return fmt.Sprintf("%04d-%02d", year, month)
+ }
+ return strings.NewReplacer("{month}", name, "{y}", strconv.Itoa(year)).Replace(layout)
+}
+
+// readingText is the reading time of a post in the language l, from the string
+// reading_time (a sentence with {n}); without the string it is empty and no
+// reading time is shown.
+func readingText(minutes int, l site.Lang) string {
+ layout := l.Strings["reading_time"]
+ if layout == "" {
+ return ""
+ }
+ return strings.ReplaceAll(layout, "{n}", strconv.Itoa(minutes))
+}
diff --git a/internal/build/date_test.go b/internal/build/date_test.go
new file mode 100644
index 0000000..5aa09d9
--- /dev/null
+++ b/internal/build/date_test.go
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package build
+
+import (
+ "testing"
+ "time"
+
+ "git.kmalloc.org/squid/motorino/internal/site"
+)
+
+// dateLang returns a language with the strings that write a date.
+func dateLang(layout string, months ...string) site.Lang {
+ l := site.Lang{Code: "xx", Strings: map[string]string{}}
+ if layout != "" {
+ l.Strings["date_long"] = layout
+ }
+ for i, m := range months {
+ l.Strings["month_"+string(rune('0'+(i+1)/10))+string(rune('0'+(i+1)%10))] = m
+ }
+ return l
+}
+
+// allMonths lists twelve month names for a test language.
+var allMonths = []string{"gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"}
+
+// TestLongDate checks the long date in a language, as written in the date.
+func TestLongDate(t *testing.T) {
+ date, err := time.Parse("2006-01-02T15:04:05-0700", "2026-11-05T23:30:00-0500")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := longDate(date, dateLang("{d} {month} {y}", allMonths...)); got != "5 novembre 2026" {
+ t.Errorf("longDate() = %q, want the day without a zero, the month name and the year", got)
+ }
+ if got := longDate(date, dateLang("{month} {d}, {y}", allMonths...)); got != "novembre 5, 2026" {
+ t.Errorf("longDate() with another layout = %q", got)
+ }
+}
+
+// TestLongDateFallsBack checks the ISO date when the language has no layout or a month.
+func TestLongDateFallsBack(t *testing.T) {
+ date, _ := time.Parse("2006-01-02T15:04:05-0700", "2026-11-14T12:00:00+0100")
+ if got := longDate(date, dateLang("")); got != "2026-11-14" {
+ t.Errorf("no layout: longDate() = %q, want the ISO date", got)
+ }
+ if got := longDate(date, dateLang("{d} {month} {y}", "uno", "due")); got != "2026-11-14" {
+ t.Errorf("a missing month name: longDate() = %q, want the ISO date", got)
+ }
+}
+
+// TestMonthYear checks the label of an archive month.
+func TestMonthYear(t *testing.T) {
+ l := dateLang("{d} {month} {y}", allMonths...)
+ l.Strings["date_month_year"] = "{month} {y}"
+ if got := monthYear(2026, 11, l); got != "novembre 2026" {
+ t.Errorf("monthYear() = %q", got)
+ }
+ if got := monthYear(2026, 3, dateLang("")); got != "2026-03" {
+ t.Errorf("monthYear() without strings = %q, want 2026-03", got)
+ }
+}
+
+// TestReadingText checks the reading time sentence and its absence.
+func TestReadingText(t *testing.T) {
+ l := site.Lang{Strings: map[string]string{"reading_time": "{n} min di lettura"}}
+ if got := readingText(3, l); got != "3 min di lettura" {
+ t.Errorf("readingText() = %q", got)
+ }
+ if got := readingText(3, site.Lang{Strings: map[string]string{}}); got != "" {
+ t.Errorf("readingText() without a string = %q, want empty", got)
+ }
+}
diff --git a/internal/build/feed.go b/internal/build/feed.go
index d9adb7c..b9a1aeb 100644
--- a/internal/build/feed.go
+++ b/internal/build/feed.go
@@ -15,10 +15,16 @@ import (
// href="/people.html", but not one that is relative to the protocol (href="//host/x").
var siteRelative = regexp.MustCompile(`\b(href|src)="/([^/])`)
+// cdata wraps text in a CDATA section; the end marker inside the text is split
+// over two sections, so it cannot close the first one.
+func cdata(text string) string {
+ return "", "]]]]>") + "]]>"
+}
+
// feed returns the RSS 2.0 feed of the latest limit posts, which must be sorted
-// newest first. Each item carries the full text with absolute links. The
-// channel is described by the language l, and newsURL is the address of the
-// news page, such as "/news/".
+// newest first. Each item has the description as a plain summary and the full
+// text, with absolute links, in content:encoded. The channel is described by
+// the language l, and newsURL is the address of the news page, such as "/news/".
func feed(base string, l site.Lang, newsURL string, posts []renderedPost, limit int) string {
if limit < len(posts) {
posts = posts[:limit]
@@ -32,7 +38,16 @@ func feed(base string, l site.Lang, newsURL string, posts []renderedPost, limit
items.WriteString("" + link + "\n")
items.WriteString(`` + link + "\n")
items.WriteString("" + p.Date.Format(time.RFC1123Z) + "\n")
- items.WriteString("" + render.Escape(text) + "\n")
+ if p.Description != "" {
+ items.WriteString("" + render.Escape(p.Description) + "\n")
+ }
+ if p.Author != "" {
+ items.WriteString("" + render.Escape(p.Author) + "\n")
+ }
+ for _, c := range p.Categories {
+ items.WriteString("" + render.Escape(c.Name) + "\n")
+ }
+ items.WriteString("" + cdata(text) + "\n")
items.WriteString("\n")
}
built := ""
@@ -41,7 +56,7 @@ func feed(base string, l site.Lang, newsURL string, posts []renderedPost, limit
}
url := base + newsURL
return `
-
+kmalloc.org: ` + render.Escape(l.Nav["news"]) + `
` + url + `
diff --git a/internal/build/feed_test.go b/internal/build/feed_test.go
index bf3b932..78c27a1 100644
--- a/internal/build/feed_test.go
+++ b/internal/build/feed_test.go
@@ -18,7 +18,7 @@ func feedLang() site.Lang {
// TestFeedItems checks the channel, the item fields, the limit and the dates.
func TestFeedItems(t *testing.T) {
items := []renderedPost{
- {Post: testPost("new", "2026-11-14", "New ", ""), HTML: `
"},
}
@@ -35,7 +35,11 @@ func TestFeedItems(t *testing.T) {
`https://kmalloc.org/news/2026/11/new.html`,
"Sat, 14 Nov 2026 12:00:00 +0100",
"Sat, 14 Nov 2026 12:00:00 +0100",
- `<a href="https://kmalloc.org/people.html">`,
+ `xmlns:content="http://purl.org/rss/1.0/modules/content/"`,
+ "A summary & more.",
+ `See people.]]>`,
+ "FLUG",
+ "Linux Day",
} {
if !strings.Contains(got, want) {
t.Errorf("feed does not contain %q\n%s", want, got)
@@ -49,6 +53,34 @@ func TestFeedItems(t *testing.T) {
}
}
+// TestFeedCarriesTheFullTextAsContent checks that the text is in content:encoded and the
+// description stays a plain summary, and that the end marker of a CDATA section in a text
+// does not close it.
+func TestFeedCarriesTheFullTextAsContent(t *testing.T) {
+ post := testPost("a", "2026-11-14", "A", "Short.")
+ post.Author = "Matteo Bini"
+ items := []renderedPost{{Post: post, HTML: "
" {
+ t.Errorf("content:encoded = %+v, want the text back as written", parsed.Channel.Items)
+ }
+}
+
// TestFeedLeavesProtocolRelativeLinks checks that "//host/x" is not given the site address.
func TestFeedLeavesProtocolRelativeLinks(t *testing.T) {
items := []renderedPost{{Post: testPost("a", "2026-11-14", "A", ""), HTML: `p`}}
diff --git a/internal/build/fixture_test.go b/internal/build/fixture_test.go
index e02e0ac..cf5d456 100644
--- a/internal/build/fixture_test.go
+++ b/internal/build/fixture_test.go
@@ -46,6 +46,12 @@ func readOut(t *testing.T, out, rel string) string {
return string(data)
}
+// readOutMaybe returns the content of a file of the output, or the error when it is missing.
+func readOutMaybe(out, rel string) (string, error) {
+ data, err := os.ReadFile(filepath.Join(out, filepath.FromSlash(rel)))
+ return string(data), err
+}
+
// mustContain fails the test for each want that is not in got.
func mustContain(t *testing.T, name, got string, wants ...string) {
t.Helper()
diff --git a/internal/build/news.go b/internal/build/news.go
index a9f6e89..eafa38c 100644
--- a/internal/build/news.go
+++ b/internal/build/news.go
@@ -24,12 +24,13 @@ type renderedPost struct {
}
// newsItem returns the
of a post for a list: the date, the title as a
-// link and, when withDescription is set and there is one, the description. News
-// are written in English, so on any other language the link says so.
+// link and, when withDescription is set and there is one, the description. A
+// post is written in its own language, so on a page in another language the
+// link says which one.
func newsItem(p content.Post, lang string, withDescription bool) string {
mark := ""
- if lang != "en" {
- mark = ` hreflang="en" lang="en"`
+ if p.Language != "" && p.Language != lang {
+ mark = fmt.Sprintf(` hreflang="%s" lang="%s"`, p.Language, p.Language)
}
day := p.Date.Format(dateOnly)
item := fmt.Sprintf(`
"
}
+// newsPanel returns a post for a list of the news as a note panel: first a small
+// line with the date and the categories, then the title in bold with a full stop
+// (unless it ends with one, a question mark or an exclamation mark), then the
+// description, then the link to read more, which names the post for a reader that
+// hears the links out of context. lang is the language of the page; the link of a
+// post in another language says so. Without the string read_more the title is the
+// link and there is no link to read more, unless needMore is set: the blog list has
+// no other link to the post, so there it is an error.
+func (b *builder) newsPanel(p content.Post, lang string, needMore bool) (string, error) {
+ l := b.langs[lang]
+ more := l.Strings["read_more"]
+ if more == "" && needMore {
+ return "", fmt.Errorf("lang/%s.json: the language has no read_more string, which the blog list needs", lang)
+ }
+ mark := ""
+ if p.Language != "" && p.Language != lang {
+ mark = fmt.Sprintf(` hreflang="%s" lang="%s"`, p.Language, p.Language)
+ }
+ meta := fmt.Sprintf(``, p.Date.Format(dateOnly), render.Escape(longDate(p.Date, l)))
+ if links := categoryLinks(p); links != "" {
+ meta += " · " + links
+ }
+ title := p.Title
+ if !strings.HasSuffix(title, ".") && !strings.HasSuffix(title, "?") && !strings.HasSuffix(title, "!") {
+ title += "."
+ }
+ var out strings.Builder
+ out.WriteString("
")
+ return out.String(), nil
+}
+
+// newsPanels returns the panels of the posts of a category or of an archive,
+// one after the other, or an empty string when there are none.
+func (b *builder) newsPanels(posts []content.Post, lang string) (string, error) {
+ panels := make([]string, len(posts))
+ for i, p := range posts {
+ panel, err := b.newsPanel(p, lang, false)
+ if err != nil {
+ return "", err
+ }
+ panels[i] = panel
+ }
+ return strings.Join(panels, "\n"), nil
+}
+
// newsList returns the full list of the news as a
, or an empty string
// when there are no posts.
func newsList(posts []content.Post, lang string) string {
diff --git a/internal/build/news_test.go b/internal/build/news_test.go
index 39bddfe..3960f21 100644
--- a/internal/build/news_test.go
+++ b/internal/build/news_test.go
@@ -23,7 +23,7 @@ func testPost(slug, day, title, description string, cats ...string) content.Post
}
return content.Post{
Slug: slug, Path: content.PostPath(date, slug), Title: title, Description: description,
- Date: date, Categories: categories, Source: "news/" + slug + ".md",
+ Language: "en", Date: date, Categories: categories, Source: "news/" + slug + ".md",
}
}
diff --git a/internal/build/output.go b/internal/build/output.go
new file mode 100644
index 0000000..0dbe133
--- /dev/null
+++ b/internal/build/output.go
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package build
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+)
+
+// motorinoMarker is the file motorino leaves in a folder it emptied with the
+// clean option. A folder that has it, or has nothing in it, may be emptied again;
+// any other folder never is. It is only written when the option is used, so the
+// folders of a build without it hold the site and nothing else.
+const motorinoMarker = ".motorino-out"
+
+// writeOutput writes the files (path with slashes, relative to out) into out and
+// returns the files that were already in out and are not among them: the pages
+// of an earlier build that this one no longer makes. With clean set it first
+// empties out, but only a folder that is new, empty or marked by an earlier clean
+// build, and never the folder of the site or one that holds it. It does not
+// touch the folder before every file is known, so a content error leaves it as
+// it was.
+func writeOutput(out, siteDir string, clean bool, files map[string][]byte) ([]string, error) {
+ if clean {
+ if err := emptyOutput(out, siteDir); err != nil {
+ return nil, err
+ }
+ files = withMarker(files)
+ }
+ for rel, data := range files {
+ if err := writeFile(out, rel, data); err != nil {
+ return nil, err
+ }
+ }
+ return staleFiles(out, files)
+}
+
+// withMarker returns the files and the marker.
+func withMarker(files map[string][]byte) map[string][]byte {
+ marked := make(map[string][]byte, len(files)+1)
+ for rel, data := range files {
+ marked[rel] = data
+ }
+ marked[motorinoMarker] = []byte("This folder is written by motorino and emptied by motorino build -clean and motorino gemini -clean.\n")
+ return marked
+}
+
+// emptyOutput removes what is in out, after checking that it may be removed.
+func emptyOutput(out, siteDir string) error {
+ absOut, err := filepath.Abs(out)
+ if err != nil {
+ return err
+ }
+ absSite, err := filepath.Abs(siteDir)
+ if err != nil {
+ return err
+ }
+ if rel, err := filepath.Rel(absOut, absSite); err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
+ return fmt.Errorf("refusing to empty %s: it is the folder of the site or holds it", out)
+ }
+ entries, err := os.ReadDir(out)
+ if os.IsNotExist(err) || (err == nil && len(entries) == 0) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("read %s: %w", out, err)
+ }
+ if info, err := os.Lstat(filepath.Join(out, motorinoMarker)); err != nil || !info.Mode().IsRegular() {
+ return fmt.Errorf("refusing to empty %s: it has files and no %s, which motorino leaves in a folder it emptied; empty it yourself this first time", out, motorinoMarker)
+ }
+ for _, entry := range entries {
+ if err := os.RemoveAll(filepath.Join(out, entry.Name())); err != nil {
+ return fmt.Errorf("empty %s: %w", out, err)
+ }
+ }
+ return nil
+}
+
+// staleFiles lists the files under out that are not among the written ones, with
+// slashes, sorted. The marker is never one of them.
+func staleFiles(out string, written map[string][]byte) ([]string, error) {
+ var stale []string
+ err := filepath.WalkDir(out, func(path string, entry os.DirEntry, err error) error {
+ if err != nil || entry.IsDir() {
+ return err
+ }
+ rel, err := filepath.Rel(out, path)
+ if err != nil {
+ return err
+ }
+ rel = filepath.ToSlash(rel)
+ if _, ok := written[rel]; !ok && rel != motorinoMarker {
+ stale = append(stale, rel)
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, fmt.Errorf("read %s: %w", out, err)
+ }
+ sort.Strings(stale)
+ return stale, nil
+}
diff --git a/internal/build/output_test.go b/internal/build/output_test.go
new file mode 100644
index 0000000..8fd0efa
--- /dev/null
+++ b/internal/build/output_test.go
@@ -0,0 +1,162 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package build
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// put writes a file of a test folder.
+func put(t *testing.T, dir, rel, text string) {
+ t.Helper()
+ path := filepath.Join(dir, filepath.FromSlash(rel))
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(text), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// extraBuilders are the other outputs the tests of the output folder run against, by name: each takes the
+// folder of a site and returns a function that builds it into a folder.
+var extraBuilders = map[string]func(site string) func(out string, clean bool) ([]string, error){}
+
+// builders are the outputs, each as a function that builds the site made of files into a folder and returns
+// the files of the folder that the build did not write.
+func builders(t *testing.T, files map[string]string) map[string]func(out string, clean bool) ([]string, error) {
+ t.Helper()
+ site := writeFiles(t, files)
+ all := map[string]func(string, bool) ([]string, error){
+ "html": func(out string, clean bool) ([]string, error) {
+ r, err := Build(Options{SiteDir: site, OutDir: out, Version: "1.2.3", Now: fixedNow, Clean: clean})
+ return r.Stale, err
+ },
+ }
+ for name, newBuilder := range extraBuilders {
+ all[name] = newBuilder(site)
+ }
+ return all
+}
+
+// TestStaleFilesAreReported checks that a build into a folder with files it did not write reports them and leaves them.
+func TestStaleFilesAreReported(t *testing.T) {
+ for name, run := range builders(t, withFiles(nil)) {
+ t.Run(name, func(t *testing.T) {
+ out := t.TempDir()
+ put(t, out, "news/page/2/index.html", "old")
+ put(t, out, "old.txt", "old")
+ stale, err := run(out, false)
+ if err != nil {
+ t.Fatalf("build error = %v", err)
+ }
+ if strings.Join(stale, ",") != "news/page/2/index.html,old.txt" {
+ t.Errorf("stale = %v, want the two old files", stale)
+ }
+ if !exists(t, out, "old.txt") {
+ t.Error("a build without -clean removed a file")
+ }
+ if exists(t, out, motorinoMarker) {
+ t.Error("a build without -clean wrote the marker into the folder")
+ }
+ })
+ }
+}
+
+// TestFreshFolderHasNothingStale checks that a build into a new folder reports nothing and writes only the site.
+func TestFreshFolderHasNothingStale(t *testing.T) {
+ for name, run := range builders(t, withFiles(nil)) {
+ t.Run(name, func(t *testing.T) {
+ stale, err := run(filepath.Join(t.TempDir(), "new"), false)
+ if err != nil || len(stale) != 0 {
+ t.Errorf("stale = %v, error = %v", stale, err)
+ }
+ })
+ }
+}
+
+// TestCleanEmptiesAFolderItMarked checks that -clean removes the old files of a folder that has the marker,
+// the pages of a list that got shorter included, and writes the marker again.
+func TestCleanEmptiesAFolderItMarked(t *testing.T) {
+ for name, run := range builders(t, withFiles(nil)) {
+ t.Run(name, func(t *testing.T) {
+ out := t.TempDir()
+ put(t, out, motorinoMarker, "x")
+ put(t, out, "news/page/2/index.html", "old")
+ put(t, out, "old/deep/file.txt", "old")
+ stale, err := run(out, true)
+ if err != nil {
+ t.Fatalf("build error = %v", err)
+ }
+ if len(stale) != 0 {
+ t.Errorf("stale = %v after a clean build", stale)
+ }
+ for _, gone := range []string{"news/page/2/index.html", "old/deep/file.txt"} {
+ if exists(t, out, gone) {
+ t.Errorf("%s is still there after -clean", gone)
+ }
+ }
+ if !exists(t, out, motorinoMarker) {
+ t.Error("the marker is gone after -clean")
+ }
+ })
+ }
+}
+
+// TestCleanTakesAnEmptyOrNewFolder checks that -clean needs no marker for a folder with nothing in it, and marks it.
+func TestCleanTakesAnEmptyOrNewFolder(t *testing.T) {
+ for name, run := range builders(t, withFiles(nil)) {
+ t.Run(name, func(t *testing.T) {
+ for _, out := range []string{t.TempDir(), filepath.Join(t.TempDir(), "new", "deeper")} {
+ if _, err := run(out, true); err != nil {
+ t.Fatalf("build into %s error = %v", out, err)
+ }
+ if !exists(t, out, motorinoMarker) {
+ t.Errorf("no marker in %s", out)
+ }
+ }
+ })
+ }
+}
+
+// TestCleanRefusesAFolderThatIsNotMotorinos checks that -clean leaves a folder with files and no marker alone.
+func TestCleanRefusesAFolderThatIsNotMotorinos(t *testing.T) {
+ for name, run := range builders(t, withFiles(nil)) {
+ t.Run(name, func(t *testing.T) {
+ out := t.TempDir()
+ put(t, out, "precious.txt", "keep me")
+ _, err := run(out, true)
+ if err == nil || !strings.Contains(err.Error(), motorinoMarker) {
+ t.Fatalf("error = %v, want one that names %s", err, motorinoMarker)
+ }
+ if got := readOut(t, out, "precious.txt"); got != "keep me" {
+ t.Errorf("precious.txt = %q", got)
+ }
+ if exists(t, out, "index.html") || exists(t, out, "index.gmi") || exists(t, out, "en/index.gmi") {
+ t.Error("the build wrote into a folder it refused to empty")
+ }
+ })
+ }
+}
+
+// TestCleanRefusesAFolderThatHoldsTheSite checks that -clean never empties the folder of the site or one above it,
+// even when it has the marker.
+func TestCleanRefusesAFolderThatHoldsTheSite(t *testing.T) {
+ parent := t.TempDir()
+ site := filepath.Join(parent, "site")
+ for rel, text := range withFiles(nil) {
+ put(t, site, rel, text)
+ }
+ put(t, parent, motorinoMarker, "x")
+ for _, out := range []string{site, parent} {
+ if _, err := Build(Options{SiteDir: site, OutDir: out, Now: fixedNow, Clean: true}); err == nil || !strings.Contains(err.Error(), "site") {
+ t.Errorf("Build into %s: error = %v, want one about the site", out, err)
+ }
+ }
+ if !exists(t, site, "site.json") {
+ t.Error("the site is gone")
+ }
+}
diff --git a/internal/build/pages.go b/internal/build/pages.go
index b161e8e..45cb424 100644
--- a/internal/build/pages.go
+++ b/internal/build/pages.go
@@ -5,6 +5,7 @@ package build
import (
"fmt"
"regexp"
+ "strconv"
"strings"
"git.kmalloc.org/squid/motorino/internal/content"
@@ -22,18 +23,51 @@ func (b *builder) renderPages() error {
return nil
}
-// renderPage converts the body of a page to HTML, expands the generated lists,
-// puts it in its layout and in the shared frame.
+// blogBlock matches a paragraph that holds the blog list placeholder.
+var blogBlock = regexp.MustCompile(`(?m)^\{\{news_blog\}\}\s*$`)
+
+// renderPage renders a page. A page with the blog list is rendered once for
+// every page of the list: the first at its own address, the others under it, at
+// page/2/, page/3/ and so on.
func (b *builder) renderPage(p content.Page) error {
+ total := 1
+ if blogBlock.MatchString(p.Body) {
+ if !strings.HasSuffix(p.Path, "/") {
+ return fmt.Errorf("%s: {{news_blog}} must be on an index page (an index.md), so that its pages have addresses under it", p.Source)
+ }
+ total = pageCount(len(b.posts))
+ }
+ for n := 1; n <= total; n++ {
+ if err := b.renderPageNumber(p, n, total); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// renderPageNumber converts the body of a page to HTML, expands the generated
+// lists, puts it in its layout and in the shared frame. n is the number of the
+// page of the blog list, out of total; both are 1 for any other page.
+func (b *builder) renderPageNumber(p content.Page, n, total int) error {
d := document{
- lang: p.Lang, id: p.ID, lead: "back", path: p.Path, title: p.Title,
+ lang: p.Lang, id: p.ID, lead: "back", path: pagePath(p.Path, n), title: p.Title,
description: p.Description, switches: p.Switch, source: p.Source,
}
d.nav = p.ID
if p.ID == "home" {
d.lead = "home"
}
+ if n > 1 {
+ label, err := b.pageLabel(p.Lang, n, total)
+ if err != nil {
+ return err
+ }
+ d.id, d.switches = "", nil
+ d.title = p.Title + ", " + label
+ d.source = fmt.Sprintf("%s (page %d of the list)", p.Source, n)
+ }
ctx := b.documentContext(d)
+ ctx["news_page_n"] = strconv.Itoa(n)
if p.ManifestoVersion != "" {
ctx["manifesto_version"] = render.Escape(p.ManifestoVersion)
}
@@ -100,7 +134,8 @@ func (b *builder) markdown(name, source, lang string, ctx map[string]string) (st
var codeElement = regexp.MustCompile(`(?s)]*>.*?`)
// expandBlocks replaces each paragraph that holds only a block placeholder by
-// the generated HTML. A block placeholder inside other text is an error. All
+// the generated HTML. An empty list of categories or of the archive goes with the
+// heading right before it. A block placeholder inside other text is an error. All
// blocks are checked before any is expanded, so the text of a generated list
// (a news title may say {{latest_news}}) is never taken for a placeholder.
func (b *builder) expandBlocks(name, html, lang string, ctx map[string]string) (string, error) {
@@ -120,11 +155,41 @@ func (b *builder) expandBlocks(name, html, lang string, ctx map[string]string) (
if err != nil {
return "", err
}
+ if generated == "" && headedBlocks[block] {
+ html = removeWithHeading(html, marker)
+ continue
+ }
html = strings.ReplaceAll(html, marker, generated)
}
return html, nil
}
+// headedBlocks are the lists a page puts under a heading of its own, which goes
+// when the list is empty. The latest news bring their heading with them, and a
+// heading before them is the page's.
+var headedBlocks = map[string]bool{"categories_list": true, "news_archive": true}
+
+// headingEnd matches the end of a heading element at the end of a text.
+var headingEnd = regexp.MustCompile(`$`)
+
+// removeWithHeading removes every marker of an empty block and the heading right
+// before it, which would be left with nothing under it.
+func removeWithHeading(html, marker string) string {
+ for {
+ at := strings.Index(html, marker)
+ if at < 0 {
+ return html
+ }
+ before := strings.TrimRight(html[:at], " \t\r\n")
+ if m := headingEnd.FindStringSubmatchIndex(before); m != nil {
+ if open := strings.LastIndex(before[:m[0]], "= 0 {
+ before = before[:open]
+ }
+ }
+ html = before + "\n" + strings.TrimLeft(html[at+len(marker):], "\n")
+ }
+}
+
// block returns the HTML of a generated list.
func (b *builder) block(name, lang string, ctx map[string]string) (string, error) {
switch name {
@@ -133,6 +198,11 @@ func (b *builder) block(name, lang string, ctx map[string]string) (string, error
return list, nil
}
return "
\n" + ctx["news_empty"] + "\n
", nil
+ case "news_blog":
+ n, _ := strconv.Atoi(ctx["news_page_n"])
+ return b.newsBlog(lang, n, ctx)
+ case "news_archive":
+ return b.newsArchive(lang, ctx)
case "latest_news":
if len(b.posts) == 0 {
return "", nil
@@ -156,13 +226,13 @@ func (b *builder) renderPosts() error {
if err != nil {
return err
}
- for _, p := range b.posts {
+ for i, p := range b.posts {
d := document{
- lang: b.defaultLang, nav: "news", lead: "news", path: p.Path, title: p.Title,
+ lang: p.Language, nav: "news", lead: "news", path: p.Path, title: p.Title,
prefixed: true, description: p.Description, source: p.Source,
}
ctx := b.documentContext(d)
- html, _, err := b.markdown(p.Source, p.Body, b.defaultLang, ctx)
+ html, _, err := b.markdown(p.Source, p.Body, p.Language, ctx)
if err != nil {
return err
}
@@ -171,6 +241,9 @@ func (b *builder) renderPosts() error {
ctx["date"] = day
ctx["post_body"] = html
ctx["post_byline"] = byline(p)
+ if err := b.postFields(i, ctx); err != nil {
+ return err
+ }
body, err := render.Substitute("templates/post.html", tmpl, ctx)
if err != nil {
return err
@@ -190,12 +263,8 @@ func byline(p content.Post) string {
if p.Author != "" {
out.WriteString(" · " + render.Escape(p.Author))
}
- if len(p.Categories) > 0 {
- links := make([]string, len(p.Categories))
- for i, c := range p.Categories {
- links[i] = fmt.Sprintf(`%s`, categoryPath(c.Slug), render.Escape(c.Name))
- }
- out.WriteString(" · " + strings.Join(links, ", "))
+ if links := categoryLinks(p); links != "" {
+ out.WriteString(" · " + links)
}
return out.String()
}
@@ -211,13 +280,17 @@ func (b *builder) renderCategories() error {
}
for _, c := range b.categories {
d := document{
- lang: b.defaultLang, nav: "news", lead: "news", path: categoryPath(c.Slug), title: c.Name, prefixed: true,
- description: b.langs[b.defaultLang].Strings["category_h"] + ": " + c.Name,
+ lang: b.newsLang, nav: "news", lead: "news", path: categoryPath(c.Slug), title: c.Name, prefixed: true,
+ description: b.langs[b.newsLang].Strings["category_h"] + ": " + c.Name,
source: fmt.Sprintf("the page of the category %q", c.Name),
}
ctx := b.documentContext(d)
ctx["category_name"] = render.Escape(c.Name)
- ctx["category_posts"] = newsList(c.posts, b.defaultLang)
+ panels, err := b.newsPanels(c.posts, b.newsLang)
+ if err != nil {
+ return err
+ }
+ ctx["category_posts"] = panels
body, err := render.Substitute("templates/category.html", tmpl, ctx)
if err != nil {
return err
@@ -231,7 +304,6 @@ func (b *builder) renderCategories() error {
// renderFeed writes the feed next to the news page.
func (b *builder) renderFeed() error {
- newsPath := b.byKey[pageKey{"news", b.defaultLang}].Path
- text := feed(b.cfg.Strings["base_url"], b.langs[b.defaultLang], newsPath, b.rendered, feedLimit)
- return b.publish(outputPath(newsPath+"feed.xml"), "the feed", text)
+ text := feed(b.cfg.Strings["base_url"], b.langs[b.newsLang], b.newsPath, b.rendered, feedLimit)
+ return b.publish(outputPath(b.newsPath+"feed.xml"), "the feed", text)
}
diff --git a/internal/build/post.go b/internal/build/post.go
new file mode 100644
index 0000000..6164108
--- /dev/null
+++ b/internal/build/post.go
@@ -0,0 +1,113 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package build
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "git.kmalloc.org/squid/motorino/internal/content"
+ "git.kmalloc.org/squid/motorino/internal/render"
+ "git.kmalloc.org/squid/motorino/internal/site"
+)
+
+// categoryLinks returns the links to the categories of a post, separated by a
+// comma, or an empty string when the post has none.
+func categoryLinks(p content.Post) string {
+ links := make([]string, len(p.Categories))
+ for i, c := range p.Categories {
+ links[i] = fmt.Sprintf(`%s`, categoryPath(c.Slug), render.Escape(c.Name))
+ }
+ return strings.Join(links, ", ")
+}
+
+// postFields adds to ctx the placeholders of the page of the post b.posts[i],
+// written in the language of the post:
+//
+// date_long the date for a reader, such as "14 November 2026"
+// post_summary the written description as a lead paragraph, or nothing
+// post_meta a line with the date, the author, the categories, the reading time
+// post_reading the reading time sentence, or nothing
+// post_mastodon the link to reply on Mastodon, or nothing
+// post_nav the links to the older and the newer post and to all the news
+// og_type article
+// article_meta the published time and a tag for each category
+//
+// Whatever needs a string that the language file lacks is left out, except the
+// Mastodon link: an address that was written and cannot be labelled is an error.
+func (b *builder) postFields(i int, ctx map[string]string) error {
+ p := b.posts[i]
+ l := b.langs[p.Language]
+ long := render.Escape(longDate(p.Date, l))
+ ctx["date_long"] = long
+
+ ctx["post_summary"] = ""
+ if p.HasDescription {
+ ctx["post_summary"] = `
` + render.Escape(p.Description) + "
"
+ }
+
+ parts := []string{fmt.Sprintf(``, p.Date.Format(dateOnly), long)}
+ if p.Author != "" {
+ parts = append(parts, render.Escape(p.Author))
+ }
+ if links := categoryLinks(p); links != "" {
+ parts = append(parts, links)
+ }
+ reading := render.Escape(readingText(p.ReadingMinutes(), l))
+ ctx["post_reading"] = reading
+ if reading != "" {
+ parts = append(parts, reading)
+ }
+ ctx["post_meta"] = `
` + strings.Join(parts, " · ") + "
"
+
+ ctx["post_mastodon"] = ""
+ if p.Mastodon != "" {
+ label := l.Strings["reply_mastodon"]
+ if label == "" {
+ return fmt.Errorf("%s: the post has a Mastodon address, but lang/%s.json has no reply_mastodon to label the link", p.Source, p.Language)
+ }
+ ctx["post_mastodon"] = fmt.Sprintf(`
`, render.EscapeAttr(p.Mastodon), render.Escape(label))
+ }
+
+ ctx["post_nav"] = b.postNav(i, l)
+
+ ctx["og_type"] = "article"
+ meta := []string{fmt.Sprintf(``, p.Date.Format(time.RFC3339))}
+ for _, c := range p.Categories {
+ meta = append(meta, fmt.Sprintf(``, render.EscapeAttr(c.Name)))
+ }
+ ctx["article_meta"] = strings.Join(meta, "\n")
+ return nil
+}
+
+// postNav returns the navigation of a post page: the newer post, the older
+// post and the link to all the news. It is empty when the language lacks the
+// strings post_older, post_newer and post_nav, or when there is nothing to link.
+func (b *builder) postNav(i int, l site.Lang) string {
+ older, newer, label := l.Strings["post_older"], l.Strings["post_newer"], l.Strings["post_nav"]
+ if older == "" || newer == "" || label == "" {
+ return ""
+ }
+ link := func(p content.Post, rel, text string) string {
+ title := render.Escape(p.Title)
+ if p.Language != "" && p.Language != l.Code {
+ title = fmt.Sprintf(`%s`, p.Language, title)
+ }
+ return fmt.Sprintf(`
\n", render.EscapeAttr(label), strings.Join(items, "\n"))
+}
diff --git a/internal/content/new.go b/internal/content/new.go
new file mode 100644
index 0000000..a293db0
--- /dev/null
+++ b/internal/content/new.go
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package content
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "git.kmalloc.org/squid/motorino/internal/mdx"
+)
+
+// NewPost writes the file of a new post in dir/news and returns its path
+// relative to dir. The name comes from the title, the date is now with its own
+// offset, the category is News and the post is a draft, so that it is not
+// published until Draft is taken out. The author line is written only when
+// author is not empty. An existing file is never written over.
+func NewPost(dir, title, author string, now time.Time) (string, error) {
+ title = strings.TrimSpace(title)
+ if title == "" || strings.ContainsAny(title, "\r\n") {
+ return "", fmt.Errorf("the title must be a single line of text")
+ }
+ if err := mdx.RejectEmDash("the title", title); err != nil {
+ return "", err
+ }
+ slug, err := CategorySlug(title)
+ if err != nil {
+ return "", fmt.Errorf("the title %q has no letters or digits to make a file name from", title)
+ }
+ rel := "news/" + slug + ".md"
+ path := filepath.Join(dir, filepath.FromSlash(rel))
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return "", fmt.Errorf("create %s: %w", filepath.Dir(path), err)
+ }
+ var b strings.Builder
+ b.WriteString("Title: " + title + "\n")
+ if author != "" {
+ b.WriteString("Author: " + author + "\n")
+ }
+ b.WriteString("Date: " + now.Format("2006-01-02T15:04:05-0700") + "\n")
+ b.WriteString("Categories: News\n")
+ b.WriteString("Description:\n")
+ b.WriteString("Draft: true\n-\n\n")
+ file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
+ if err != nil {
+ if os.IsExist(err) {
+ return "", fmt.Errorf("%s already exists", rel)
+ }
+ return "", fmt.Errorf("create %s: %w", rel, err)
+ }
+ defer file.Close()
+ if _, err := file.WriteString(b.String()); err != nil {
+ return "", fmt.Errorf("write %s: %w", rel, err)
+ }
+ return rel, nil
+}
diff --git a/internal/content/new_test.go b/internal/content/new_test.go
new file mode 100644
index 0000000..7309e48
--- /dev/null
+++ b/internal/content/new_test.go
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package content
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// newsNow is the moment the new post tests run at.
+var newsNow = time.Date(2026, 11, 16, 10, 45, 12, 0, time.FixedZone("CET", 3600))
+
+// TestNewPostWritesADraftThatLoads checks the file, its name and its header.
+func TestNewPostWritesADraftThatLoads(t *testing.T) {
+ dir := t.TempDir()
+ rel, err := NewPost(dir, "Il manifesto è cambiato", "squid", newsNow)
+ if err != nil {
+ t.Fatalf("NewPost() error = %v", err)
+ }
+ if rel != "news/il-manifesto-e-cambiato.md" {
+ t.Errorf("NewPost() = %q, want news/il-manifesto-e-cambiato.md", rel)
+ }
+ data, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{"Title: Il manifesto è cambiato\n", "Author: squid\n", "Date: 2026-11-16T10:45:12+0100\n", "Categories: News\n", "Draft: true\n", "\n-\n"} {
+ if !strings.Contains(string(data), want) {
+ t.Errorf("the file does not contain %q\n%s", want, data)
+ }
+ }
+ posts, err := LoadPosts(dir)
+ if err != nil || len(posts) != 1 {
+ t.Fatalf("LoadPosts() = %v, %v", posts, err)
+ }
+ if p := posts[0]; !p.Draft || p.Title != "Il manifesto è cambiato" || p.Author != "squid" || p.Visible(newsNow.Add(time.Hour)) {
+ t.Errorf("the new post is %+v, want a hidden draft with the title and the author", p)
+ }
+}
+
+// TestNewPostWithoutAuthor checks that no author line is written without one.
+func TestNewPostWithoutAuthor(t *testing.T) {
+ dir := t.TempDir()
+ rel, err := NewPost(dir, "No author", "", newsNow)
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, _ := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel)))
+ if strings.Contains(string(data), "Author:") {
+ t.Errorf("an Author line without an author:\n%s", data)
+ }
+}
+
+// TestNewPostRefuses checks the titles and the files it will not write over.
+func TestNewPostRefuses(t *testing.T) {
+ dir := t.TempDir()
+ if _, err := NewPost(dir, "Twice", "", newsNow); err != nil {
+ t.Fatal(err)
+ }
+ tests := []struct{ name, title, want string }{
+ {"existing file", "Twice", "already exists"},
+ {"empty title", " ", "title"},
+ {"no letters", "!!!", "no letters"},
+ {"line break", "One\nTwo", "title"},
+ {"em dash", "One — two", "dash"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ rel, err := NewPost(dir, tt.title, "", newsNow)
+ if err == nil || !strings.Contains(err.Error(), tt.want) {
+ t.Errorf("NewPost(%q) = %q, %v, want an error with %q", tt.title, rel, err, tt.want)
+ }
+ })
+ }
+}
diff --git a/internal/content/posts.go b/internal/content/posts.go
index ae5f103..b28b9c8 100644
--- a/internal/content/posts.go
+++ b/internal/content/posts.go
@@ -4,6 +4,7 @@ package content
import (
"fmt"
+ "net/url"
"os"
"path/filepath"
"regexp"
@@ -28,18 +29,54 @@ type Post struct {
Date time.Time
// Categories are the categories of the post, in the order written.
Categories []Category
+ // HasDescription is true when the header has a Description; without one,
+ // Description is the first sentence of the body and a page should not show
+ // it as a summary, because the text starts with it.
+ HasDescription bool
+ // Mastodon is the address of the post on Mastodon, where a reader can reply;
+ // empty when the header has none.
+ Mastodon string
+ // Draft is true for a post that is not to be published yet.
+ Draft bool
+ // Language is the language the post is written in, from the Language key;
+ // empty when the header has none, and the builder then uses the language of
+ // the news.
+ Language string
+ // Words is the number of words of the body.
+ Words int
// Source is the file the post was read from, relative to the site.
Source string
// Body is the Markdown after the header.
Body string
}
+// wordsPerMinute is the reading speed the reading time is worked out with.
+const wordsPerMinute = 200
+
+// ReadingMinutes returns how many minutes the post takes to read, at least 1.
+func (p Post) ReadingMinutes() int {
+ minutes := (p.Words + wordsPerMinute - 1) / wordsPerMinute
+ if minutes < 1 {
+ return 1
+ }
+ return minutes
+}
+
+// Visible reports whether the post is published at the moment now: it is not a
+// draft and its date has come.
+func (p Post) Visible(now time.Time) bool {
+ return !p.Draft && !p.Date.After(now)
+}
+
// postKeys are the keys a news header may have.
-var postKeys = []string{"Title", "Author", "Date", "Categories", "Description"}
+var postKeys = []string{"Title", "Author", "Date", "Categories", "Description", "Mastodon", "Draft", "Language"}
// dateLayouts are the accepted spellings of Date, ISO 8601 with an offset.
var dateLayouts = []string{"2006-01-02T15:04:05-0700", "2006-01-02T15:04:05Z07:00"}
+// LanguageCode is the shape of a language code: "en", "pt-BR".
+var LanguageCode = regexp.MustCompile(`^[a-z]{2,3}(-[A-Za-z0-9]+)?$`)
+
// slugName matches a file name made of lowercase words joined by hyphens.
var slugName = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
@@ -113,16 +150,55 @@ func loadPost(file string) (Post, error) {
if err != nil {
return Post{}, err
}
+ mastodon, err := parseMastodon(source, h.Get("Mastodon"))
+ if err != nil {
+ return Post{}, err
+ }
+ draft, err := parseDraft(source, h.Get("Draft"))
+ if err != nil {
+ return Post{}, err
+ }
+ language := h.Get("Language")
+ if language != "" && !LanguageCode.MatchString(language) {
+ return Post{}, fmt.Errorf("%s: Language %q is not a language code like \"en\" or \"pt-BR\"", source, language)
+ }
description := h.Get("Description")
- if description == "" {
+ hasDescription := description != ""
+ if !hasDescription {
description = firstSentence(body)
}
return Post{
Slug: slug, Path: PostPath(date, slug), Title: h.Get("Title"), Author: h.Get("Author"),
- Description: description, Date: date, Categories: categories, Source: source, Body: body,
+ Description: description, HasDescription: hasDescription, Mastodon: mastodon, Draft: draft, Language: language,
+ Words: len(strings.Fields(body)), Date: date, Categories: categories, Source: source, Body: body,
}, nil
}
+// parseMastodon accepts an empty value or an https address with a host and no
+// spaces, because the address becomes the target of a link.
+func parseMastodon(source, value string) (string, error) {
+ if value == "" {
+ return "", nil
+ }
+ u, err := url.Parse(value)
+ if err != nil || u.Scheme != "https" || u.Host == "" || strings.ContainsAny(value, " \t\"'<>") {
+ return "", fmt.Errorf("%s: Mastodon %q is not an https address, such as https://social.kmalloc.org/@squid/115000000000000000", source, value)
+ }
+ return value, nil
+}
+
+// parseDraft reads the Draft key: true or yes make a draft; false, no or no key
+// do not.
+func parseDraft(source, value string) (bool, error) {
+ switch strings.ToLower(value) {
+ case "", "false", "no":
+ return false, nil
+ case "true", "yes":
+ return true, nil
+ }
+ return false, fmt.Errorf("%s: Draft %q must be true or false", source, value)
+}
+
// parseDate reads Date in any of the accepted layouts.
func parseDate(source, value string) (time.Time, error) {
for _, layout := range dateLayouts {
diff --git a/internal/content/posts_test.go b/internal/content/posts_test.go
index c3dfda2..9e60ab9 100644
--- a/internal/content/posts_test.go
+++ b/internal/content/posts_test.go
@@ -190,3 +190,108 @@ func TestLoadPostsNoNewsFolder(t *testing.T) {
t.Errorf("LoadPosts() = %v, %v, want no posts and no error", posts, err)
}
}
+
+// postFile returns a news file with the given extra header lines.
+func postFile(extra string) string {
+ return "Title: A post\nDate: 2026-11-14T12:00:00+0100\n" + extra + "-\nOne two three four five.\n"
+}
+
+// loadOne loads a single news file and returns its post.
+func loadOne(t *testing.T, file string) (Post, error) {
+ t.Helper()
+ posts, err := LoadPosts(writeFiles(t, map[string]string{"news/a-post.md": file}))
+ if err != nil {
+ return Post{}, err
+ }
+ return posts[0], nil
+}
+
+// TestPostMastodon checks the optional reply address and its validation.
+func TestPostMastodon(t *testing.T) {
+ p, err := loadOne(t, postFile("Mastodon: https://social.kmalloc.org/@squid/115000000000000000\n"))
+ if err != nil || p.Mastodon != "https://social.kmalloc.org/@squid/115000000000000000" {
+ t.Fatalf("Mastodon = %q, err = %v", p.Mastodon, err)
+ }
+ if p, _ = loadOne(t, postFile("")); p.Mastodon != "" {
+ t.Errorf("a post without the key has Mastodon %q", p.Mastodon)
+ }
+ for _, bad := range []string{"http://social.kmalloc.org/@squid/1", "not an address", "https://", "https://a b/c", "javascript:alert(1)"} {
+ if _, err := loadOne(t, postFile("Mastodon: "+bad+"\n")); err == nil || !strings.Contains(err.Error(), "Mastodon") {
+ t.Errorf("Mastodon %q: error = %v, want one about Mastodon", bad, err)
+ }
+ }
+}
+
+// TestPostDraft checks the Draft key.
+func TestPostDraft(t *testing.T) {
+ for value, want := range map[string]bool{"true": true, "True": true, "yes": true, "false": false, "no": false} {
+ p, err := loadOne(t, postFile("Draft: "+value+"\n"))
+ if err != nil || p.Draft != want {
+ t.Errorf("Draft %q: got %v, err %v, want %v", value, p.Draft, err, want)
+ }
+ }
+ if p, _ := loadOne(t, postFile("")); p.Draft {
+ t.Error("a post without Draft must not be a draft")
+ }
+ if _, err := loadOne(t, postFile("Draft: maybe\n")); err == nil || !strings.Contains(err.Error(), "Draft") {
+ t.Errorf("Draft maybe: error = %v, want one about Draft", err)
+ }
+}
+
+// TestPostVisible checks that drafts and future dates stay hidden.
+func TestPostVisible(t *testing.T) {
+ now, _ := time.Parse("2006-01-02T15:04:05-0700", "2026-11-15T12:00:00+0100")
+ past, _ := loadOne(t, postFile(""))
+ draft, _ := loadOne(t, postFile("Draft: true\n"))
+ future, _ := loadOne(t, "Title: Later\nDate: 2026-12-01T09:00:00+0100\n-\nSoon.\n")
+ if !past.Visible(now) || draft.Visible(now) || future.Visible(now) {
+ t.Errorf("Visible: past %v draft %v future %v, want true false false", past.Visible(now), draft.Visible(now), future.Visible(now))
+ }
+ if !future.Visible(future.Date) {
+ t.Error("a post is visible from the moment of its date")
+ }
+}
+
+// TestPostHasDescription tells a written description from the fallback.
+func TestPostHasDescription(t *testing.T) {
+ written, _ := loadOne(t, postFile("Description: Written by hand.\n"))
+ fallback, _ := loadOne(t, postFile(""))
+ if !written.HasDescription || written.Description != "Written by hand." {
+ t.Errorf("written = %+v", written)
+ }
+ if fallback.HasDescription || fallback.Description != "One two three four five." {
+ t.Errorf("fallback: HasDescription %v, Description %q", fallback.HasDescription, fallback.Description)
+ }
+}
+
+// TestPostReadingMinutes checks the word count and the reading time.
+func TestPostReadingMinutes(t *testing.T) {
+ p, _ := loadOne(t, postFile(""))
+ if p.Words != 5 || p.ReadingMinutes() != 1 {
+ t.Errorf("Words %d, ReadingMinutes %d, want 5 and 1", p.Words, p.ReadingMinutes())
+ }
+ long := strings.Repeat("word ", 401) + "\n"
+ p, _ = loadOne(t, "Title: Long\nDate: 2026-11-14T12:00:00+0100\n-\n"+long)
+ if p.Words != 401 || p.ReadingMinutes() != 3 {
+ t.Errorf("Words %d, ReadingMinutes %d, want 401 and 3", p.Words, p.ReadingMinutes())
+ }
+ if (Post{}).ReadingMinutes() != 1 {
+ t.Error("an empty post still reads in 1 minute")
+ }
+}
+
+// TestPostLanguage checks the optional Language key and its validation.
+func TestPostLanguage(t *testing.T) {
+ p, err := loadOne(t, postFile("Language: it\n"))
+ if err != nil || p.Language != "it" {
+ t.Fatalf("Language = %q, err = %v", p.Language, err)
+ }
+ if p, _ = loadOne(t, postFile("")); p.Language != "" {
+ t.Errorf("a post without the key has Language %q, want empty (the builder gives it the language of the news)", p.Language)
+ }
+ for _, bad := range []string{"Italian", "IT", "i", "it_IT", "it fr"} {
+ if _, err := loadOne(t, postFile("Language: "+bad+"\n")); err == nil || !strings.Contains(err.Error(), "Language") {
+ t.Errorf("Language %q: error = %v, want one about Language", bad, err)
+ }
+ }
+}