feat: motorino new writes a draft, motorino build -drafts previews it
All checks were successful
check / check (pull_request) Successful in 30s

motorino new -site DIR "A title" writes news/a-title.md with the header ready:
the date of now, the author from site.json, the category News and Draft: true.
motorino build -drafts publishes the drafts and the posts dated in the future,
for a preview. The README describes the header keys, the news language, the blog
placeholders and blocks, and the language strings they use.

Refs #9
This commit is contained in:
tgiachi 2026-11-16 12:10:30 +01:00
commit 633da1c46b
5 changed files with 268 additions and 4 deletions

View file

@ -8,6 +8,8 @@ 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 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
```
@ -38,11 +40,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/<name>.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/<name>.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/<lang>/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 entries (title, long date, categories, description, a read more link), 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`. `{{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).

View file

@ -5,7 +5,8 @@
//
// Usage:
//
// motorino build [-site DIR] [-out DIR]
// motorino build [-site DIR] [-out DIR] [-drafts]
// 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] | 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,7 @@ 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")
if err := flags.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
return 0
@ -64,7 +71,7 @@ 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})
if err != nil {
fmt.Fprintf(stderr, "motorino: %v\n", err)
return 1
@ -72,3 +79,32 @@ func runBuild(args []string, stdout, stderr io.Writer) int {
fmt.Fprintf(stdout, "built %d pages into %s\n", result.Pages, *out)
return 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
}

View file

@ -122,3 +122,68 @@ 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)
}
}

58
internal/content/new.go Normal file
View file

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

View file

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