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(``, pagePath(b.newsPath, n-1), render.Escape(newer))) + } + parts = append(parts, render.Escape(page)) + if n < total { + parts = append(parts, fmt.Sprintf(``, 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(`
  • %s (%d)
  • `, b.monthPath(m.year, m.month), render.Escape(monthYear(m.year, m.month, b.langs[lang])), len(m.posts)) + } + return "
      \n" + strings.Join(items, "\n") + "\n
    " +} + +// 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("
  • %d (%d)\n%s
  • ", b.yearPath(y.year), y.year, len(y.posts), b.monthList(y, lang)) + } + return "
      \n" + strings.Join(items, "\n") + "\n
    ", nil +} + +// renderArchives writes the page of every year and every month that has posts, +// when the site has templates/archive.html. +func (b *builder) renderArchives() error { + if !b.hasArchive() { + return nil + } + tmpl, err := b.template("archive") + if err != nil { + return err + } + lang := b.newsLang + l := b.langs[lang] + page := func(path, name, nav string, posts []content.Post, source string) error { + d := document{ + lang: lang, nav: "news", lead: "news", path: path, title: name, prefixed: true, + description: l.Strings["archive_h"] + ": " + name, source: source, + } + ctx := b.documentContext(d) + ctx["archive_name"] = render.Escape(name) + ctx["archive_nav"] = nav + panels, err := b.newsPanels(posts, lang) + if err != nil { + return err + } + ctx["archive_posts"] = panels + body, err := render.Substitute("templates/archive.html", tmpl, ctx) + if err != nil { + return err + } + return b.frame(d, ctx, body) + } + for _, y := range groupArchive(b.posts) { + year := strconv.Itoa(y.year) + if err := page(b.yearPath(y.year), year, b.monthList(y, lang), y.posts, "the archive of "+year); err != nil { + return err + } + up := "" + if text := l.Strings["archive_up"]; text != "" { + up = fmt.Sprintf("

    %s %s

    ", 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, + `

    About the shop.

    `, + `

    · squid · FLUG · 1 min read

    `, + `

    Reply on Mastodon

    `, + `