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
58 lines
1.9 KiB
Go
58 lines
1.9 KiB
Go
// 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
|
|
}
|