frontmatter

package
v0.0.39 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2026 License: Apache-2.0, MIT Imports: 11 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

draft/frontmatter

Metadata extraction, YAML frontmatter generation, and identity-preserving regeneration of an article set.

Go reference Website

Contents

Install

go get github.com/sebastienrousseau/draft@latest
import "github.com/sebastienrousseau/draft/frontmatter"

Quick start

package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/sebastienrousseau/draft/frontmatter"
)

func main() {
	body := "# Router-S Cuts Compute\n\n**One number tells the story.**\n\nRouter-S used 5x fewer FLOPs.\n"

	meta := frontmatter.ExtractMetadata(body) // title, subtitle, keywords, category
	fmt.Println("title:", meta.Title)

	site := frontmatter.DefaultSite
	site.Name = "My Site"

	yaml := frontmatter.GenerateWithOptions(body, frontmatter.Options{
		Date:     time.Date(2026, 7, 29, 0, 0, 0, 0, time.UTC),
		Slug:     "router-s-cuts-compute",                     // the filename is the identity, not the headline
		Site:     &site,                                       // nil selects frontmatter.DefaultSite
		Existing: map[string]string{"author": "Ada Lovelace"}, // curated fields always win
	})
	doc := frontmatter.Combine(yaml, body)
	fmt.Printf("combined document: %d bytes\n", len(doc))

	// Split is Combine's inverse, up to surrounding whitespace: both trim, so
	// the round trip is stable rather than byte-identical to a padded input.
	gotYAML, gotBody := frontmatter.Split(doc)
	fmt.Println(len(gotYAML) > 0, gotBody == strings.TrimSpace(body))

	// ProcessFile writes the body/yaml/final set beside the input.
	dir, err := os.MkdirTemp("", "draft-*")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)

	path := filepath.Join(dir, "2026-07-29-router-s-cuts-compute-body.md")
	if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
		log.Fatal(err)
	}

	bodyPath, yamlPath, finalPath, err := frontmatter.ProcessFile(path, time.Now())
	if err != nil {
		log.Fatalf("regenerating the article set: %v", err)
	}
	fmt.Println(filepath.Base(bodyPath), filepath.Base(yamlPath), filepath.Base(finalPath))
}

API

Symbol Signature Purpose
ExtractMetadata func(markdown string) Metadata Title, subtitle, description, excerpt, keywords, tags, category, slug
Generate func(markdown string, date time.Time) string Frontmatter from the body alone
GenerateWithOptions func(markdown string, opts Options) string Same, honouring slug, site and existing fields
Combine func(frontmatterYAML, body string) string Join into one publishable document
Split func(content string) (string, string) Inverse of Combine
ProcessFile func(inputPath string, date time.Time) (bodyPath, frontmatterPath, finalPath string, err error) Write or rewrite the whole set
PartOfSet func(path string) bool Whether a path belongs to a generated set
Slugify func(s string) string URL-friendly slug
Site / DefaultSite / SiteFromEnv publisher identity See below
Options struct{ Date time.Time; Slug string; Existing map[string]string; Site *Site } Generation inputs beyond the body

The three regeneration rules

ProcessFile is safe to run at any time because of three guarantees:

  1. The filename is the article's identity. A YYYY-MM-DD prefix and the slug in the filename drive every URL in the frontmatter. Retitle the article and the permalink holds.
  2. Your edits always win. Values in Options.Existing — read back from the prior frontmatter — are preserved verbatim; only missing fields are generated. Delete a field to have it rebuilt.
  3. Unchanged input is a no-op. Reprocessing a set that has not changed rewrites every file byte for byte identically.

The set is three files, written side by side:

2026-07-29/
├── source/2026-07-29-<slug>-body.md         # the article — edit this
├── yaml/2026-07-29-<slug>-frontmatter.yaml  # adjacent frontmatter
└── final/2026-07-29-<slug>-final.md         # combined, ready to publish

Publisher identity

Site holds the identity stamped into generated frontmatter: base URL, CDN, display name, short name, email, Twitter handle, location, measurement ID and the first year of the copyright range.

Options.Site of nil selects DefaultSite. SiteFromEnv returns DefaultSite with any DRAFT_SITE_* environment overrides applied, which is what the CLI uses. Curated frontmatter fields still win over anything generated from a Site.

License

Licensed under either of Apache License 2.0 or MIT License, at your option. © Sebastien Rousseau.

Back to top ↑

Documentation

Overview

Package frontmatter extracts metadata from article Markdown and generates YAML frontmatter, as well as splitting and combining frontmatter and article bodies.

Index

Examples

Constants

View Source
const MaxArticleBytes = 32 << 20

MaxArticleBytes bounds how large a Markdown file ProcessFile will read. An article is prose; anything past this is a mistake, and reading it would cost several times its size once metadata extraction runs over it.

Variables

View Source
var DefaultSite = Site{
	BaseURL:       "https://sebastienrousseau.com",
	CDN:           "https://cloudcdn.pro",
	Name:          "Sebastien Rousseau",
	ShortName:     "sebastienrousseau",
	Email:         "contact@sebastienrousseau.com",
	TwitterHandle: "@wwdseb",
	Location:      "London, UK",
	MeasurementID: "G-169G4ET5HQ",
	CopyrightFrom: 2025,
}

DefaultSite is the publisher identity used when Options.Site is nil.

Functions

func Combine

func Combine(frontmatterYAML, body string) string

Combine joins a YAML frontmatter block (with --- delimiting lines) and a Markdown body.

