Phase 3 part 4: changes approved one at a time, as Gitea pull requests

Proposals (at most 3 waiting) for pages on page one without clicks and
for the audit's title and description issues: the AI writes the title
(without the site's suffix, within the pixel budget) and description
from the live page and its searches. A yes syncs a working copy of the
site's Gitea repository (token as a header only), finds the page's Hugo
content file, sets title and description in its front matter, builds
with Hugo to check the page comes out as proposed, pushes a branch and
opens a pull request; it never merges. Merged changes are checked on
the live site, then compared before and after from Search Console.
Hugo is in the image. Schema 15.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 08:04:01 -07:00
co-authored by Claude Opus 5.5
parent 43a7b42126
commit 438192faba
26 changed files with 2267 additions and 11 deletions
+46
View File
@@ -0,0 +1,46 @@
// Package hugotest makes a small Hugo site in a Git repository, for tests.
package hugotest
import (
"os"
"os/exec"
"path/filepath"
"testing"
)
// Site makes a small Hugo site in a bare repository and returns its
// clone URL. Its titles are "Page title · Site".
func Site(t testing.TB) string {
t.Helper()
dir := t.TempDir()
src := filepath.Join(dir, "src")
files := map[string]string{
"hugo.toml": "baseURL = 'https://site.example/'\ntitle = 'Site'\ndisableKinds = ['taxonomy', 'term', 'RSS', 'sitemap']\n",
"layouts/_default/baseof.html": `<!doctype html><html><head><title>{{ if .IsHome }}{{ site.Title }}{{ else }}{{ .Title }} · {{ site.Title }}{{ end }}</title><meta name="description" content="{{ .Description }}"></head><body>{{ block "main" . }}{{ end }}</body></html>`,
"layouts/_default/single.html": `{{ define "main" }}<h1>{{ .Title }}</h1>{{ .Content }}{{ end }}`,
"layouts/_default/list.html": `{{ define "main" }}<h1>{{ .Title }}</h1>{{ .Content }}{{ end }}`,
"content/_index.md": "---\ntitle: Home\n---\nWelcome.\n",
"content/pricing.md": "---\ntitle: Pricing\ndescription: |\n Old description\n on two lines\ndraft: false\n---\nOur prices.\n",
"content/blog/first-post/index.md": "+++\ntitle = \"First post\"\n+++\nHello.\n",
"content/about.md": "---\ntitle: About us\nurl: /company/\n---\nWho we are.\n",
}
for name, body := range files {
p := filepath.Join(src, name)
os.MkdirAll(filepath.Dir(p), 0o755)
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
bare := filepath.Join(dir, "site.git")
for _, args := range [][]string{
{"init", "-q", "-b", "main", src},
{"-C", src, "add", "."},
{"-C", src, "-c", "user.name=T", "-c", "user.email=t@example.com", "commit", "-qm", "init"},
{"clone", "-q", "--bare", src, bare},
} {
if out, err := exec.Command("git", args...).CombinedOutput(); err != nil {
t.Fatalf("git %v: %s", args, out)
}
}
return "file://" + bare
}
+384
View File
@@ -0,0 +1,384 @@
// Package hugorepo works on a Hugo website's Git repository: a working
// copy kept under the data folder, finding the content file behind a page,
// editing its front matter, building the site to check a change, and
// pushing a branch. It never pushes to the branch that gets published.
package hugorepo
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"golang.org/x/net/html"
)
// Repo is a working copy.
type Repo struct {
Dir string // the working copy
CloneURL string // https://…/owner/name.git
Token string // sent as a header, never stored in the copy
Branch string // the branch that gets published
Author string // "Name <email>" for commits
}
// git runs a git command in the working copy, with the token as an HTTP
// header so it never lands in .git/config.
func (r *Repo) git(ctx context.Context, args ...string) (string, error) {
full := []string{"-c", "http.extraHeader=Authorization: token " + r.Token, "-c", "credential.helper="}
if name, email, ok := splitAuthor(r.Author); ok {
full = append(full, "-c", "user.name="+name, "-c", "user.email="+email)
}
full = append(full, args...)
cmd := exec.CommandContext(ctx, "git", full...)
cmd.Dir = r.Dir
cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0", "GIT_ASKPASS=true")
out, err := cmd.CombinedOutput()
if err != nil {
msg := strings.TrimSpace(strings.ReplaceAll(string(out), r.Token, "***"))
return msg, fmt.Errorf("git %s: %s", args[0], firstLine(msg))
}
return string(out), nil
}
func firstLine(s string) string {
for _, l := range strings.Split(s, "\n") {
if l = strings.TrimSpace(l); l != "" && !strings.HasPrefix(l, "hint:") {
return l
}
}
return s
}
func splitAuthor(a string) (name, email string, ok bool) {
i, j := strings.Index(a, "<"), strings.Index(a, ">")
if i < 0 || j < i {
return "", "", false
}
return strings.TrimSpace(a[:i]), a[i+1 : j], true
}
// Sync makes the working copy a clean copy of the published branch: a
// clone the first time, a fetch and hard reset after that.
func (r *Repo) Sync(ctx context.Context) error {
if _, err := os.Stat(filepath.Join(r.Dir, ".git")); errors.Is(err, fs.ErrNotExist) {
if err := os.MkdirAll(filepath.Dir(r.Dir), 0o755); err != nil {
return err
}
parent := &Repo{Dir: filepath.Dir(r.Dir), Token: r.Token}
if _, err := parent.git(ctx, "clone", "--quiet", "--branch", r.Branch, r.CloneURL, filepath.Base(r.Dir)); err != nil {
return err
}
_, err := r.git(ctx, "submodule", "update", "--init", "--recursive", "--quiet")
return err
}
for _, args := range [][]string{
{"fetch", "--quiet", "--prune", "origin"},
{"checkout", "--quiet", "--force", r.Branch},
{"reset", "--quiet", "--hard", "origin/" + r.Branch},
{"clean", "-fdq"},
{"submodule", "update", "--init", "--recursive", "--quiet"},
} {
if _, err := r.git(ctx, args...); err != nil {
return err
}
}
return nil
}
// Branch starts a new branch from the published one.
func (r *Repo) NewBranch(ctx context.Context, name string) error {
_, err := r.git(ctx, "checkout", "--quiet", "-B", name, "origin/"+r.Branch)
return err
}
// Diff is the working copy's uncommitted change.
func (r *Repo) Diff(ctx context.Context) (string, error) {
return r.git(ctx, "diff")
}
// CommitAndPush commits everything changed and pushes the current branch.
func (r *Repo) CommitAndPush(ctx context.Context, branch, message string) error {
if _, err := r.git(ctx, "commit", "--quiet", "-am", message); err != nil {
return err
}
_, err := r.git(ctx, "push", "--quiet", "--force", "origin", "HEAD:refs/heads/"+branch)
return err
}
// --- Finding a page's file ---
var contentExts = map[string]bool{".md": true, ".markdown": true, ".html": true, ".htm": true}
// FindContent returns the content file (relative to the repository) that
// makes a page, from its path ("/blog/post/"). It understands index.md and
// _index.md, and url and slug in front matter.
func (r *Repo) FindContent(pagePath string) (string, error) {
want := cleanPath(pagePath)
root := filepath.Join(r.Dir, "content")
var found []string
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !contentExts[strings.ToLower(filepath.Ext(p))] {
return err
}
rel, _ := filepath.Rel(root, p)
for _, u := range urlsFor(rel, p) {
if u == want {
found = append(found, filepath.ToSlash(filepath.Join("content", rel)))
break
}
}
return nil
})
if err != nil {
return "", fmt.Errorf("reading the content folder: %w", err)
}
switch len(found) {
case 0:
return "", fmt.Errorf("no content file makes %s", want)
case 1:
return found[0], nil
}
return "", fmt.Errorf("several content files could make %s: %s", want, strings.Join(found, ", "))
}
func cleanPath(p string) string {
p = "/" + strings.Trim(strings.ToLower(p), "/") + "/"
if p == "//" {
return "/"
}
return p
}
// urlsFor are the paths a content file may be published at: from where it
// sits (with and without a leading language folder), and from its front
// matter's url or slug.
func urlsFor(rel, full string) []string {
rel = filepath.ToSlash(rel)
dir, file := filepath.Split(rel)
base := strings.TrimSuffix(file, filepath.Ext(file))
var p string
if base == "index" || base == "_index" {
p = dir
} else {
p = dir + base
}
out := []string{cleanPath(urlize(p))}
if parts := strings.SplitN(strings.Trim(p, "/"), "/", 2); len(parts[0]) == 2 {
rest := ""
if len(parts) == 2 {
rest = parts[1]
}
out = append(out, cleanPath(urlize(rest)))
}
fm := frontMatter(full)
if u := fm["url"]; u != "" {
out = append(out, cleanPath(u))
}
if s := fm["slug"]; s != "" && base != "_index" {
out = append(out, cleanPath(urlize(dir+s)))
}
return out
}
var spaces = regexp.MustCompile(`\s+`)
// urlize does what Hugo does to a path: lower case, spaces to hyphens.
func urlize(p string) string { return spaces.ReplaceAllString(strings.ToLower(p), "-") }
// frontMatter reads a file's simple front matter keys (title, url, slug,
// description), YAML or TOML.
func frontMatter(path string) map[string]string {
out := map[string]string{}
f, err := os.Open(path)
if err != nil {
return out
}
defer f.Close()
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 64<<10), 1<<20)
if !sc.Scan() {
return out
}
delim := strings.TrimSpace(sc.Text())
if delim != "---" && delim != "+++" {
return out
}
sep := ":"
if delim == "+++" {
sep = "="
}
for sc.Scan() {
line := sc.Text()
if strings.TrimSpace(line) == delim {
break
}
if strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") {
continue
}
k, v, ok := strings.Cut(line, sep)
if !ok {
continue
}
out[strings.ToLower(strings.TrimSpace(k))] = unquote(strings.TrimSpace(v))
}
return out
}
func unquote(v string) string {
if len(v) >= 2 && (v[0] == '"' && v[len(v)-1] == '"') {
if s, err := strconv.Unquote(v); err == nil {
return s
}
}
if len(v) >= 2 && v[0] == '\'' && v[len(v)-1] == '\'' {
return strings.ReplaceAll(v[1:len(v)-1], "''", "'")
}
return v
}
// FrontMatterValue reads one front matter key of a content file.
func (r *Repo) FrontMatterValue(rel, key string) string {
return frontMatter(filepath.Join(r.Dir, rel))[strings.ToLower(key)]
}
// SetFrontMatter sets a top-level front matter key, YAML or TOML, adding
// it if it isn't there.
func (r *Repo) SetFrontMatter(rel, key, value string) error {
path := filepath.Join(r.Dir, rel)
raw, err := os.ReadFile(path)
if err != nil {
return err
}
lines := strings.Split(string(raw), "\n")
if len(lines) == 0 {
return errors.New(rel + " is empty")
}
delim := strings.TrimSpace(lines[0])
var line string
switch delim {
case "---":
line = key + ": " + strconv.Quote(value)
case "+++":
line = key + " = " + strconv.Quote(value)
default:
return fmt.Errorf("%s has no YAML or TOML front matter", rel)
}
sep := map[string]string{"---": ":", "+++": "="}[delim]
end := -1
for i := 1; i < len(lines); i++ {
if strings.TrimSpace(lines[i]) == delim {
end = i
break
}
}
if end < 0 {
return fmt.Errorf("%s's front matter doesn't end", rel)
}
done := false
for i := 1; i < end; i++ {
k, _, ok := strings.Cut(lines[i], sep)
if ok && !strings.HasPrefix(lines[i], " ") && strings.EqualFold(strings.TrimSpace(k), key) {
lines[i] = line
// A YAML block value (key: | or >) continues on indented lines.
for i+1 < end && (strings.HasPrefix(lines[i+1], " ") || strings.HasPrefix(lines[i+1], "\t")) {
lines = append(lines[:i+1], lines[i+2:]...)
end--
}
done = true
break
}
}
if !done {
lines = append(lines[:end], append([]string{line}, lines[end:]...)...)
}
return os.WriteFile(path, []byte(strings.Join(lines, "\n")), 0o644)
}
// --- Building ---
// HugoVersion is the Hugo in the image, or "" if there's none.
func HugoVersion(ctx context.Context) string {
out, err := exec.CommandContext(ctx, "hugo", "version").Output()
if err != nil {
return ""
}
return strings.TrimSpace(string(out))
}
// Build builds the site into a temporary folder, returned for reading;
// the caller removes it.
func (r *Repo) Build(ctx context.Context) (string, error) {
out, err := os.MkdirTemp("", "supermarket-hugo-")
if err != nil {
return "", err
}
ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
cmd := exec.CommandContext(ctx, "hugo", "--quiet", "--destination", out, "--cleanDestinationDir")
cmd.Dir = r.Dir
var buf bytes.Buffer
cmd.Stdout, cmd.Stderr = &buf, &buf
if err := cmd.Run(); err != nil {
os.RemoveAll(out)
return "", fmt.Errorf("hugo couldn't build the site: %s", firstLine(buf.String()))
}
return out, nil
}
// BuiltHead reads the title and meta description a built page has.
func BuiltHead(outDir, pagePath string) (title, description string, err error) {
p := strings.Trim(pagePath, "/")
candidates := []string{filepath.Join(outDir, p, "index.html"), filepath.Join(outDir, p+".html")}
var raw []byte
for _, c := range candidates {
if raw, err = os.ReadFile(c); err == nil {
break
}
}
if err != nil {
return "", "", fmt.Errorf("the build has no page at %s", pagePath)
}
doc, err := html.Parse(bytes.NewReader(raw))
if err != nil {
return "", "", err
}
var walk func(*html.Node)
walk = func(n *html.Node) {
if n.Type == html.ElementNode {
switch n.Data {
case "title":
if title == "" && n.FirstChild != nil {
title = strings.Join(strings.Fields(n.FirstChild.Data), " ")
}
case "meta":
var name, content string
for _, a := range n.Attr {
switch strings.ToLower(a.Key) {
case "name":
name = strings.ToLower(a.Val)
case "content":
content = a.Val
}
}
if name == "description" && description == "" {
description = strings.Join(strings.Fields(content), " ")
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
}
walk(doc)
return title, description, nil
}
+92
View File
@@ -0,0 +1,92 @@
package hugorepo
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"supermarket/internal/hugorepo/hugotest"
)
func TestRepo(t *testing.T) {
ctx := context.Background()
clone := hugotest.Site(t)
r := &Repo{Dir: filepath.Join(t.TempDir(), "sites", "o__site"), CloneURL: clone, Token: "secret-token", Branch: "main", Author: "Pat <pat@example.com>"}
if err := r.Sync(ctx); err != nil {
t.Fatal(err)
}
if err := r.Sync(ctx); err != nil { // a second time fetches
t.Fatal(err)
}
for page, want := range map[string]string{
"/": "content/_index.md", "/pricing/": "content/pricing.md", "/blog/first-post/": "content/blog/first-post/index.md",
"/company/": "content/about.md",
} {
if got, err := r.FindContent(page); err != nil || got != want {
t.Errorf("%s: %q %v", page, got, err)
}
}
if _, err := r.FindContent("/nope/"); err == nil {
t.Error("found a file for a page that doesn't exist")
}
if err := r.NewBranch(ctx, "supermarket/seo-1"); err != nil {
t.Fatal(err)
}
if err := r.SetFrontMatter("content/pricing.md", "title", `Pricing: "plans" from $5`); err != nil {
t.Fatal(err)
}
if err := r.SetFrontMatter("content/pricing.md", "description", "New description"); err != nil {
t.Fatal(err)
}
if err := r.SetFrontMatter("content/blog/first-post/index.md", "description", "A post"); err != nil {
t.Fatal(err)
}
raw, _ := os.ReadFile(filepath.Join(r.Dir, "content/pricing.md"))
if string(raw) != "---\ntitle: \"Pricing: \\\"plans\\\" from $5\"\ndescription: \"New description\"\ndraft: false\n---\nOur prices.\n" {
t.Errorf("pricing.md:\n%s", raw)
}
raw, _ = os.ReadFile(filepath.Join(r.Dir, "content/blog/first-post/index.md"))
if !strings.Contains(string(raw), "description = \"A post\"\n+++") {
t.Errorf("toml:\n%s", raw)
}
if v := r.FrontMatterValue("content/pricing.md", "title"); v != `Pricing: "plans" from $5` {
t.Errorf("read back: %q", v)
}
if HugoVersion(ctx) == "" {
t.Skip("no hugo")
}
out, err := r.Build(ctx)
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(out)
title, desc, err := BuiltHead(out, "/pricing/")
if err != nil || title != `Pricing: "plans" from $5 · Site` || desc != "New description" {
t.Errorf("built: %q %q %v", title, desc, err)
}
diff, _ := r.Diff(ctx)
if !strings.Contains(diff, "+title:") {
t.Errorf("diff: %s", diff)
}
if err := r.CommitAndPush(ctx, "supermarket/seo-1", "SEO: test"); err != nil {
t.Fatal(err)
}
if out, err := exec.Command("git", "-C", strings.TrimPrefix(clone, "file://"), "log", "--format=%an <%ae>|%s", "supermarket/seo-1", "-1").CombinedOutput(); err != nil ||
strings.TrimSpace(string(out)) != "Pat <pat@example.com>|SEO: test" {
t.Errorf("pushed: %s %v", out, err)
}
cfg, _ := os.ReadFile(filepath.Join(r.Dir, ".git", "config"))
if strings.Contains(string(cfg), "secret-token") {
t.Error("the token is stored in the working copy")
}
// Sync goes back to a clean main.
if err := r.Sync(ctx); err != nil {
t.Fatal(err)
}
if v := r.FrontMatterValue("content/pricing.md", "title"); v != "Pricing" {
t.Errorf("after sync: %q", v)
}
}