Files
davidandClaude Opus 5.5 7da7c5fd9c Phase 6 part 5, step 3: theme updates by pull request
The theme carries a MANIFEST of its files' SHA-256s. A site's Theme card
shows its copy's version against Supermarket's and any files changed by
hand; Update the theme opens a pull request that writes new and changed
files, removes retired ones, rebuilds, and lists what it replaces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:30:48 -07:00

209 lines
9.6 KiB
Go

package web
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os/exec"
"path/filepath"
"strings"
"testing"
"supermarket/internal/ai"
"supermarket/internal/hugorepo"
"supermarket/internal/hugorepo/hugotest"
"supermarket/internal/profile"
"supermarket/internal/secrets"
"supermarket/internal/sites"
"supermarket/internal/theme"
)
func TestNewSite(t *testing.T) {
if hugorepo.HugoVersion(context.Background()) == "" {
t.Skip("no hugo")
}
bare := filepath.Join(t.TempDir(), "acme.git")
if out, err := exec.Command("git", "init", "--quiet", "--bare", "--initial-branch", "main", bare).CombinedOutput(); err != nil {
t.Fatalf("%s", out)
}
clone := "file://" + bare
empty := true
var opened []map[string]string
g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/v1/repos/Us/acme":
fmt.Fprintf(w, `{"full_name":"Us/acme","default_branch":"main","clone_url":%q,"empty":%v,"permissions":{"push":true}}`, clone, empty)
case r.URL.Path == "/api/v1/repos/Us/acme/pulls" && r.Method == http.MethodPost:
var body map[string]string
json.NewDecoder(r.Body).Decode(&body)
opened = append(opened, body)
fmt.Fprint(w, `{"number":1,"state":"open","html_url":"https://gitea.example/pulls/1"}`)
default:
http.NotFound(w, r)
}
}))
defer g.Close()
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://old.example"}}})
postForm(h, "/settings/search", url.Values{"gitea_url": {g.URL}, secrets.GiteaToken: {"tok"}})
if body := do(h, http.MethodGet, "/sites/new", nil, nil).Body.String(); !strings.Contains(body, g.URL+"/repo/create") || !strings.Contains(body, `value="#e0ff4f"`) {
t.Errorf("form: %s", body)
}
form := url.Values{"repo": {"Us/acme"}, "url": {"https://www.acme.example"}, "title": {"Acme Widgets"}, "tagline": {"Widgets for everyone"},
"email": {"hello@acme.example"}, "dark": {"#1d1238"}, "primary": {"#ffb703"}, "accent": {"#e4572e"}, "font": {"Manrope"}}
for field, bad := range map[string]string{"url": "http://acme.example", "dark": "purple", "repo": "nope", "title": " "} {
v := url.Values{}
for k, vs := range form {
v[k] = vs
}
v.Set(field, bad)
if rec := postForm(h, "/sites/new", v); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `role="alert"`) {
t.Errorf("bad %s accepted: %d", field, rec.Code)
}
}
empty = false
if body := postForm(h, "/sites/new", form).Body.String(); !strings.Contains(body, "isn&#39;t empty") {
t.Errorf("non-empty repository: %s", body)
}
empty = true
rec := postForm(h, "/sites/new", form)
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/sites?site=1&msg=site-created" {
t.Fatalf("create: %d %s", rec.Code, rec.Body.String())
}
show := func(ref, path string) string {
out, err := exec.Command("git", "--git-dir", bare, "show", ref+":"+path).CombinedOutput()
if err != nil {
t.Fatalf("%s %s: %s", ref, path, out)
}
return string(out)
}
cfg := show("main", "hugo.toml")
for _, want := range []string{`baseURL = "https://www.acme.example/"`, `title = "Acme Widgets"`, `theme = "supermarket"`, `primary = "#ffb703"`, `font = "Manrope"`, `email = "hello@acme.example"`} {
if !strings.Contains(cfg, want) {
t.Errorf("hugo.toml lacks %s:\n%s", want, cfg)
}
}
if v := show("main", "themes/supermarket/VERSION"); v != "1\n" || !strings.Contains(show("main", "content/_index.md"), "Widgets for everyone") {
t.Errorf("theme or home: %q", v)
}
p, _ := profile.Load(s.DB)
if len(p.Websites) != 2 || p.Websites[1].URL != "https://www.acme.example" || p.Websites[1].Repo != "Us/acme" || p.Websites[1].Branch != "main" {
t.Errorf("profile: %+v", p.Websites)
}
body := do(h, http.MethodGet, "/sites?site=1&msg=site-created", nil, nil).Body.String()
for _, want := range []string{"The site is started", "First pages", "version 1", ">Home page<", ">About page<", ">Contact page<", "<summary>form", "<summary>hero"} {
if !strings.Contains(body, want) {
t.Errorf("site page lacks %q", want)
}
}
// The same address again is refused.
if body := postForm(h, "/sites/new", form).Body.String(); !strings.Contains(body, "already one of your websites") {
t.Errorf("again: %s", body)
}
// A contact page from the theme's sections joins the top menu.
composed, _ := json.Marshal(map[string]any{"path": "/contact/", "title": "Contact", "description": "Write to us.",
"sections_yaml": "- type: hero\n title: Talk to us\n compact: true\n- type: form\n headline: Write to us\n subject: Contact\n fields:\n - { name: name, label: Name, required: true }\n - { name: email, label: Email, type: email, required: true }\n",
"needs": []string{}})
newAIClient = func(ai.Config, *secrets.Store) (ai.Client, error) { return cannedAI{string(composed)}, nil }
defer func() { newAIClient = ai.New }()
if rec := postForm(h, "/sites/pages", url.Values{"site": {"1"}, "kind": {"contact"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("contact: %d %s", rec.Code, rec.Body.String())
}
pg, _ := sites.GetPage(s.DB, 1)
if pg.Error != "" || len(pg.Warnings) != 0 {
t.Errorf("contact page: %q %v", pg.Error, pg.Warnings)
}
postForm(h, "/sites/pages/1/pr", url.Values{"title": {pg.Title}, "description": {pg.Description}, "path": {pg.Path}, "sections": {pg.Sections}})
if len(opened) != 1 {
t.Fatalf("no pull request: %v", opened)
}
if fm := show("supermarket/site-page-1", "content/contact.md"); !strings.Contains(fm, "menus:\n main:\n weight: 90\n") {
t.Errorf("contact file:\n%s", fm)
}
if !strings.Contains(opened[0]["body"], "the page is at /contact/") {
t.Errorf("build check: %s", opened[0]["body"])
}
}
func TestThemeUpdate(t *testing.T) {
if hugorepo.HugoVersion(context.Background()) == "" {
t.Skip("no hugo")
}
// A site with an older copy of the theme: version 0, a file the theme
// no longer has, and the header changed by hand.
files := map[string]string{"hugo.toml": "baseURL = 'https://acme.example/'\ntitle = 'Acme'\ntheme = 'supermarket'\ndisableKinds = ['taxonomy', 'term', 'RSS', 'sitemap']\n",
"content/_index.md": "---\ntitle: Home\nsections:\n - type: hero\n title: Hi\n---\n"}
old := theme.Files()
old["VERSION"] = "0\n"
old["layouts/partials/retired.html"] = "<p>old</p>"
delete(old, "layouts/404.html")
old["MANIFEST"] = theme.Manifest(old)
old["layouts/partials/header.html"] += "<!-- changed by hand -->"
for p, b := range old {
files[theme.Dir+"/"+p] = b
}
clone := hugotest.Site(t, files)
var opened []map[string]string
g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/v1/repos/Us/acme":
fmt.Fprintf(w, `{"full_name":"Us/acme","default_branch":"main","clone_url":%q,"permissions":{"push":true}}`, clone)
case r.URL.Path == "/api/v1/repos/Us/acme/pulls" && r.Method == http.MethodPost:
var body map[string]string
json.NewDecoder(r.Body).Decode(&body)
opened = append(opened, body)
fmt.Fprint(w, `{"number":4,"state":"open","html_url":"https://gitea.example/pulls/4"}`)
default:
http.NotFound(w, r)
}
}))
defer g.Close()
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Acme", Websites: []profile.Website{{URL: "https://acme.example", Repo: "Us/acme"}}})
postForm(h, "/settings/search", url.Values{"gitea_url": {g.URL}, secrets.GiteaToken: {"tok"}})
postForm(h, "/sites/sync", url.Values{"site": {"0"}})
body := do(h, http.MethodGet, "/sites", nil, nil).Body.String()
if !strings.Contains(body, "theme version 0; Supermarket has version 1") || !strings.Contains(body, "Changed by hand in the site's copy of the theme: layouts/partials/header.html.") {
t.Errorf("before: %s", body)
}
if rec := postForm(h, "/sites/theme/update", url.Values{"site": {"0"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("update: %d %s", rec.Code, rec.Body.String())
}
if len(opened) != 1 {
t.Fatalf("pull requests: %v", opened)
}
pr := opened[0]
for _, want := range []string{"from version 0 to 1", "**Changed:**\n- `layouts/partials/header.html`", "**Added:**\n- `layouts/404.html`",
"**Removed:**\n- `layouts/partials/retired.html`", "replaced by this update", "Checked with a build"} {
if !strings.Contains(pr["body"], want) {
t.Errorf("pull request lacks %q:\n%s", want, pr["body"])
}
}
if pr["head"] != "supermarket/theme-1" || pr["title"] != "Sites: update the theme to version 1" {
t.Errorf("pull request: %v", pr)
}
bare := strings.TrimPrefix(clone, "file://")
if out, _ := exec.Command("git", "--git-dir", bare, "show", "supermarket/theme-1:"+theme.Dir+"/VERSION").CombinedOutput(); string(out) != "1\n" {
t.Errorf("VERSION on the branch: %q", out)
}
if out, err := exec.Command("git", "--git-dir", bare, "show", "supermarket/theme-1:"+theme.Dir+"/layouts/partials/retired.html").CombinedOutput(); err == nil {
t.Errorf("the retired file is still there: %s", out)
}
// Once merged, the site is up to date; updating again is refused.
exec.Command("git", "--git-dir", bare, "update-ref", "refs/heads/main", "refs/heads/supermarket/theme-1").Run()
postForm(h, "/sites/sync", url.Values{"site": {"0"}})
body = do(h, http.MethodGet, "/sites", nil, nil).Body.String()
if !strings.Contains(body, "version 1: the latest") || strings.Contains(body, "Changed by hand") || !strings.Contains(body, "https://gitea.example/pulls/4") {
t.Errorf("after: %s", body)
}
if body := postForm(h, "/sites/theme/update", url.Values{"site": {"0"}}).Body.String(); !strings.Contains(body, "already has the theme&#39;s version 1") {
t.Errorf("again: %s", body)
}
}