From 7da7c5fd9ca156b1686a18030757b512f38938e5 Mon Sep 17 00:00:00 2001 From: David Young Date: Sun, 22 Nov 2026 15:30:48 -0700 Subject: [PATCH] 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 --- PLAN.md | 15 +++ TEST.md | 7 ++ internal/sites/themeupdate.go | 181 ++++++++++++++++++++++++++++++ internal/theme/theme.go | 46 +++++++- internal/theme/theme_test.go | 4 + internal/web/newsite_test.go | 79 +++++++++++++ internal/web/server.go | 1 + internal/web/sites.go | 42 ++++++- internal/web/templates/sites.html | 15 ++- 9 files changed, 384 insertions(+), 6 deletions(-) create mode 100644 internal/sites/themeupdate.go diff --git a/PLAN.md b/PLAN.md index 4f8a747..891f5ec 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1439,6 +1439,21 @@ shared theme for new sites (deferred in Phase 5). the form). Commits are by the Core's user "via Supermarket" (`commitAuthor`). Deploying the new site is still the user's Gitea hook. + **Step 3 built (2026-11-22; no schema change).** The theme carries a + `MANIFEST` (each file's SHA-256) beside its `VERSION`, so a site's copy + can be checked for files changed by hand. Sites → Sections and pages + shows a *Theme* card on sites using it: their version against + Supermarket's, the files changed by hand, and *Update the theme* when + Supermarket's is newer. The update (`supermarket/theme-`) writes the + new and changed files, removes the ones the theme no longer has, + rebuilds, and opens a pull request listing what changed, was added and + removed, and which hand-edited files it replaces (changes belong in the + site's own `layouts/` or `static/`, which win over the theme). To ship a + theme change: edit `internal/theme/files/`, raise `theme.Version`. + +**Part 5 is complete**, and with it Phase 6's plan. Not tried for real: a +new site on the real Gitea (the user creates the empty repository). + **Part 1 built (2026-11-22; no schema change).** `internal/backup` makes backups with `VACUUM INTO` (to a `.part` file, then renamed; mode 0600) into `/backups`, named `app---[-].db` diff --git a/TEST.md b/TEST.md index 44287fe..aecf733 100644 --- a/TEST.md +++ b/TEST.md @@ -681,6 +681,13 @@ Throughout, also notice: the Lead Capture address (the theme's form is ready). - [ ] After adding your Gitea deploy hook and merging, the site is live at its address, and Publishing confirms each page. +- [ ] A site made with the theme shows a *Theme* card: "version 1: the + latest". After a Supermarket update with a newer theme, it offers + *Update the theme*; the pull request lists the changed, added and + removed files and builds. +- [ ] Edit a file under `themes/supermarket/` by hand and read the site + again: the Theme card names it as changed by hand, and the update's + pull request says it will be replaced. ## 9. Search diff --git a/internal/sites/themeupdate.go b/internal/sites/themeupdate.go new file mode 100644 index 0000000..b4c1e34 --- /dev/null +++ b/internal/sites/themeupdate.go @@ -0,0 +1,181 @@ +package sites + +import ( + "context" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + + "supermarket/internal/api/gitea" + "supermarket/internal/hugorepo" + "supermarket/internal/seo" + "supermarket/internal/theme" +) + +// ThemeState is a site's copy of Supermarket's theme. +type ThemeState struct { + Has bool + Version int // the copy's; 0 when its VERSION can't be read + Latest int // Supermarket's + Edited []string // files changed by hand since the copy was made +} + +// Outdated says whether Supermarket has a newer theme than the copy. +func (t ThemeState) Outdated() bool { return t.Has && t.Version < t.Latest } + +// themeFiles reads a site's copy of the theme: path (inside the theme) → +// content. +func themeFiles(siteDir string) (map[string][]byte, error) { + root := filepath.Join(siteDir, theme.Dir) + out := map[string][]byte{} + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + raw, err := os.ReadFile(p) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, p) + out[filepath.ToSlash(rel)] = raw + return nil + }) + return out, err +} + +// ReadTheme reads a site's copy of the theme from its working copy. +func ReadTheme(siteDir string) ThemeState { + st := ThemeState{Latest: theme.Version} + files, err := themeFiles(siteDir) + if err != nil || len(files) == 0 { + return st + } + st.Has = true + st.Version, _ = strconv.Atoi(strings.TrimSpace(string(files["VERSION"]))) + st.Edited = edited(files) + return st +} + +// edited lists the files in a copy that don't match its manifest: changed +// or added by hand (a copy without a manifest can't be checked). +func edited(files map[string][]byte) []string { + man, ok := files["MANIFEST"] + if !ok { + return nil + } + sums := theme.ParseManifest(string(man)) + var out []string + for p, raw := range files { + if p == "VERSION" || p == "MANIFEST" { + continue + } + if sums[p] != theme.Sum(raw) { + out = append(out, p) + } + } + sort.Strings(out) + return out +} + +// ThemeDiff is what an update changes in the copy. +type ThemeDiff struct { + From, To int + Added, Changed, Removed []string + Overwritten []string // edited by hand, and replaced +} + +// UpdateTheme opens a pull request that replaces the site's copy of the +// theme with Supermarket's: files added, changed and removed, checked with +// a build. Files changed by hand are listed, since the update overwrites +// them (the site's own layouts/ is the place for changes: it wins over the +// theme). +func UpdateTheme(ctx context.Context, ap *seo.Applier) (*gitea.Pull, *ThemeDiff, error) { + wc, full, published, err := ap.WorkingCopy(ctx) + if err != nil { + return nil, nil, err + } + defer wc.Release() + old, err := themeFiles(wc.Dir) + if err != nil || len(old) == 0 { + return nil, nil, errors.New("this site doesn't use Supermarket's theme (there's no " + theme.Dir + ")") + } + d := &ThemeDiff{To: theme.Version, Overwritten: edited(old)} + d.From, _ = strconv.Atoi(strings.TrimSpace(string(old["VERSION"]))) + if d.From >= d.To { + return nil, nil, fmt.Errorf("the site already has the theme's version %d", d.From) + } + branch := fmt.Sprintf("supermarket/theme-%d", theme.Version) + if err := wc.NewBranch(ctx, branch); err != nil { + return nil, nil, err + } + latest := theme.Files() + for p, body := range latest { + prev, had := old[p] + switch { + case !had: + d.Added = append(d.Added, p) + case string(prev) != body: + if p != "VERSION" && p != "MANIFEST" { + d.Changed = append(d.Changed, p) + } + default: + continue + } + if err := wc.WriteFile(theme.Dir+"/"+p, body); err != nil { + return nil, nil, err + } + } + for p := range old { + if _, keep := latest[p]; !keep { + d.Removed = append(d.Removed, p) + if err := wc.RemoveFile(theme.Dir + "/" + p); err != nil { + return nil, nil, err + } + } + } + sort.Strings(d.Added) + sort.Strings(d.Changed) + sort.Strings(d.Removed) + note := "Not checked with a build: there's no Hugo in Supermarket's image." + if hugorepo.HugoVersion(ctx) != "" { + out, err := wc.Build(ctx) + if err != nil { + return nil, nil, fmt.Errorf("with the new theme, %w", err) + } + os.RemoveAll(out) + note = "Checked with a build: the site builds with the new theme." + } + subject := fmt.Sprintf("Sites: update the theme to version %d", theme.Version) + if err := wc.CommitAndPush(ctx, branch, subject); err != nil { + return nil, nil, err + } + var b strings.Builder + fmt.Fprintf(&b, "Updates the site's copy of Supermarket's theme (`%s`) from version %d to %d.\n\n", theme.Dir, d.From, d.To) + list := func(title string, ps []string) { + if len(ps) == 0 { + return + } + fmt.Fprintf(&b, "**%s:**\n", title) + for _, p := range ps { + fmt.Fprintf(&b, "- `%s`\n", p) + } + b.WriteString("\n") + } + list("Changed", d.Changed) + list("Added", d.Added) + list("Removed", d.Removed) + if len(d.Overwritten) > 0 { + list("Changed by hand in the site's copy, and replaced by this update (move such changes to the site's own layouts/ or static/, which win over the theme)", d.Overwritten) + } + b.WriteString(note + "\n\nPreview it in Supermarket (Sites → Previews) before merging: merging publishes it.") + pull, err := ap.Gitea.OpenPull(ctx, full, branch, published, subject, b.String()) + if err != nil { + return nil, nil, err + } + return pull, d, nil +} diff --git a/internal/theme/theme.go b/internal/theme/theme.go index 6005b11..961c8ed 100644 --- a/internal/theme/theme.go +++ b/internal/theme/theme.go @@ -4,7 +4,9 @@ package theme import ( + "crypto/sha256" "embed" + "fmt" "io/fs" "sort" "strconv" @@ -26,8 +28,50 @@ const Name = "supermarket" var files embed.FS // Files are the theme's files: path (inside the theme) → content, -// VERSION included. +// VERSION and MANIFEST included. func Files() map[string]string { + out := files0() + out["MANIFEST"] = Manifest(out) + return out +} + +// Manifest lists each file's SHA-256 (VERSION and MANIFEST aside), so a +// site's copy can be checked for files changed by hand. +func Manifest(files map[string]string) string { + var b strings.Builder + for _, p := range sortedKeys(files) { + if p == "VERSION" || p == "MANIFEST" { + continue + } + fmt.Fprintf(&b, "%x %s\n", sha256.Sum256([]byte(files[p])), p) + } + return b.String() +} + +// ParseManifest reads a MANIFEST: path → SHA-256 (hex). +func ParseManifest(m string) map[string]string { + out := map[string]string{} + for _, l := range strings.Split(m, "\n") { + if sum, p, ok := strings.Cut(l, " "); ok && p != "" { + out[p] = sum + } + } + return out +} + +// Sum is a file's SHA-256, as in the manifest. +func Sum(content []byte) string { return fmt.Sprintf("%x", sha256.Sum256(content)) } + +func sortedKeys(m map[string]string) []string { + var ks []string + for k := range m { + ks = append(ks, k) + } + sort.Strings(ks) + return ks +} + +func files0() map[string]string { out := map[string]string{"VERSION": strconv.Itoa(Version) + "\n"} _ = fs.WalkDir(files, "files", func(p string, d fs.DirEntry, err error) error { if err != nil || d.IsDir() { diff --git a/internal/theme/theme_test.go b/internal/theme/theme_test.go index b5a52d3..3f12e50 100644 --- a/internal/theme/theme_test.go +++ b/internal/theme/theme_test.go @@ -133,6 +133,10 @@ disableKinds = ["taxonomy", "term", "RSS"] func TestFiles(t *testing.T) { fs := Files() + man := ParseManifest(fs["MANIFEST"]) + if len(man) != len(fs)-2 || man["static/css/supermarket.css"] != Sum([]byte(fs["static/css/supermarket.css"])) { + t.Errorf("manifest: %d entries for %d files", len(man), len(fs)) + } if fs["VERSION"] != "1\n" || !strings.Contains(fs["README.md"], "| `hero` |") || !strings.Contains(LeadScript(), "window.leadPost") { t.Error("files") } diff --git a/internal/web/newsite_test.go b/internal/web/newsite_test.go index 505d800..23f3c44 100644 --- a/internal/web/newsite_test.go +++ b/internal/web/newsite_test.go @@ -14,9 +14,11 @@ import ( "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) { @@ -127,3 +129,80 @@ func TestNewSite(t *testing.T) { 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"] = "

old

" + delete(old, "layouts/404.html") + old["MANIFEST"] = theme.Manifest(old) + old["layouts/partials/header.html"] += "" + 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's version 1") { + t.Errorf("again: %s", body) + } +} diff --git a/internal/web/server.go b/internal/web/server.go index 3accdb5..dfbaf69 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -186,6 +186,7 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("GET /sites/pages/{id}", s.sitePagePage) mux.HandleFunc("POST /sites/pages/{id}/{action}", s.sitePageAction) mux.HandleFunc("GET /sites/publishing", s.sitesPublishingPage) + mux.HandleFunc("POST /sites/theme/update", s.sitesThemeUpdate) mux.HandleFunc("GET /sites/new", s.newSitePage) mux.HandleFunc("POST /sites/new", s.newSiteCreate) mux.HandleFunc("GET /sites/forms", s.sitesFormsPage) diff --git a/internal/web/sites.go b/internal/web/sites.go index 7e21117..125b90f 100644 --- a/internal/web/sites.go +++ b/internal/web/sites.go @@ -15,7 +15,6 @@ import ( "supermarket/internal/hugorepo" "supermarket/internal/profile" "supermarket/internal/sites" - "supermarket/internal/theme" ) // siteRepo is a website with a Hugo repository, from the profile. @@ -101,8 +100,12 @@ func (s *Server) renderSites(w http.ResponseWriter, r *http.Request, errMsg stri cancel() } wc.Release() - if raw, rerr := os.ReadFile(filepath.Join(wc.Dir, theme.Dir, "VERSION")); rerr == nil { - data["Theme"] = strings.TrimSpace(string(raw)) + if ts := sites.ReadTheme(wc.Dir); ts.Has { + data["Theme"] = ts + var pr formsPR + if ok, _ := s.DB.GetJSON(themePRKey(cur.Repo), &pr); ok { + data["ThemePR"] = pr + } data["Kinds"] = []string{"home", "about", "contact"} if p, _ := profile.Load(s.DB); p != nil { data["Products"] = p.Products @@ -399,3 +402,36 @@ func (n noListing) Open(name string) (http.File, error) { } return f, nil } + +func themePRKey(repo string) string { return "sites:theme-pr:" + repo } + +// sitesThemeUpdate opens the pull request that brings a site's copy of the +// theme up to date. +func (s *Server) sitesThemeUpdate(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + _, cur := s.currentSite(r) + if cur == nil || cur.Repo == "" { + s.renderSites(w, r, "Choose a website with a Hugo repository.") + return + } + if s.gitea() == nil { + s.renderSites(w, r, "Save a Gitea token under Settings → Search engines first.") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute) + defer cancel() + pull, d, err := sites.UpdateTheme(ctx, s.applier(seoSite{Index: cur.Index, URL: cur.URL})) + if err != nil { + s.renderSites(w, r, err.Error()) + return + } + pr := formsPR{Number: pull.Number, URL: pull.HTMLURL, At: time.Now(), State: "open", Capture: strconv.Itoa(d.To)} + if err := s.DB.PutJSON(themePRKey(cur.Repo), pr); err != nil { + s.serverError(w, err) + return + } + http.Redirect(w, r, "/sites?site="+strconv.Itoa(cur.Index), http.StatusSeeOther) +} diff --git a/internal/web/templates/sites.html b/internal/web/templates/sites.html index 12908bb..8229f62 100644 --- a/internal/web/templates/sites.html +++ b/internal/web/templates/sites.html @@ -26,10 +26,21 @@ {{end}} {{with .Catalog}} -{{if $d.Theme}} +{{with $d.Theme}} +
+

The theme

+ {{if .Outdated}} +

This site has Supermarket's theme version {{.Version}}; Supermarket has version {{.Latest}}.

+
+ + Opens a pull request that replaces the site's copy, checked with a build.
+ {{else}}

This site has Supermarket's theme, version {{.Version}}: the latest.

{{end}} + {{with .Edited}}

Changed by hand in the site's copy of the theme: {{join . ", "}}. An update replaces them; such changes belong in the site's own layouts/ or static/, which win over the theme.

{{end}} + {{with $d.ThemePR}}

Last update: the pull request ↗, {{ago .At}}.

{{end}} +

First pages

-

This site uses Supermarket's theme (version {{$d.Theme}}). Build its pages: each is written from your profile, opens for you to edit and preview, and goes to the site as a pull request.

+

This site uses Supermarket's theme. Build its pages: each is written from your profile, opens for you to edit and preview, and goes to the site as a pull request.

{{range $d.Kinds}}