feat(news): hide drafts and future posts, give the news one language

- Draft: true and a date in the future keep a post out of the pages, the lists,
  the categories and the feed. motorino build -drafts (next commit) shows them.
- news_language in site.json, and an optional Language key in a post, choose the
  language of the news pages and of the interface strings they use. The news
  still exist once, not once per language.
- New header keys Mastodon (an https address), Draft and Language; a post knows
  its reading time and whether its description was written.

Refs #9
This commit is contained in:
tgiachi 2026-11-16 12:04:50 +01:00
commit 26edf78449
10 changed files with 546 additions and 31 deletions

129
internal/build/blog_test.go Normal file
View file

@ -0,0 +1,129 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package build
import (
"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)
}
})
}
}

View file

@ -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,19 @@ 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
}
// 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_<id> and mark it with cur_<id>.
// 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_<id> and mark it with cur_<id>.
var requiredPages = []string{"home", "news"}
// newsOnHome is how many news the home page lists; feedLimit is how many the feed has.
@ -47,6 +55,14 @@ type builder struct {
cfg site.Config
langs map[string]site.Lang
defaultLang string
// 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
@ -121,14 +137,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 +171,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 +196,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 {

51
internal/build/date.go Normal file
View file

@ -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))
}

View file

@ -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)
}
}

View file

@ -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()

View file

@ -24,12 +24,13 @@ type renderedPost struct {
}
// newsItem returns the <li> 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(`<li><time datetime="%s">%s</time> <a href="%s"%s>%s</a>`,

View file

@ -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",
}
}

View file

@ -158,11 +158,11 @@ func (b *builder) renderPosts() error {
}
for _, 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
}
@ -211,13 +211,13 @@ 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)
ctx["category_posts"] = newsList(c.posts, b.newsLang)
body, err := render.Substitute("templates/category.html", tmpl, ctx)
if err != nil {
return err
@ -231,7 +231,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)
}

View file

@ -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 {

View file

@ -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)
}
}
}