func Generate

func Generate(markdown string, date time.Time) string

Generate constructs a YAML frontmatter string conforming to the standard schema.

func GenerateWithOptions

func GenerateWithOptions(markdown string, opts Options) string

GenerateWithOptions constructs the standard frontmatter schema, preferring opts.Existing values over generated ones so curated metadata survives regeneration.

Example

GenerateWithOptions stamps your own publisher identity, and any field already present in Existing wins over a generated one.

package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/sebastienrousseau/draft/frontmatter"
)

func main() {
	site := frontmatter.Site{BaseURL: "https://example.org", Name: "Ada"}
	yaml := frontmatter.GenerateWithOptions("# Title\n\nBody.", frontmatter.Options{
		Date:     time.Date(2026, 1, 15, 0, 0, 0, 0, time.UTC),
		Slug:     "my-canonical-slug",
		Site:     &site,
		Existing: map[string]string{"category": `"Technology"`},
	})
	for _, line := range []string{`url: "https://example.org/2026-01-15-my-canonical-slug"`, `category: "Technology"`} {
		fmt.Println(contains(yaml, line))
	}
}

func contains(haystack, needle string) bool { return strings.Contains(haystack, needle) }
Output:
true
true

func PartOfSet

func PartOfSet(path string) bool

PartOfSet reports whether path belongs to a generated body/frontmatter/final trio, either by filename suffix or by sitting in a day-folder source/ or final/ directory.

func ProcessFile

func ProcessFile(inputPath string, date time.Time) (bodyPath, frontmatterPath, finalPath string, err error)

ProcessFile reads a Markdown file, generates adjacent frontmatter, and writes the body, adjacent frontmatter, and final combined files. The filename is the article's publishing identity: a YYYY-MM-DD prefix takes precedence over date and the remaining stem becomes the canonical slug, so regenerating never changes an article's permalink. Existing frontmatter — from the input itself or from the adjacent -frontmatter.yaml — is preserved field by field; only missing fields are generated from the body.

func Slugify

func Slugify(s string) string

Slugify converts text into a URL-friendly slug.

func Split

func Split(content string) (string, string)

Split divides a raw document into frontmatter (if present) and body content.

Example

Split separates an existing frontmatter block from the body, and Combine puts them back together — the round trip is lossless.

package main

import (
	"fmt"

	"github.com/sebastienrousseau/draft/frontmatter"
)

func main() {
	doc := "---\ntitle: \"Kept\"\n---\n\n# Body\n\nProse."
	fm, body := frontmatter.Split(doc)
	fmt.Println(len(fm) > 0, body)
}
Output:
true # Body

Prose.

Types

type Metadata

type Metadata struct {
	Title       string
	Subtitle    string
	Description string
	Excerpt     string
	Keywords    string
	Tags        string
	Category    string
	Slug        string
}

Metadata holds extracted article metadata fields used to build YAML frontmatter.

func ExtractMetadata

func ExtractMetadata(markdown string) Metadata

ExtractMetadata parses the Markdown body and extracts metadata for frontmatter generation.

Example

ExtractMetadata reads the article body: the H1 is the title, a deck paragraph or bold line is the subtitle, and the category is scored from the text rather than taken from the first keyword that matches.

package main

import (
	"fmt"

	"github.com/sebastienrousseau/draft/frontmatter"
)

func main() {
	meta := frontmatter.ExtractMetadata("# Agent Autonomy in Banking\n\n" +
		"<p class=\"deck\">What boards must certify before agents act.</p>\n")
	fmt.Println(meta.Title)
	fmt.Println(meta.Subtitle)
	fmt.Println(meta.Slug)
}
Output:
Agent Autonomy in Banking
What boards must certify before agents act.
agent-autonomy-in-banking

type Options

type Options struct {
	// Date is used for all date-derived fields when the corresponding
	// existing field is absent. Zero means time.Now().
	Date time.Time
	// Slug overrides the title-derived slug for URL-shaped fields, so a
	// file's canonical URL follows its filename rather than its headline.
	Slug string
	// Existing holds field values from prior frontmatter (raw, as they
	// appeared after "key: "). They always win over generated values;
	// delete a field from the source frontmatter to have it regenerated.
	Existing map[string]string
	// Site is the publisher identity; nil means DefaultSite.
	Site *Site
	// Engine, Model and Version record what wrote the article: the backend
	// that produced the body, the model it used, and the draft release that
	// ran. They are emitted only when set, so a set regenerated from its
	// files keeps whatever provenance it already carries and gains none it
	// cannot prove.
	Engine  string
	Model   string
	Version string
}

Options adjusts how Generate builds frontmatter beyond what the body provides.

type Site

type Site struct {
	BaseURL       string // canonical site root, e.g. https://sebastienrousseau.com
	CDN           string // asset host, e.g. https://cloudcdn.pro
	Name          string // display name
	ShortName     string // slug-like identity used in asset paths
	Email         string
	TwitterHandle string
	Location      string
	MeasurementID string
	CopyrightFrom int // first year of the copyright range
}

Site holds the publisher identity stamped into generated frontmatter.

func SiteFromEnv

func SiteFromEnv() Site

SiteFromEnv returns DefaultSite with any DRAFT_SITE_* environment overrides applied: BASE_URL, CDN, NAME, SHORT_NAME, EMAIL, TWITTER, LOCATION, MEASUREMENT_ID, and COPYRIGHT_FROM. Unset or malformed values keep the default, so a partial override is always safe.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL