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:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user