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
+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)
}
}
}