Phase 5 part 2: preview any branch of a site

Sites → Previews builds a branch with Hugo (drafts included) and serves it
under /preview/<site>/<branch>/, links rewritten to stay inside, behind a
sandboxing CSP so a branch's scripts can't act on the app or phone home.
The image now builds Hugo v0.170.1 from source; Alpine's 0.147.2 couldn't
build the site. Hugo's errors show their innermost cause.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 14:02:23 -07:00
co-authored by Claude Opus 5.5
parent 1152cd448b
commit 233c6ac630
13 changed files with 722 additions and 5 deletions
+108 -1
View File
@@ -402,7 +402,7 @@ func (r *Repo) Build(ctx context.Context) (string, error) {
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 "", fmt.Errorf("hugo couldn't build the site: %s", hugoError(buf.String()))
}
return out, nil
}
@@ -615,3 +615,110 @@ func (r *Repo) UpsertPage(rel string, fields []Field, body string) error {
}
return nil
}
// --- Previews ---
// Branch is a branch on the server.
type Branch struct {
Name, Hash, Subject string
At time.Time
}
// Branches are the server's branches, as of the last Sync, newest first.
func (r *Repo) Branches(ctx context.Context) ([]Branch, error) {
out, err := r.git(ctx, "for-each-ref", "--sort=-committerdate",
"--format=%(refname:strip=3)%1f%(objectname)%1f%(committerdate:unix)%1f%(subject)", "refs/remotes/origin")
if err != nil {
return nil, err
}
var bs []Branch
for _, l := range strings.Split(strings.TrimSpace(out), "\n") {
f := strings.Split(l, "\x1f")
if len(f) != 4 || f[0] == "HEAD" {
continue
}
sec, _ := strconv.ParseInt(f[2], 10, 64)
bs = append(bs, Branch{Name: f[0], Hash: f[1], At: time.Unix(sec, 0), Subject: f[3]})
}
return bs, nil
}
// CheckoutRemote puts a server branch's latest commit in the working copy
// (detached), and returns that commit. Sync puts the published branch back.
func (r *Repo) CheckoutRemote(ctx context.Context, branch string) (string, error) {
if strings.HasPrefix(branch, "-") {
return "", fmt.Errorf("no branch %q", branch)
}
for _, args := range [][]string{
{"checkout", "--quiet", "--force", "--detach", "refs/remotes/origin/" + branch},
{"clean", "-fdq"},
{"submodule", "update", "--init", "--recursive", "--quiet"},
} {
if _, err := r.git(ctx, args...); err != nil {
return "", err
}
}
out, err := r.git(ctx, "rev-parse", "HEAD")
return strings.TrimSpace(out), err
}
// BuildTo builds the site as it is into dest (emptied first), for viewing
// at baseURL. Drafts and future pages are included: a preview shows
// everything.
func (r *Repo) BuildTo(ctx context.Context, dest, baseURL string) error {
if err := os.RemoveAll(dest); err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return err
}
ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
cmd := exec.CommandContext(ctx, "hugo", "--quiet", "--destination", dest, "--baseURL", baseURL,
"--buildDrafts", "--buildFuture", "--cacheDir", filepath.Join(os.TempDir(), "supermarket-hugo-cache"))
cmd.Dir = r.Dir
var buf bytes.Buffer
cmd.Stdout, cmd.Stderr = &buf, &buf
if err := cmd.Run(); err != nil {
os.RemoveAll(dest)
return fmt.Errorf("hugo couldn't build the site: %s", hugoError(buf.String()))
}
return nil
}
var hugoPath = regexp.MustCompile(`"(?:/[^"]*/)?((?:layouts|content|themes|assets|data)/[^"]*)"`)
// hugoError picks the cause out of Hugo's output: the first ERROR line (or
// the final "Error:" line), with file paths cut to the repository's.
func hugoError(out string) string {
var pick string
for _, l := range strings.Split(out, "\n") {
l = strings.TrimSpace(l)
if strings.HasPrefix(l, "ERROR") {
pick = strings.TrimSpace(strings.TrimPrefix(l, "ERROR"))
break
}
if strings.HasPrefix(l, "Error:") && pick == "" {
pick = strings.TrimSpace(strings.TrimPrefix(l, "Error:"))
}
}
if pick == "" {
pick = firstLine(out)
}
if pick == "" {
return "no message (is the Hugo version recent enough for this site?)"
}
pick = hugoPath.ReplaceAllString(pick, `"$1"`)
// The innermost cause is what's useful; Hugo nests each template call.
if i := strings.LastIndex(pick, ": execute of template failed: "); i >= 0 {
head := pick
if j := strings.Index(head, ` failed: `); j >= 0 && j < i {
head = head[:j]
}
pick = head + ": " + pick[i+len(": execute of template failed: "):]
}
if r := []rune(pick); len(r) > 500 {
pick = string(r[:500]) + "…"
}
return pick
}
+16
View File
@@ -90,3 +90,19 @@ func TestRepo(t *testing.T) {
t.Errorf("after sync: %q", v)
}
}
func TestHugoError(t *testing.T) {
out := `Start building sites …
ERROR render of "/data/sites/x/content/partners.md" failed: "/data/sites/x/layouts/_default/single.html:2:5": execute of template failed: template: single.html:2:5: executing "main" at <partial "render-sections.html" .>: error calling partial: "/data/sites/x/layouts/partials/sections/hero.html:104:29": execute of template failed: template: _partials/sections/hero.html:104:29: executing "_partials/sections/hero.html" at <hugo>: can't evaluate field Data in type interface {}
Error: error building site: render: failed to render pages: …`
want := `render of "content/partners.md": template: _partials/sections/hero.html:104:29: executing "_partials/sections/hero.html" at <hugo>: can't evaluate field Data in type interface {}`
if got := hugoError(out); got != want {
t.Errorf("got %s\nwant %s", got, want)
}
if got := hugoError("Error: config not found"); got != "config not found" {
t.Errorf("Error: line: %s", got)
}
if got := hugoError(""); !strings.Contains(got, "no message") {
t.Errorf("empty: %s", got)
}
}
+98
View File
@@ -0,0 +1,98 @@
package sites
import (
"io/fs"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
)
// Preview is a built copy of one branch of a site.
type Preview struct {
Branch string `json:"branch"`
Slug string `json:"slug"` // its part of the preview's address
Commit string `json:"commit"` // what was built
At time.Time `json:"at"`
Err string `json:"error,omitempty"`
}
var nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
// Slug names a branch in a preview's address: lower case letters, digits
// and hyphens, different from the slugs already taken by other branches.
func Slug(branch string, taken []Preview) string {
base := strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(branch), "-"), "-")
if base == "" {
base = "branch"
}
slug := base
for n := 2; ; n++ {
clash := false
for _, p := range taken {
if p.Slug == slug && p.Branch != branch {
clash = true
}
}
if !clash {
return slug
}
slug = base + "-" + strconv.Itoa(n)
}
}
var (
attrURL = regexp.MustCompile(`(\s(?:href|src|action|poster|data-src)=["']?)/([^/]|["'\s>]|$)`)
srcsetRe = regexp.MustCompile(`(\ssrcset=)(["'])([^"']*)(["'])`)
refreshRe = regexp.MustCompile(`(?i)(content=["']?\d+\s*;\s*url=)/([^/])`)
cssURL = regexp.MustCompile(`(url\(\s*["']?)/([^/])`)
)
// Rehome rewrites a site built for "/" to be served under prefix
// ("/preview/0/main/"): every address that starts at the site's root, in
// HTML attributes, srcsets, redirects and CSS, gets the prefix. Addresses
// to other sites are left alone.
func Rehome(dir, prefix string) error {
prefix = "/" + strings.Trim(prefix, "/") + "/"
return filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
ext := strings.ToLower(filepath.Ext(p))
if ext != ".html" && ext != ".htm" && ext != ".css" {
return nil
}
raw, err := os.ReadFile(p)
if err != nil {
return err
}
s := RehomeText(string(raw), prefix, ext == ".css")
if s == string(raw) {
return nil
}
return os.WriteFile(p, []byte(s), 0o644)
})
}
// RehomeText does Rehome's rewriting on one file's text.
func RehomeText(s, prefix string, css bool) string {
s = cssURL.ReplaceAllString(s, "${1}"+prefix+"${2}")
if css {
return s
}
s = attrURL.ReplaceAllString(s, "${1}"+prefix+"${2}")
s = refreshRe.ReplaceAllString(s, "${1}"+prefix+"${2}")
return srcsetRe.ReplaceAllStringFunc(s, func(m string) string {
g := srcsetRe.FindStringSubmatch(m)
parts := strings.Split(g[3], ",")
for i, c := range parts {
t := strings.TrimLeft(c, " \t\n")
if strings.HasPrefix(t, "/") && !strings.HasPrefix(t, "//") {
parts[i] = c[:len(c)-len(t)] + prefix + t[1:]
}
}
return g[1] + g[2] + strings.Join(parts, ",") + g[4]
})
}
+40
View File
@@ -0,0 +1,40 @@
package sites
import "testing"
func TestRehomeText(t *testing.T) {
const p = "/preview/0/main/"
for in, want := range map[string]string{
`<a href="/pricing/">`: `<a href="/preview/0/main/pricing/">`,
`<a href="/">`: `<a href="/preview/0/main/">`,
`<a href=/about/>`: `<a href=/preview/0/main/about/>`,
`<a href="//cdn.example/x.js">`: `<a href="//cdn.example/x.js">`,
`<a href="https://other.example/">`: `<a href="https://other.example/">`,
`<a href="#top">`: `<a href="#top">`,
`<img src='/i.png' srcset="/a.png 1x, /b.png 2x, https://c/d.png 3x">`: `<img src='/preview/0/main/i.png' srcset="/preview/0/main/a.png 1x, /preview/0/main/b.png 2x, https://c/d.png 3x">`,
`<meta http-equiv="refresh" content="0; url=/new/">`: `<meta http-equiv="refresh" content="0; url=/preview/0/main/new/">`,
`<div style="background:url('/bg.jpg')">`: `<div style="background:url('/preview/0/main/bg.jpg')">`,
`<form action="/send">`: `<form action="/preview/0/main/send">`,
} {
if got := RehomeText(in, p, false); got != want {
t.Errorf("%s\n got %s\nwant %s", in, got, want)
}
}
if got := RehomeText(`a{background:url(/x.png)} <a href="/">`, p, true); got != `a{background:url(/preview/0/main/x.png)} <a href="/">` {
t.Errorf("css: %s", got)
}
}
func TestSlug(t *testing.T) {
taken := []Preview{{Branch: "supermarket/page-1", Slug: "supermarket-page-1"}}
for branch, want := range map[string]string{
"main": "main",
"supermarket/page-1": "supermarket-page-1",
"Supermarket/Page_1": "supermarket-page-1-2",
"///": "branch",
} {
if got := Slug(branch, taken); got != want {
t.Errorf("%q: %q, want %q", branch, got, want)
}
}
}
+7
View File
@@ -178,6 +178,13 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("POST /metrics/customers/{id}", s.metricsCustomerMatch)
mux.HandleFunc("GET /sites", s.sitesPage)
mux.HandleFunc("POST /sites/sync", s.sitesSync)
mux.HandleFunc("GET /sites/previews", s.sitesPreviewsPage)
mux.HandleFunc("POST /sites/previews/build", s.sitesPreviewBuild)
mux.HandleFunc("POST /sites/previews/delete", s.sitesPreviewDelete)
mux.HandleFunc("GET /preview/{site}/{slug}/{path...}", s.previewServe)
mux.HandleFunc("GET /preview/{site}/{slug}", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, r.URL.Path+"/", http.StatusMovedPermanently)
})
mux.HandleFunc("GET /seo", s.seoPage)
mux.HandleFunc("GET /seo/check", s.seoCheckPage)
mux.HandleFunc("GET /seo/engines", s.seoEnginesPage)
+1 -1
View File
@@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) {
"/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz",
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
"/content/scheduled", "/content/published",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews",
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
rec := do(h, http.MethodGet, path, nil, nil)
if rec.Code != http.StatusOK {
+238
View File
@@ -2,7 +2,10 @@ package web
import (
"context"
"errors"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
@@ -153,3 +156,238 @@ func (s *Server) sitesSync(w http.ResponseWriter, r *http.Request) {
}
http.Redirect(w, r, "/sites?site="+strconv.Itoa(cur.Index), http.StatusSeeOther)
}
// --- Previews ---
func sitePreviewsKey(full string) string { return "sites:previews:" + full }
func (s *Server) previewDir(full, slug string) string {
return filepath.Join(s.DataDir, "previews", strings.ReplaceAll(full, "/", "__"), slug)
}
func previewPrefix(site int, slug string) string {
return "/preview/" + strconv.Itoa(site) + "/" + slug + "/"
}
func (s *Server) previews(full string) []sites.Preview {
var ps []sites.Preview
_, _ = s.DB.GetJSON(sitePreviewsKey(full), &ps)
return ps
}
// previewRow is a branch on the previews page.
type previewRow struct {
hugorepo.Branch
Published bool
Preview *sites.Preview
Link string
Stale bool // the branch has moved on since the preview was built
}
func (s *Server) sitesPreviewsPage(w http.ResponseWriter, r *http.Request) {
s.renderPreviews(w, r, "")
}
func (s *Server) renderPreviews(w http.ResponseWriter, r *http.Request, errMsg string) {
all, cur := s.currentSite(r)
data := map[string]any{"Sites": all, "Current": cur, "Gitea": s.gitea() != nil, "Hugo": hugorepo.HugoVersion(r.Context()) != ""}
if cur != nil && cur.Repo != "" {
var synced siteSynced
if ok, _ := s.DB.GetJSON(siteSyncKey(cur.Repo), &synced); ok && !synced.At.IsZero() {
data["HasSynced"], data["Synced"] = true, synced
ps := s.previews(cur.Repo)
wc := &hugorepo.Repo{Dir: s.siteDir(cur.Repo), Branch: synced.Branch}
wc.Acquire()
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
branches, err := wc.Branches(ctx)
cancel()
wc.Release()
if err != nil {
errMsg = "Couldn't list the branches: " + err.Error()
}
var rows []previewRow
for _, b := range branches {
row := previewRow{Branch: b, Published: b.Name == synced.Branch}
for i := range ps {
if ps[i].Branch == b.Name {
row.Preview = &ps[i]
if ps[i].Commit != "" {
row.Link = previewPrefix(cur.Index, ps[i].Slug)
row.Stale = ps[i].Commit != b.Hash
}
}
}
if row.Published {
rows = append([]previewRow{row}, rows...)
} else {
rows = append(rows, row)
}
}
data["Rows"] = rows
}
}
s.render(w, r, "sites-previews", page{Title: "Previews", Nav: "sites/previews", Error: errMsg, Data: data})
}
// sitesPreviewBuild builds a branch's preview: a fresh read of the
// repository, the branch checked out, Hugo built, and the result moved to
// where /preview/ serves it.
func (s *Server) sitesPreviewBuild(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
_, cur := s.currentSite(r)
branch := r.PostFormValue("branch")
if cur == nil || cur.Repo == "" || branch == "" {
s.renderPreviews(w, r, "Choose a website and a branch.")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
defer cancel()
p, err := s.buildPreview(ctx, *cur, branch)
if err != nil {
s.renderPreviews(w, r, err.Error())
return
}
http.Redirect(w, r, "/sites/previews?site="+strconv.Itoa(cur.Index)+"&built="+url.QueryEscape(p.Slug), http.StatusSeeOther)
}
func (s *Server) buildPreview(ctx context.Context, cur siteRepo, branch string) (*sites.Preview, error) {
if hugorepo.HugoVersion(ctx) == "" {
return nil, errors.New("there's no Hugo in Supermarket's image, so previews can't be built")
}
ap := s.applier(seoSite{Index: cur.Index, URL: cur.URL})
wc, _, published, err := ap.WorkingCopy(ctx)
if err != nil {
return nil, err
}
defer wc.Release()
_ = s.DB.PutJSON(siteSyncKey(cur.Repo), siteSynced{At: time.Now(), Branch: published})
ps := s.previews(cur.Repo)
p := sites.Preview{Branch: branch, Slug: sites.Slug(branch, ps), At: time.Now()}
commit, err := wc.CheckoutRemote(ctx, branch)
if err == nil {
tmp := s.previewDir(cur.Repo, "."+p.Slug+".building")
if err = wc.BuildTo(ctx, tmp, "/"); err == nil {
if err = sites.Rehome(tmp, previewPrefix(cur.Index, p.Slug)); err == nil {
dest := s.previewDir(cur.Repo, p.Slug)
os.RemoveAll(dest)
err = os.Rename(tmp, dest)
}
os.RemoveAll(tmp)
}
}
// Leave the working copy on the published branch for the next job.
_ = wc.Sync(ctx)
if err != nil {
p.Err = err.Error()
} else {
p.Commit = commit
}
kept := []sites.Preview{p}
for _, old := range ps {
if old.Branch != branch {
kept = append(kept, old)
} else if err != nil && old.Commit != "" {
// A failed build keeps serving the last good one.
kept[0].Commit, kept[0].Slug = old.Commit, old.Slug
}
}
if perr := s.DB.PutJSON(sitePreviewsKey(cur.Repo), kept); perr != nil {
return nil, perr
}
if err != nil {
return nil, err
}
return &p, nil
}
// sitesPreviewDelete removes a branch's preview.
func (s *Server) sitesPreviewDelete(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 == "" {
http.Redirect(w, r, "/sites/previews", http.StatusSeeOther)
return
}
var kept []sites.Preview
for _, p := range s.previews(cur.Repo) {
if p.Branch == r.PostFormValue("branch") {
os.RemoveAll(s.previewDir(cur.Repo, p.Slug))
continue
}
kept = append(kept, p)
}
if err := s.DB.PutJSON(sitePreviewsKey(cur.Repo), kept); err != nil {
s.serverError(w, err)
return
}
http.Redirect(w, r, "/sites/previews?site="+strconv.Itoa(cur.Index), http.StatusSeeOther)
}
// previewCSP is the policy for previewed pages. They're the site's own
// pages, scripts and all, but whatever a branch holds mustn't be able to
// act on Supermarket: sandbox gives each page an origin of its own, so
// its requests to the app are cross-site (and refused), and nothing is
// sent anywhere else (no analytics from previews).
const previewCSP = "sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox; default-src 'self'; " +
"img-src 'self' data: https:; media-src 'self' https:; font-src 'self' data:; style-src 'self' 'unsafe-inline'; " +
"script-src 'self' 'unsafe-inline'; connect-src 'none'; form-action 'none'; frame-ancestors 'none'"
// previewServe serves a built preview.
func (s *Server) previewServe(w http.ResponseWriter, r *http.Request) {
site, err := strconv.Atoi(r.PathValue("site"))
if err != nil {
http.NotFound(w, r)
return
}
var cur *siteRepo
for _, sr := range s.siteRepos() {
if sr.Index == site && sr.Repo != "" {
cur = &sr
}
}
slug := r.PathValue("slug")
if cur == nil || strings.HasPrefix(slug, ".") {
http.NotFound(w, r)
return
}
found := false
for _, p := range s.previews(cur.Repo) {
if p.Slug == slug && p.Commit != "" {
found = true
}
}
if !found {
http.Error(w, "No preview of that branch. Build one under Sites → Previews.", http.StatusNotFound)
return
}
h := w.Header()
h.Set("Content-Security-Policy", previewCSP)
h.Set("Cache-Control", "no-store")
prefix := strings.TrimSuffix(previewPrefix(site, slug), "/")
http.StripPrefix(prefix, http.FileServer(noListing{http.Dir(s.previewDir(cur.Repo, slug))})).ServeHTTP(w, r)
}
// noListing serves files, and folders only through their index.html.
type noListing struct{ fs http.FileSystem }
func (n noListing) Open(name string) (http.File, error) {
f, err := n.fs.Open(name)
if err != nil {
return nil, err
}
if st, err := f.Stat(); err == nil && st.IsDir() {
idx, err := n.fs.Open(strings.TrimSuffix(name, "/") + "/index.html")
if err != nil {
f.Close()
return nil, os.ErrNotExist
}
idx.Close()
}
return f, nil
}
+113
View File
@@ -1,13 +1,18 @@
package web
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"supermarket/internal/hugorepo"
"supermarket/internal/hugorepo/hugotest"
"supermarket/internal/profile"
"supermarket/internal/secrets"
@@ -64,3 +69,111 @@ func TestSitesPage(t *testing.T) {
t.Errorf("after a failed read: %s", body)
}
}
func TestSitePreviews(t *testing.T) {
if hugorepo.HugoVersion(context.Background()) == "" {
t.Skip("no hugo")
}
clone := hugotest.Site(t, map[string]string{
"layouts/_default/single.html": `{{ define "main" }}<h1>{{ .Title }}</h1><a href="/pricing/">Prices</a><img src="{{ "logo.png" | relURL }}">{{ .Content }}{{ end }}`,
"static/logo.png": "png",
})
// A second branch, as a pull request would have.
work := t.TempDir()
for _, args := range [][]string{
{"clone", "-q", clone, work},
{"-C", work, "checkout", "-qb", "supermarket/page-1"},
} {
if out, err := exec.Command("git", args...).CombinedOutput(); err != nil {
t.Fatalf("git %v: %s", args, out)
}
}
os.WriteFile(filepath.Join(work, "content", "new.md"), []byte("---\ntitle: Brand new\ndraft: true\n---\nFresh.\n"), 0o644)
for _, args := range [][]string{
{"-C", work, "add", "."},
{"-C", work, "-c", "user.name=T", "-c", "user.email=t@example.com", "commit", "-qm", "Add a page"},
{"-C", work, "push", "-q", "origin", "supermarket/page-1"},
} {
if out, err := exec.Command("git", args...).CombinedOutput(); err != nil {
t.Fatalf("git %v: %s", args, out)
}
}
g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/v1/repos/Us/site" {
fmt.Fprintf(w, `{"full_name":"Us/site","default_branch":"main","clone_url":%q,"permissions":{"push":true}}`, clone)
return
}
http.NotFound(w, r)
}))
defer g.Close()
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: "https://us.example/", Repo: "Us/site"}}})
postForm(h, "/settings/search", url.Values{"gitea_url": {g.URL}, secrets.GiteaToken: {"tok"}})
if body := do(h, http.MethodGet, "/sites/previews", nil, nil).Body.String(); !strings.Contains(body, "under <a href=\"/sites?site=0\">Sections and pages</a> first") {
t.Errorf("before reading: %s", body)
}
postForm(h, "/sites/sync", url.Values{"site": {"0"}})
body := do(h, http.MethodGet, "/sites/previews", nil, nil).Body.String()
if !strings.Contains(body, "<strong>main</strong> <span class=\"badge published\">") || !strings.Contains(body, "supermarket/page-1") ||
!strings.Contains(body, "Add a page") || strings.Contains(body, "Open preview") {
t.Errorf("branches: %s", body)
}
if rec := do(h, http.MethodGet, "/preview/0/supermarket-page-1/", nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("before building: %d", rec.Code)
}
rec := postForm(h, "/sites/previews/build", url.Values{"site": {"0"}, "branch": {"supermarket/page-1"}})
if rec.Code != http.StatusSeeOther {
t.Fatalf("build: %d %s", rec.Code, rec.Body.String())
}
body = do(h, http.MethodGet, "/sites/previews", nil, nil).Body.String()
if !strings.Contains(body, `href="/preview/0/supermarket-page-1/"`) || strings.Contains(body, "moved on") {
t.Errorf("after building: %s", body)
}
// The draft page is there, its links stay inside the preview, and the
// page is sandboxed.
rec = do(h, http.MethodGet, "/preview/0/supermarket-page-1/new/", nil, nil)
got := rec.Body.String()
if rec.Code != http.StatusOK || !strings.Contains(got, "<h1>Brand new</h1>") || !strings.Contains(got, `href="/preview/0/supermarket-page-1/pricing/"`) ||
!strings.Contains(got, `src="/preview/0/supermarket-page-1/logo.png"`) {
t.Errorf("preview page: %d %s", rec.Code, got)
}
if csp := rec.Header().Get("Content-Security-Policy"); !strings.HasPrefix(csp, "sandbox allow-scripts") || strings.Contains(csp, "allow-same-origin") {
t.Errorf("csp: %s", csp)
}
if rec := do(h, http.MethodGet, "/preview/0/supermarket-page-1/logo.png", nil, nil); rec.Code != http.StatusOK || rec.Body.String() != "png" {
t.Errorf("static file: %d", rec.Code)
}
if rec := do(h, http.MethodGet, "/preview/0/supermarket-page-1", nil, nil); rec.Code != http.StatusMovedPermanently {
t.Errorf("no slash: %d", rec.Code)
}
if rec := do(h, http.MethodGet, "/preview/0/supermarket-page-1/../../../app.db", nil, nil); rec.Code == http.StatusOK {
t.Errorf("escaped the preview: %d", rec.Code)
}
// The working copy is back on the published branch.
if _, err := os.Stat(filepath.Join(s.siteDir("Us/site"), "content", "new.md")); err == nil {
t.Error("the working copy was left on the branch")
}
// A post from a preview page (its origin is "null") is refused.
if rec := do(h, http.MethodPost, "/sites/previews/delete", strings.NewReader("site=0&branch=supermarket/page-1"),
map[string]string{"Origin": "null", "Content-Type": "application/x-www-form-urlencoded"}); rec.Code != http.StatusForbidden {
t.Errorf("post from a preview: %d", rec.Code)
}
// The branch moves on: the preview says so.
os.WriteFile(filepath.Join(work, "content", "new.md"), []byte("---\ntitle: Newer\n---\n"), 0o644)
exec.Command("git", "-C", work, "-c", "user.name=T", "-c", "user.email=t@example.com", "commit", "-qam", "Again").Run()
exec.Command("git", "-C", work, "push", "-q", "origin", "supermarket/page-1").Run()
postForm(h, "/sites/sync", url.Values{"site": {"0"}})
if body := do(h, http.MethodGet, "/sites/previews", nil, nil).Body.String(); !strings.Contains(body, "moved on") {
t.Errorf("stale: %s", body)
}
postForm(h, "/sites/previews/delete", url.Values{"site": {"0"}, "branch": {"supermarket/page-1"}})
if rec := do(h, http.MethodGet, "/preview/0/supermarket-page-1/new/", nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("after deleting: %d", rec.Code)
}
if _, err := os.Stat(s.previewDir("Us/site", "supermarket-page-1")); err == nil {
t.Error("the files are still there")
}
}
+1
View File
@@ -62,6 +62,7 @@
{{if eq .ID "sites"}}
<div class="subnav">
<a href="/sites" {{if eq $nav "sites/site"}}aria-current="page"{{end}}>Sections and pages</a>
<a href="/sites/previews" {{if eq $nav "sites/previews"}}aria-current="page"{{end}}>Previews</a>
</div>
{{end}}
{{if eq .ID "prospects"}}
@@ -0,0 +1,53 @@
{{define "content"}}{{with .Data}}{{$d := .}}
<div class="heading"><h1>Previews</h1></div>
<p class="lede">See a branch of your website before it's merged. Supermarket builds the branch with Hugo, drafts included, and serves it here. Your live site isn't touched. Pull requests from Supermarket are branches too, so this is where you check a new page.</p>
{{if not .Sites}}
<section class="card empty"><p>Add your website and its Hugo repository under <a href="/settings/profile">Settings → Profile</a> first.</p></section>
{{else}}
{{if gt (len .Sites) 1}}<nav class="tabs">{{range .Sites}}<a href="/sites/previews?site={{.Index}}" {{if and $d.Current (eq .Index $d.Current.Index)}}aria-current="page"{{end}}>{{.URL}}</a>{{end}}</nav>{{end}}
{{if not .Hugo}}<p class="warn-text">There's no Hugo in Supermarket's image, so previews can't be built.</p>{{end}}
{{with .Current}}{{$cur := .}}
{{if .Err}}
<section class="card"><p class="warn-text">{{.URL}}: {{.Err}}. Set it under <a href="/settings/profile">Settings → Profile</a>.</p></section>
{{else if not $d.HasSynced}}
<section class="card empty"><p>Read {{.Repo}} under <a href="/sites?site={{.Index}}">Sections and pages</a> first.</p></section>
{{else}}
<p class="help">Branches of {{.Repo}}, as of the last read {{ago $d.Synced.At}}. Building reads the repository again first, so it builds the branch's latest commit. A preview can't send anything anywhere or change anything in Supermarket, and analytics don't count it.</p>
<div class="table-wrap"><table>
<thead><tr><th>Branch</th><th>Latest commit</th><th>Preview</th><th></th></tr></thead>
<tbody>
{{range $d.Rows}}
<tr>
<td><strong>{{.Name}}</strong>{{if .Published}} <span class="badge published">published</span>{{end}}</td>
<td class="small">{{.Subject}}<br><span class="muted">{{ago .At}}</span></td>
<td class="small">
{{with .Preview}}
{{if .Commit}}Built {{ago .At}}{{end}}
{{with .Err}}<br><span class="error-text">The last build failed: {{.}}</span>{{end}}
{{else}}<span class="muted">None yet</span>{{end}}
{{if .Stale}}<br><span class="warn-text">The branch has moved on since.</span>{{end}}
</td>
<td>
<div class="row-actions">
{{with .Link}}<a class="button" href="{{.}}" target="_blank" rel="noopener">Open preview ↗</a>{{end}}
<form method="post" action="/sites/previews/build">
<input type="hidden" name="site" value="{{$cur.Index}}"><input type="hidden" name="branch" value="{{.Name}}">
<button type="submit" class="secondary" data-busy="Building…" {{if or (not $d.Hugo) (not $d.Gitea)}}disabled{{end}}>{{if .Preview}}Build again{{else}}Build preview{{end}}</button>
</form>
{{if .Preview}}
<form method="post" action="/sites/previews/delete">
<input type="hidden" name="site" value="{{$cur.Index}}"><input type="hidden" name="branch" value="{{.Name}}">
<button type="submit" class="secondary">Delete</button>
</form>
{{end}}
</div>
</td>
</tr>
{{end}}
</tbody>
</table></div>
{{end}}
{{end}}
{{end}}
{{end}}{{end}}