Files
davidandClaude Opus 5.5 1152cd448b Phase 5 part 1: read a site's section types and pages
Sites → Sections and pages reads the website's Hugo repository: each
section type with the README's description, the fields in use and the
layout's, the pages using it and a real example; the pages and their
sections; the latest commits. Working copies are now held by one job at a
time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 13:52:35 -07:00

381 lines
10 KiB
Go

// Package sites reads and builds a Hugo website whose pages are made of
// sections: each page's front matter has a `sections:` list, and each
// section's `type` names a partial in layouts/partials/sections/. The
// catalogue of a site's section types comes from the site itself (its
// partials, its README, and how its pages use them), so new pages are
// made only of what the site already knows how to show.
package sites
import (
"bufio"
"bytes"
"io/fs"
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"strings"
"gopkg.in/yaml.v3"
)
// SectionType is one kind of section the site can show.
type SectionType struct {
Name string
Doc string // from the README, when it says what the type takes
Fields []Field // seen in the site's pages, most used first
Layout []string // fields the layout reads, its helpers' included
Pages []string // paths of the pages that use it
Uses int // how many times it's used, all pages together
Example string // one real use, as YAML
Missing bool // used by pages, but there's no partial for it
exampleSize int
}
// Field is a field seen in use, with the keys of its list items when it's
// a list of maps.
type Field struct {
Name string
Items []string
Count int
}
// Page is one content page.
type Page struct {
File string // relative to the repository
Path string // where it's published
Title string
Types []string // its sections' types, in order
Draft bool
Sections bool // it's built from sections (not a Markdown body)
}
// Catalog is what a site is made of.
type Catalog struct {
Types []SectionType
Helpers []string // partials the sections share (headings, buttons…)
Pages []Page
}
// Type finds a section type by name.
func (c *Catalog) Type(name string) *SectionType {
for i := range c.Types {
if c.Types[i].Name == name {
return &c.Types[i]
}
}
return nil
}
// Has says whether the site has the section type.
func (c *Catalog) Has(name string) bool {
t := c.Type(name)
return t != nil && !t.Missing
}
// PathFunc says where a content file (relative to content/) is published.
type PathFunc func(rel string) string
var (
partialRef = regexp.MustCompile(`partial\s+"sections/([\w-]+)\.html"\s*(?:(\$s|\.)(?:\s|-?\}\}|\)))?`)
dollarS = regexp.MustCompile(`\$s\.([a-z]\w*)`)
bareDot = regexp.MustCompile(`(?:^|[\s(])\.([a-z]\w*)`)
readmeList = regexp.MustCompile("^\\s*[-*]\\s+`([\\w-]+)`\\s+[—–-]+\\s+(.+)$")
readmeRow = regexp.MustCompile("^\\|\\s*`([\\w-]+)`\\s*\\|\\s*(.+?)\\s*\\|\\s*$")
)
// Read reads the catalogue from a working copy of the site.
func Read(dir string, pathOf PathFunc) (*Catalog, error) {
partDir := filepath.Join(dir, "layouts", "partials", "sections")
entries, err := os.ReadDir(partDir)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
partials := map[string]string{}
for _, e := range entries {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".html") {
raw, err := os.ReadFile(filepath.Join(partDir, e.Name()))
if err != nil {
return nil, err
}
partials[strings.TrimSuffix(e.Name(), ".html")] = string(raw)
}
}
// Partials named by another partial, or by render-sections, are
// helpers unless a page uses them as a type.
referenced := map[string]bool{}
calls := map[string][]string{} // partial → helpers it hands the section to
for name, src := range partials {
for _, m := range partialRef.FindAllStringSubmatch(src, -1) {
referenced[m[1]] = true
if m[2] != "" {
calls[name] = append(calls[name], m[1])
}
}
}
if raw, err := os.ReadFile(filepath.Join(dir, "layouts", "partials", "render-sections.html")); err == nil {
for _, m := range partialRef.FindAllStringSubmatch(string(raw), -1) {
referenced[m[1]] = true
}
}
c := &Catalog{}
uses := map[string]*SectionType{}
fieldCount := map[string]map[string]*Field{}
get := func(name string) *SectionType {
t := uses[name]
if t == nil {
t = &SectionType{Name: name}
uses[name] = t
fieldCount[name] = map[string]*Field{}
}
return t
}
root := filepath.Join(dir, "content")
err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
if os.IsNotExist(err) && p == root {
return fs.SkipDir
}
return err
}
if d.IsDir() || !strings.EqualFold(filepath.Ext(p), ".md") {
return nil
}
rel, _ := filepath.Rel(root, p)
pg := Page{File: filepath.ToSlash(filepath.Join("content", rel)), Path: pathOf(rel)}
fm, node, err := readFrontMatter(p)
if err != nil || fm == nil {
// Not YAML (or not readable): listed, but not read for sections.
pg.Title = otherTitle(p)
c.Pages = append(c.Pages, pg)
return nil
}
pg.Title, _ = fm["title"].(string)
pg.Draft, _ = fm["draft"].(bool)
secs, _ := fm["sections"].([]any)
pg.Sections = len(secs) > 0
secNodes := sectionNodes(node)
for i, s := range secs {
m, ok := s.(map[string]any)
if !ok {
continue
}
name, _ := m["type"].(string)
if name == "" {
continue
}
pg.Types = append(pg.Types, name)
t := get(name)
t.Uses++
if !slices.Contains(t.Pages, pg.Path) {
t.Pages = append(t.Pages, pg.Path)
}
for k, v := range m {
if k == "type" {
continue
}
f := fieldCount[name][k]
if f == nil {
f = &Field{Name: k}
fieldCount[name][k] = f
}
f.Count++
if list, ok := v.([]any); ok {
for _, it := range list {
if im, ok := it.(map[string]any); ok {
for ik := range im {
if !slices.Contains(f.Items, ik) {
f.Items = append(f.Items, ik)
}
}
}
}
}
}
if (t.Example == "" || len(m) > t.exampleSize) && i < len(secNodes) {
t.Example, t.exampleSize = example(secNodes[i]), len(m)
}
}
c.Pages = append(c.Pages, pg)
return nil
})
if err != nil {
return nil, err
}
for name := range partials {
if referenced[name] && uses[name] == nil {
c.Helpers = append(c.Helpers, name)
continue
}
get(name)
}
docs := readmeDocs(dir)
for name, t := range uses {
_, has := partials[name]
t.Missing = !has
t.Doc = docs[name]
for _, f := range fieldCount[name] {
sort.Strings(f.Items)
t.Fields = append(t.Fields, *f)
}
sort.Slice(t.Fields, func(i, j int) bool {
if t.Fields[i].Count != t.Fields[j].Count {
return t.Fields[i].Count > t.Fields[j].Count
}
return t.Fields[i].Name < t.Fields[j].Name
})
if has {
t.Layout = layoutFields(name, partials, calls, map[string]bool{})
}
c.Types = append(c.Types, *t)
}
sort.Slice(c.Types, func(i, j int) bool {
if c.Types[i].Uses != c.Types[j].Uses {
return c.Types[i].Uses > c.Types[j].Uses
}
return c.Types[i].Name < c.Types[j].Name
})
sort.Strings(c.Helpers)
sort.Slice(c.Pages, func(i, j int) bool { return c.Pages[i].Path < c.Pages[j].Path })
return c, nil
}
// layoutFields are the section fields a partial reads, and those of the
// helpers it hands the section to.
func layoutFields(name string, partials map[string]string, calls map[string][]string, seen map[string]bool) []string {
if seen[name] {
return nil
}
seen[name] = true
src := partials[name]
set := map[string]bool{}
re := bareDot
if strings.Contains(src, "$s :=") {
re = dollarS
}
for _, m := range re.FindAllStringSubmatch(stripComments(src), -1) {
set[m[1]] = true
}
for _, h := range calls[name] {
for _, f := range layoutFields(h, partials, calls, seen) {
set[f] = true
}
}
delete(set, "type")
out := make([]string, 0, len(set))
for f := range set {
out = append(out, f)
}
sort.Strings(out)
return out
}
var comments = regexp.MustCompile(`(?s)\{\{-?\s*/\*.*?\*/\s*-?\}\}`)
func stripComments(s string) string { return comments.ReplaceAllString(s, "") }
// readmeDocs reads what the README says each type takes: rows of a table
// ("| `hero` | fields |") or list items ("- `paths` — what it is").
func readmeDocs(dir string) map[string]string {
out := map[string]string{}
for _, name := range []string{"README.md", "readme.md", "README"} {
raw, err := os.ReadFile(filepath.Join(dir, name))
if err != nil {
continue
}
sc := bufio.NewScanner(bytes.NewReader(raw))
sc.Buffer(make([]byte, 64<<10), 1<<20)
for sc.Scan() {
line := sc.Text()
var m []string
if m = readmeRow.FindStringSubmatch(line); m == nil {
m = readmeList.FindStringSubmatch(line)
}
if m == nil {
continue
}
if prev := out[m[1]]; prev != "" {
out[m[1]] = prev + " " + strings.TrimSpace(m[2])
} else {
out[m[1]] = strings.TrimSpace(m[2])
}
}
break
}
return out
}
// readFrontMatter reads a page's YAML front matter, as a map and as a
// node (which keeps the fields' order, for examples). Pages with TOML or
// JSON front matter come back nil: section pages use YAML.
func readFrontMatter(path string) (map[string]any, *yaml.Node, error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, nil, err
}
raw = bytes.TrimPrefix(raw, []byte("\ufeff"))
if !bytes.HasPrefix(raw, []byte("---")) {
return nil, nil, nil
}
rest := raw[3:]
if i := bytes.IndexByte(rest, '\n'); i >= 0 {
rest = rest[i+1:]
}
end := bytes.Index(rest, []byte("\n---"))
if end < 0 {
return nil, nil, nil
}
var fm map[string]any
if err := yaml.Unmarshal(rest[:end+1], &fm); err != nil {
return nil, nil, err
}
var node yaml.Node
_ = yaml.Unmarshal(rest[:end+1], &node)
return fm, &node, nil
}
// sectionNodes are the items of the front matter's sections list.
func sectionNodes(doc *yaml.Node) []*yaml.Node {
if doc == nil || len(doc.Content) == 0 {
return nil
}
m := doc.Content[0]
if m.Kind != yaml.MappingNode {
return nil
}
for i := 0; i+1 < len(m.Content); i += 2 {
if m.Content[i].Value == "sections" && m.Content[i+1].Kind == yaml.SequenceNode {
return m.Content[i+1].Content
}
}
return nil
}
var tomlTitle = regexp.MustCompile(`(?m)^title\s*=\s*["']([^"']*)["']`)
// otherTitle reads the title of a page with TOML front matter.
func otherTitle(path string) string {
raw, err := os.ReadFile(path)
if err != nil || !bytes.HasPrefix(raw, []byte("+++")) {
return ""
}
if m := tomlTitle.FindSubmatch(raw); m != nil {
return string(m[1])
}
return ""
}
// example is one section as YAML, in its own field order.
func example(n *yaml.Node) string {
raw, err := yaml.Marshal(&yaml.Node{Kind: yaml.SequenceNode, Content: []*yaml.Node{n}})
if err != nil {
return ""
}
return strings.TrimRight(string(raw), "\n")
}