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>
This commit is contained in:
@@ -0,0 +1,380 @@
|
||||
// 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")
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package sites
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Files is a small site built from sections, for tests.
|
||||
var Files = map[string]string{
|
||||
"README.md": "# Site\n\n| Type | Fields |\n|---|---|\n| `hero` | `title`, `subhead`, `ctas` |\n\n- `faq` — questions: `items` of `q` + `a`\n",
|
||||
"layouts/partials/render-sections.html": `{{ range .Params.sections }}{{ if eq .type "hero" }}{{ partial "sections/hero.html" . }}{{ else }}{{ partial "sections/wrapper.html" . }}{{ end }}{{ end }}`,
|
||||
"layouts/partials/sections/wrapper.html": `<section>{{ partial (printf "sections/%s.html" .type) . }}</section>`,
|
||||
"layouts/partials/sections/head.html": `{{/* the heading: .ignored */}}{{ with .kicker }}<p>{{ . }}</p>{{ end }}{{ with .headline }}<h2>{{ . }}</h2>{{ end }}`,
|
||||
"layouts/partials/sections/ctas.html": `{{ range . }}<a href="{{ .url }}">{{ .label }}</a>{{ end }}`,
|
||||
"layouts/partials/sections/hero.html": `<h1>{{ .title }}</h1><p>{{ .subhead }}</p>{{ partial "sections/ctas.html" .ctas }}`,
|
||||
"layouts/partials/sections/faq.html": "{{ $s := . }}{{ partial \"sections/head.html\" $s }}{{ range $s.items }}<h3>{{ .q }}</h3>{{ .a }}{{ end }}",
|
||||
"layouts/partials/sections/stats.html": "{{ $s := . }}{{ range $s.items }}{{ .value }}{{ end }}",
|
||||
"content/_index.md": "---\ntitle: Home\nsections:\n - type: hero\n title: Hello\n subhead: There\n ctas:\n - label: Start\n url: /start/\n - type: faq\n headline: Questions\n items:\n - q: Why?\n a: Because.\n---\n",
|
||||
"content/pricing.md": "---\ntitle: Pricing\nsections:\n - type: hero\n title: Prices\n - type: widget\n size: 3\n---\n",
|
||||
"content/blog/post.md": "+++\ntitle = \"A post\"\n+++\nHello.\n",
|
||||
"content/notes.md": "---\ntitle: Notes\ndraft: true\n---\nJust text.\n",
|
||||
}
|
||||
|
||||
func write(t *testing.T, files map[string]string) string {
|
||||
dir := t.TempDir()
|
||||
for name, body := range files {
|
||||
p := filepath.Join(dir, name)
|
||||
os.MkdirAll(filepath.Dir(p), 0o755)
|
||||
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
func path(rel string) string {
|
||||
rel = strings.TrimSuffix(filepath.ToSlash(rel), ".md")
|
||||
rel = strings.Trim(strings.TrimSuffix(rel, "_index"), "/")
|
||||
if rel == "" {
|
||||
return "/"
|
||||
}
|
||||
return "/" + rel + "/"
|
||||
}
|
||||
|
||||
func TestRead(t *testing.T) {
|
||||
c, err := Read(write(t, Files), path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var names []string
|
||||
for _, ty := range c.Types {
|
||||
names = append(names, ty.Name)
|
||||
}
|
||||
// Most used first; stats has a layout but no page uses it yet; the
|
||||
// widget has no layout.
|
||||
if want := []string{"hero", "faq", "widget", "stats"}; !slices.Equal(names, want) {
|
||||
t.Errorf("types: %v, want %v", names, want)
|
||||
}
|
||||
if want := []string{"ctas", "head", "wrapper"}; !slices.Equal(c.Helpers, want) {
|
||||
t.Errorf("helpers: %v", c.Helpers)
|
||||
}
|
||||
hero := c.Type("hero")
|
||||
if hero.Uses != 2 || !slices.Equal(hero.Pages, []string{"/", "/pricing/"}) || hero.Doc != "`title`, `subhead`, `ctas`" {
|
||||
t.Errorf("hero: %+v", hero)
|
||||
}
|
||||
if hero.Fields[0].Name != "title" || hero.Fields[0].Count != 2 {
|
||||
t.Errorf("hero fields: %+v", hero.Fields)
|
||||
}
|
||||
for _, f := range hero.Fields {
|
||||
if f.Name == "ctas" && !slices.Equal(f.Items, []string{"label", "url"}) {
|
||||
t.Errorf("ctas items: %v", f.Items)
|
||||
}
|
||||
}
|
||||
// ctas is handed .ctas, not the section, so its fields aren't the hero's.
|
||||
if !slices.Equal(hero.Layout, []string{"ctas", "subhead", "title"}) {
|
||||
t.Errorf("hero layout: %v", hero.Layout)
|
||||
}
|
||||
faq := c.Type("faq")
|
||||
if faq.Doc != "questions: `items` of `q` + `a`" || !slices.Equal(faq.Layout, []string{"headline", "items", "kicker"}) {
|
||||
t.Errorf("faq: %+v", faq)
|
||||
}
|
||||
if !strings.HasPrefix(faq.Example, "- type: faq\n headline: Questions") || !strings.Contains(faq.Example, "- q: Why?") {
|
||||
t.Errorf("faq example: %s", faq.Example)
|
||||
}
|
||||
if w := c.Type("widget"); !w.Missing || c.Has("widget") || !c.Has("stats") || c.Type("stats").Uses != 0 {
|
||||
t.Errorf("widget: %+v", w)
|
||||
}
|
||||
if len(c.Pages) != 4 || c.Pages[1].Path != "/blog/post/" || c.Pages[1].Title != "A post" {
|
||||
t.Fatalf("pages: %+v", c.Pages)
|
||||
}
|
||||
home := c.Pages[0]
|
||||
if home.Path != "/" || home.Title != "Home" || !home.Sections || !slices.Equal(home.Types, []string{"hero", "faq"}) || home.File != "content/_index.md" {
|
||||
t.Errorf("home: %+v", home)
|
||||
}
|
||||
for _, p := range c.Pages {
|
||||
if p.Path == "/notes/" && (!p.Draft || p.Sections) {
|
||||
t.Errorf("notes: %+v", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadEmpty(t *testing.T) {
|
||||
c, err := Read(t.TempDir(), path)
|
||||
if err != nil || len(c.Types) != 0 || len(c.Pages) != 0 {
|
||||
t.Errorf("%+v %v", c, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user