add khosra new, which writes the first bytes into a site root
Scaffolds a **directory** bundle — the only shape that can own local files, so the other kind would hand an author a page their pictures cannot live beside. What it writes is a draft: title, today's date, `draft: true`. A tool that publishes the moment it runs publishes by accident, and drafts are honoured now. This is the first thing that writes into somebody's content directory, so it goes through os.Root like every read does (ADR-0031), and it never overwrites: an existing bundle is an error. Two bugs found by running it rather than by testing it: A key of `../escape` did not fail. It never left the site root — path.Join collapses `..` first — but it wrote a real directory *inside* the root and outside content/, which is not an escape and not a bundle either. Refused outright now, the same guard the include path needed for the same reason. The test asserts what should be true — content/ is the only thing this creates — because the weaker assertion I wrote first would have passed. `khosra new posts/x -site dir` silently ignored -site, because Go's flag package stops at the first non-flag argument, and then failed complaining there was no site root. Parsed in rounds now, so either order works. main() crossed the function-length warning as a result, so it became a dispatch table with runServe beside it — the warning was right about the code.
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
// Package scaffold writes a new bundle into a site root.
|
||||
//
|
||||
// Contributes: the `new` subcommand (no request-path behaviour).
|
||||
// Cascade keys: none.
|
||||
// Contract fields: none.
|
||||
// Not doing: per-type templates for the scaffold — an author who wants their own boilerplate wants archetypes,
|
||||
// which is a site-root feature and a decision, not a flag.
|
||||
package scaffold
|
||||
@@ -0,0 +1,94 @@
|
||||
package scaffold
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"khosra/internal/content"
|
||||
)
|
||||
|
||||
// New writes a bundle for key in lang, and returns the file it created.
|
||||
//
|
||||
// A **directory** bundle, always: only a directory bundle can own local files (content-model.md), so scaffolding
|
||||
// the other shape would hand an author a page their pictures cannot live beside. The frontmatter says
|
||||
// `draft: true`, because a tool that publishes the moment it is run is a tool that publishes by accident — and
|
||||
// drafts are honoured now (ADR-0024).
|
||||
//
|
||||
// Every write goes through [os.Root], so a key with `..` in it cannot escape the site root any more than a
|
||||
// request can (ADR-0031). Nothing is overwritten: an existing bundle is an error, never a silent replacement.
|
||||
func New(siteDir, key, lang, title string) (string, error) {
|
||||
key = content.Normalise(strings.Trim(strings.TrimSpace(key), "/"))
|
||||
if key == "" {
|
||||
return "", errors.New("no key: pass something like posts/hello-world")
|
||||
}
|
||||
// `..` is refused before anything is joined. os.Root stops an escape from the site root, but path.Join
|
||||
// collapses `..` first — so `../outside` would have written a real directory *inside* the root and outside
|
||||
// content/, which is not an escape but is not a bundle either. The include guard exists for the same reason.
|
||||
for _, segment := range strings.Split(key, "/") {
|
||||
if segment == ".." || segment == "." {
|
||||
return "", fmt.Errorf("a key names a place under content/, so %q cannot contain %q", key, segment)
|
||||
}
|
||||
}
|
||||
if lang == "" {
|
||||
lang = content.DefaultLang
|
||||
}
|
||||
if title == "" {
|
||||
title = titleFrom(key)
|
||||
}
|
||||
root, err := os.OpenRoot(siteDir)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("open site root %s: %w", siteDir, err)
|
||||
}
|
||||
defer root.Close()
|
||||
|
||||
dir := path.Join("content", key)
|
||||
if err := mkdirAll(root, dir); err != nil {
|
||||
return "", err
|
||||
}
|
||||
name := path.Join(dir, "index."+lang+".md")
|
||||
if _, err := root.Stat(name); err == nil {
|
||||
return "", fmt.Errorf("%s already exists, and nothing here overwrites content", name)
|
||||
}
|
||||
file, err := root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create %s: %w", name, err)
|
||||
}
|
||||
defer file.Close()
|
||||
if _, err := file.WriteString(frontmatter(title)); err != nil {
|
||||
return "", fmt.Errorf("write %s: %w", name, err)
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
// frontmatter is the bundle a new page starts as: the one required field, today's date, and a draft flag the
|
||||
// author removes when it is ready.
|
||||
func frontmatter(title string) string {
|
||||
return fmt.Sprintf("---\ntitle: %s\ndate: %s\ndraft: true\n---\n\n",
|
||||
title, content.Now().Format("2006-01-02"))
|
||||
}
|
||||
|
||||
// titleFrom turns a slug into a plausible title: hyphens and underscores become spaces, and the first letter is
|
||||
// capitalised. Only the first — the engine does not know which of an author's words are proper nouns.
|
||||
func titleFrom(key string) string {
|
||||
words := strings.NewReplacer("-", " ", "_", " ").Replace(path.Base(key))
|
||||
if words == "" {
|
||||
return ""
|
||||
}
|
||||
return strings.ToUpper(words[:1]) + words[1:]
|
||||
}
|
||||
|
||||
// mkdirAll creates dir and any missing parent inside the root, since os.Root offers one level at a time.
|
||||
func mkdirAll(root *os.Root, dir string) error {
|
||||
built := ""
|
||||
for _, segment := range strings.Split(dir, "/") {
|
||||
built = path.Join(built, segment)
|
||||
if err := root.Mkdir(built, 0o755); err != nil && !errors.Is(err, fs.ErrExist) {
|
||||
return fmt.Errorf("create %s: %w", built, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package scaffold
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"khosra/internal/content"
|
||||
)
|
||||
|
||||
func TestNewWritesADirectoryBundleThatScansAsADraft(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
written, err := New(dir, "posts/hello-world", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A directory bundle, because only that shape can own local files (content-model.md).
|
||||
if written != "content/posts/hello-world/index.en.md" {
|
||||
t.Errorf("wrote %q, want a directory bundle", written)
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(dir, written))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Parsed by the engine's own parser, not by eye: the scaffold has to be something khosra can read.
|
||||
b, err := content.Parse(strings.TrimPrefix(written, "content/"), data)
|
||||
if err != nil {
|
||||
t.Fatalf("the engine cannot parse its own scaffold: %v\n%s", err, data)
|
||||
}
|
||||
if b.Title != "Hello world" {
|
||||
t.Errorf("title = %q, want one derived from the slug", b.Title)
|
||||
}
|
||||
if !b.Draft {
|
||||
t.Error("a scaffold must be a draft: a tool that publishes when it runs publishes by accident")
|
||||
}
|
||||
if b.Date.IsZero() {
|
||||
t.Error("no date was written")
|
||||
}
|
||||
if b.Key != "posts/hello-world" {
|
||||
t.Errorf("key = %q", b.Key)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewHonoursLanguageAndTitle(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
written, err := New(dir, "pages/about", "bn", "পরিচিতি")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if written != "content/pages/about/index.bn.md" {
|
||||
t.Errorf("wrote %q, want the Bengali variant", written)
|
||||
}
|
||||
data, _ := os.ReadFile(filepath.Join(dir, written))
|
||||
if !strings.Contains(string(data), "title: পরিচিতি") {
|
||||
t.Errorf("the given title should be used verbatim:\n%s", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewNeverOverwritesAndNeverEscapes(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if _, err := New(dir, "posts/twice", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := New(dir, "posts/twice", "", ""); err == nil {
|
||||
t.Error("a second run must refuse rather than replace someone's writing")
|
||||
}
|
||||
// os.Root refuses an escape, and the key is normalised and trimmed before it is used at all (ADR-0031).
|
||||
for _, key := range []string{"../outside", "posts/../../outside", "", "/"} {
|
||||
if _, err := New(dir, key, "", ""); err == nil {
|
||||
t.Errorf("New(%q) should have failed", key)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(filepath.Dir(dir), "outside")); err == nil {
|
||||
t.Fatal("something was written outside the site root")
|
||||
}
|
||||
// The weaker check above is not enough: `../outside` does not escape the root, it lands *inside* it and
|
||||
// outside content/, because path.Join collapses `..` before os.Root ever sees the name. So assert what
|
||||
// should be true — content/ is the only thing this ever creates.
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.Name() != "content" {
|
||||
t.Errorf("created %q at the site root; only content/ should ever appear", e.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user