diff --git a/CHANGELOG.md b/CHANGELOG.md index dcd4106..2e89b5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,29 +1,3 @@ -## [1.3.0](https://git.kmalloc.org/squid/motorino/compare/v1.2.0...v1.3.0) (2026-11-16) - -### Features - -* **build:** report the old files of the output folder, add -clean ([52edb15](https://git.kmalloc.org/squid/motorino/commit/52edb15b64d95959e6acdec9bc194cd2cc6aba7e)), closes [#9](https://git.kmalloc.org/squid/motorino/issues/9) -* **feed:** carry the full text in content:encoded ([3f62c79](https://git.kmalloc.org/squid/motorino/commit/3f62c7960373c044dc014c8355496038ede94e22)), closes [#9](https://git.kmalloc.org/squid/motorino/issues/9) -* **gemini:** write the site as a Gemini capsule ([2f169b8](https://git.kmalloc.org/squid/motorino/commit/2f169b8d9f79a49dcefd3ddc48e5db1404dd7e17)), closes [#10](https://git.kmalloc.org/squid/motorino/issues/10) -* **gemtext:** convert the HTML of a page to gemtext ([28745d4](https://git.kmalloc.org/squid/motorino/commit/28745d452f923081f68983679a92772fe948d53e)), closes [#10](https://git.kmalloc.org/squid/motorino/issues/10) -* **gemtext:** write a table wider than 80 columns as records ([889edbf](https://git.kmalloc.org/squid/motorino/commit/889edbfd63e9693d12957c63eda5fff1aa453229)), closes [#10](https://git.kmalloc.org/squid/motorino/issues/10) -* motorino new writes a draft, motorino build -drafts previews it ([633da1c](https://git.kmalloc.org/squid/motorino/commit/633da1c46bf9bccd5b1ee9279a4c711ff441879d)), closes [#9](https://git.kmalloc.org/squid/motorino/issues/9) -* **news:** a post page with date, author, categories, summary and links ([bf50b2e](https://git.kmalloc.org/squid/motorino/commit/bf50b2e1c2d835340415c776886e1c533f047765)), closes [#9](https://git.kmalloc.org/squid/motorino/issues/9) -* **news:** blog list with pages, and an archive by year and month ([4a501d7](https://git.kmalloc.org/squid/motorino/commit/4a501d77b3c2ecd737db39620e226efcba78d873)), closes [#9](https://git.kmalloc.org/squid/motorino/issues/9) -* **news:** hide drafts and future posts, give the news one language ([26edf78](https://git.kmalloc.org/squid/motorino/commit/26edf78449dfd66da49b0e05b5bd79869c2701ca)), closes [#9](https://git.kmalloc.org/squid/motorino/issues/9) -* **news:** show the posts of the lists as note panels ([71cf140](https://git.kmalloc.org/squid/motorino/commit/71cf14006d48084281779b83ee3d0b07fbe91024)), closes [#9](https://git.kmalloc.org/squid/motorino/issues/9) - -### Bug Fixes - -* **gemini:** list items, spaces in addresses, wide tables, per post language, empty lists, layout images ([3764470](https://git.kmalloc.org/squid/motorino/commit/3764470e9b3ef294de63f069efce54bc2ef773fe)), closes [#10](https://git.kmalloc.org/squid/motorino/issues/10) -* **news:** group the archive by the month as written, drop the empty lists ([6987541](https://git.kmalloc.org/squid/motorino/commit/6987541f88246f092b4325654f4c6789773afa53)), closes [#9](https://git.kmalloc.org/squid/motorino/issues/9) - -## [1.2.0](https://git.kmalloc.org/squid/motorino/compare/v1.1.0...v1.2.0) (2026-11-15) - -### Features - -* take the menu from the site, not from the code ([eb2a8dc](https://git.kmalloc.org/squid/motorino/commit/eb2a8dc)) - ## [1.1.0](https://git.kmalloc.org/squid/motorino/compare/v1.0.1...v1.1.0) (2026-11-15) ### Features diff --git a/README.md b/README.md index 5692809..06b5921 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # motorino -The static site generator of [kmalloc.org](https://kmalloc.org/). It turns Markdown pages, news, templates and language files into plain HTML with no JavaScript, and into a Gemini capsule. It is made for that one site and is not a general-purpose generator. +The static site generator of [kmalloc.org](https://kmalloc.org/). It turns Markdown pages, news, templates and language files into plain HTML with no JavaScript. It is made for that one site and is not a general-purpose generator. Licence: GPL-3.0-or-later, see `LICENSE`. @@ -8,18 +8,11 @@ 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 gemini -site DIR -out DIR write the same site as gemtext, for a Gemini server (defaults: . and capsule) -motorino gemini -lang CODE ... the language at the root of the capsule; -drafts and -clean work as for build -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 ``` @@ -45,36 +38,11 @@ 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`. 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. +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`. 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). @@ -82,16 +50,6 @@ Pages: `Title`, `ID` (the same in every language, it links the translations), `D `{{name}}`, with lowercase letters, digits and underscores, is replaced by a string from `site.json` or the language file. An unknown placeholder stops the build and names the file. Fenced code blocks (found the way CommonMark finds them, in lists and quotes too) are left as written, so an article can show a placeholder there. Anywhere else a backslash before the placeholder (`\{{name}}`) keeps it as written, in a code span too; two backslashes are one literal backslash followed by the value. Code spans are otherwise substituted, which is how a page shows a value in monospace. The id of a heading is not checked against ids that a template writes itself, such as the `news` of the latest news block. `{{news_list}}`, `{{latest_news}}` and `{{categories_list}}` stand alone in a paragraph and expand to generated lists. -## Gemini - -`motorino gemini` reads the same site and writes gemtext: the pages of each language, the news once and a `.meta` file for the server. It does not read the templates, the style or the layouts: a page is its title, its text and a few navigation links. - -- **Language at the root.** The language served by default sits at the root and the others under `//`, the default language of the site included. It is set with `-lang`, else `gemini_language` in `site.json`, else the default language of the site. The server must be started with the same default (Agate: `--lang`). It must be a language that has a home page. -- **`.meta`.** The server reads the language of each document from `/.meta`, which it never serves and no page links to. For every language other than the root one there are two lines, `en/*:;lang=en` and `en/**/*:;lang=en`, because a `*` does not cross folders, and the same two lines for `news/` when the news are not in the root language. It is for Agate run with `--central-conf`. A post that names another `Language` than the news has a line of its own, with the path of its file (`news/2026/11/slug.gmi:;lang=it`). The server uses the first line that matches a document, so these come first, then the folders. -- **News.** They exist once, under `/news/`, as in the website: the index, the posts, the categories, the archives and `news/feed.gmi`, a list of `=> /news/2026/11/post.gmi 2026-11-14 Title` lines, newest first, which feed readers subscribe to. Every page ends with the navigation of its language, which has the news. `{{news_blog}}` lists all the posts, without pages of ten. -- **Conversion.** A heading is a heading (three levels), a paragraph is a line, the links of a paragraph, list, quote or table follow it on lines of their own, a list is bullets (a list of only links is link lines), a quote or a note is a quote, code is a preformatted block, a table is a preformatted block of aligned columns, or, when it is wider than 80 columns, a heading for each row (its first cell) with a bullet for each other cell named by its column, a bullet for each row when there is no header or only one column, an image with an alt text is a link line, unless it belongs to the layout (it has the class `logo`, `mark` or `decorative`, or the role `presentation` or `none`: then nothing is written and the file is not copied), and emphasis is dropped. A list item with no text, only an image or a link, has no bullet; a preformatted block in an item follows its bullet. A page has one first level heading: its title; a first heading that says the title is dropped and the others go one level down. The blocks (`{{news_list}}`, `{{latest_news}}` and the others) become generated lines, with the texts of the language file. -- **Addresses.** An address of the site becomes the address of its page in the capsule (`/people.html` is `/en/people.gmi`), and a fragment is dropped. A file listed in `assets` is copied when a page points to it, and only then. `http`, `https`, `mailto`, `gemini`, `xmpp`, `irc`, `ircs`, `matrix`, `bitcoin`, `magnet`, `tel` and `sms` links stay as they are. A path the website serves by other means (`/~squid/`) becomes a link to the website when it starts with one of the comma separated prefixes of `gemini_web_paths` in `site.json`. Any other address that leads nowhere stops the build and names the page. - ## Development ``` diff --git a/cmd/motorino/main.go b/cmd/motorino/main.go index 247c26b..a1997f1 100644 --- a/cmd/motorino/main.go +++ b/cmd/motorino/main.go @@ -5,9 +5,7 @@ // // Usage: // -// motorino build [-site DIR] [-out DIR] [-drafts] [-clean] -// motorino gemini [-site DIR] [-out DIR] [-lang CODE] [-drafts] [-clean] -// motorino new [-site DIR] "title" +// motorino build [-site DIR] [-out DIR] // motorino version package main @@ -18,16 +16,13 @@ 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] [-drafts] [-clean] | motorino gemini [-site DIR] [-out DIR] [-lang CODE] [-drafts] [-clean] | motorino new [-site DIR] \"title\" | motorino version" +const usage = "usage: motorino build [-site DIR] [-out DIR] | motorino version" // main runs the command line and exits with its status code. func main() { @@ -47,10 +42,6 @@ func run(args []string, stdout, stderr io.Writer) int { return 0 case "build": return runBuild(args[1:], stdout, stderr) - case "gemini": - return runGemini(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 @@ -63,8 +54,6 @@ 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 @@ -75,84 +64,11 @@ 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(), Drafts: *drafts, Clean: *clean}) + result, err := build.Build(build.Options{SiteDir: *site, OutDir: *out, Version: version.String()}) 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]) -} - -// runGemini parses the flags of the gemini command and writes the site as a -// Gemini capsule. -func runGemini(args []string, stdout, stderr io.Writer) int { - flags := flag.NewFlagSet("gemini", flag.ContinueOnError) - flags.SetOutput(stderr) - site := flags.String("site", ".", "the folder of the site") - out := flags.String("out", "capsule", "the folder the gemtext is written to") - lang := flags.String("lang", "", "the language at the root of the capsule (default: gemini_language of site.json, then the default language)") - 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 - } - return 2 - } - if flags.NArg() > 0 { - fmt.Fprintf(stderr, "motorino: unexpected arguments: %s\n%s\n", strings.Join(flags.Args(), " "), usage) - return 2 - } - result, err := build.BuildGemini(build.GeminiOptions{SiteDir: *site, OutDir: *out, Version: version.String(), Drafts: *drafts, Language: *lang, Clean: *clean}) - if err != nil { - fmt.Fprintf(stderr, "motorino: %v\n", err) - return 1 - } - fmt.Fprintf(stdout, "wrote %d gemtext files into %s\n", result.Pages, *out) - warnStale(stderr, *out, result.Stale) - 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 } diff --git a/cmd/motorino/main_test.go b/cmd/motorino/main_test.go index bf82569..cd8f08a 100644 --- a/cmd/motorino/main_test.go +++ b/cmd/motorino/main_test.go @@ -122,192 +122,3 @@ 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) - } -} - -// TestRunGemini checks the gemini command: the capsule, the language flag and the drafts flag. -func TestRunGemini(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 - capsule := filepath.Join(t.TempDir(), "capsule") - if code := run([]string{"gemini", "-site", dir, "-out", capsule, "-lang", "en"}, &out, &errOut); code != 0 { - t.Fatalf("run(gemini) = %d, stderr %q", code, errOut.String()) - } - if want := "gemtext files into " + capsule; !strings.Contains(out.String(), want) { - t.Errorf("output %q does not contain %q", out.String(), want) - } - for _, rel := range []string{"index.gmi", "manifesto.gmi", "people.gmi", "services.gmi", "news/index.gmi", "news/feed.gmi", ".meta"} { - if _, err := os.Stat(filepath.Join(capsule, filepath.FromSlash(rel))); err != nil { - t.Errorf("no %s in the capsule: %v", rel, err) - } - } - if _, err := os.Stat(filepath.Join(capsule, "news", "2026", "01", "wip.gmi")); err == nil { - t.Error("a draft is published without -drafts") - } - preview := filepath.Join(t.TempDir(), "preview") - if code := run([]string{"gemini", "-drafts", "-site", dir, "-out", preview}, &out, &errOut); code != 0 { - t.Fatalf("run(gemini -drafts) = %d, stderr %q", code, errOut.String()) - } - if _, err := os.Stat(filepath.Join(preview, "news", "2026", "01", "wip.gmi")); err != nil { - t.Errorf("a draft is missing from the capsule with -drafts: %v", err) - } -} - -// TestRunGeminiErrors checks the exit codes: 1 for a failed build, 2 for a mistake in the command line. -func TestRunGeminiErrors(t *testing.T) { - var out, errOut bytes.Buffer - if code := run([]string{"gemini", "-site", miniSite(t), "-out", filepath.Join(t.TempDir(), "c"), "-lang", "xx"}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), `"xx"`) { - t.Errorf("an unknown language: code %d, stderr %q, want 1 and a message that names it", code, errOut.String()) - } - errOut.Reset() - if code := run([]string{"gemini", "extra"}, &out, &errOut); code != 2 || !strings.Contains(errOut.String(), "unexpected arguments") { - t.Errorf("an extra argument: code %d, stderr %q, want 2", code, errOut.String()) - } -} - -// 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") - } -} - -// TestRunGeminiOldFilesAndClean checks the warning about old files and -clean for the gemini command. -func TestRunGeminiOldFilesAndClean(t *testing.T) { - site := miniSite(t) - var out, errOut bytes.Buffer - capsule := t.TempDir() - if err := os.WriteFile(filepath.Join(capsule, "old.gmi"), []byte("old"), 0o644); err != nil { - t.Fatal(err) - } - if code := run([]string{"gemini", "-site", site, "-out", capsule}, &out, &errOut); code != 0 || !strings.Contains(errOut.String(), "old.gmi") { - t.Fatalf("run(gemini) = %d, stderr %q, want 0 and a warning that names old.gmi", code, errOut.String()) - } - errOut.Reset() - if code := run([]string{"gemini", "-clean", "-site", site, "-out", capsule}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), ".motorino-out") { - t.Fatalf("run(gemini -clean) into a folder that is not motorino's = %d, stderr %q", code, errOut.String()) - } - fresh := filepath.Join(t.TempDir(), "capsule") - for i := 0; i < 2; i++ { - errOut.Reset() - if code := run([]string{"gemini", "-clean", "-site", site, "-out", fresh}, &out, &errOut); code != 0 || errOut.Len() != 0 { - t.Fatalf("run(gemini -clean) %d = %d, stderr %q", i+1, code, errOut.String()) - } - } -} diff --git a/internal/build/blog.go b/internal/build/blog.go deleted file mode 100644 index 0a8a7a5..0000000 --- a/internal/build/blog.go +++ /dev/null @@ -1,239 +0,0 @@ -// 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 deleted file mode 100644 index fe21863..0000000 --- a/internal/build/blog_test.go +++ /dev/null @@ -1,706 +0,0 @@ -// 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

    `, - `