From 1152cd448b72a38fd3c01c011be0ecb20d6a7b0a Mon Sep 17 00:00:00 2001 From: David Young Date: Sun, 22 Nov 2026 13:52:35 -0700 Subject: [PATCH] Phase 5 part 1: read a site's section types and pages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sites → Sections and pages reads the website's Hugo repository: each section type with the README's description, the fields in use and the layout's, the pages using it and a real example; the pages and their sections; the latest commits. Working copies are now held by one job at a time. Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 55 ++++ TEST.md | 19 ++ internal/hugorepo/hugotest/hugotest.go | 10 +- internal/hugorepo/repo.go | 64 +++++ internal/seo/briefs.go | 3 +- internal/seo/changes.go | 12 +- internal/seo/engines.go | 6 +- internal/sites/catalog.go | 380 +++++++++++++++++++++++++ internal/sites/catalog_test.go | 110 +++++++ internal/web/server.go | 13 +- internal/web/server_test.go | 2 +- internal/web/sites.go | 155 ++++++++++ internal/web/sites_test.go | 66 +++++ internal/web/templates/layout.html | 5 + internal/web/templates/sites.html | 69 +++++ 15 files changed, 958 insertions(+), 11 deletions(-) create mode 100644 internal/sites/catalog.go create mode 100644 internal/sites/catalog_test.go create mode 100644 internal/web/sites.go create mode 100644 internal/web/sites_test.go create mode 100644 internal/web/templates/sites.html diff --git a/PLAN.md b/PLAN.md index 9ae0aa3..dc516f1 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1207,6 +1207,61 @@ into `main`. **Parts 1 to 6 built, and merged into `main` on 2026-11-22** user's Gitea hooks deploy it to their Hugo server. The app shows the last merge, and checks the live site afterwards to confirm it changed. +**Started 2026-11-22** on branch `phase5-sites`, after Phase 4 was merged +into `main`. + +**Decisions (the user, 2026-11-22):** +- **Pages are built from each site's own sections**, not a new shared + theme. federated-website (about 20 section types) and webcoredesktop + (about 15) already use the same `sections:` front matter pattern, each + with its own layouts. Supermarket reads a site's section types (the + partials in `layouts/partials/sections/`, the README's field table, and + how existing pages use them) and composes pages from them. Nothing in + the layouts changes. A shared theme can come later. +- **Previews are built and served by the app**, under + `localhost:8470/preview/…`: Hugo builds the branch, so no second port is + needed. + +**Parts, in order, a commit after each:** +1. **Reading a site.** + - Sync the website's repository (Phase 3's working copy). + - The section catalogue: each section type with its fields (from the + README's table and from the pages that use it), an example from a + real page, and how many pages use it. + - The pages, with their address, title and section types. + - The last merge on the publish branch, from Gitea. + - A Sites page per website. +2. **Preview.** Build a branch (the published one, or a pull request's) + and serve it under `/preview///`, so a page can be seen + before it's merged. +3. **The page builder.** + - New pages of a kind: landing page, product page, " + alternative", comparison, blog post. + - Built from the profile, the Inventory, a buying signal (its angle, + with CTAs carrying its campaign tag) or an SEO brief. + - The AI composes `sections:` using only the site's own types and + fields, and code checks every type exists. + - Opened as a pull request, checked with a build, with a preview link. +4. **Pages per signal** (Phase 2's part 8): a landing page per buying + signal, created from the scorecard, and duplicated (to test a variant) + or deleted from it, always as pull requests. +5. **Publishing status.** After a merge, check the live site: the page is + there, its title matches, and the change shows. List the recent merges. + +**Part 1 built (2026-11-22; no schema change).** `internal/sites` reads a +working copy: section types are the partials in +`layouts/partials/sections/`, less the helpers other partials call (head, +ctas, wrapper…); each type gets the README's description (table rows or +list items), the fields pages use (with list items' keys), the fields its +layout reads, the pages using it, and its fullest real use as YAML in the +page's own field order. Types pages use without a layout are flagged. Pages +list their address, title and section types; TOML pages are listed but not +read. `hugorepo` gained a per-copy lock (so two jobs can't reset one copy at +once; every SEO job now takes it), `Log` and `PathOf`. Sites → Sections and +pages (`/sites`) reads the repository on request and shows the latest +commits on the published branch. Live: federated-website has 25 section +types and 59 pages (22 built from sections). + ### Future enhancements Not in any phase yet; picked up when the user asks. diff --git a/TEST.md b/TEST.md index 135c047..5d8273b 100644 --- a/TEST.md +++ b/TEST.md @@ -481,6 +481,25 @@ Throughout, also notice: - [ ] *add to the CRM* on a paying customer queues an Account on the CRM queue; once Hermes adds it, the customer shows as matched. +## 8a. Sites + +### Sections and pages + +- [ ] With no website in the profile, Sites says to add one; with a website + but no Hugo repository, it says to set one. +- [ ] *Read the repository* (needs the Gitea token) shows the website, its + repository and branch, and "Read from the repository just now". +- [ ] The latest commits on the published branch match Gitea's. +- [ ] Section types match `layouts/partials/sections/` (helpers like head, + ctas and wrapper aren't listed as types). Open a few: the README's + description, the fields in use, and the example match the site. +- [ ] A type no page uses says "not used yet"; a type a page uses with no + layout says "no layout". +- [ ] Pages built from sections list their section types in order; their + addresses open the live page. Markdown pages are under "other pages". +- [ ] With the Gitea server unreachable, *Read it again* says the read + failed and still shows the last good copy. + ## 9. Search - [ ] Searching for an inventory entry, a fetched item, a post, a prospect diff --git a/internal/hugorepo/hugotest/hugotest.go b/internal/hugorepo/hugotest/hugotest.go index 25ab533..99a23e4 100644 --- a/internal/hugorepo/hugotest/hugotest.go +++ b/internal/hugorepo/hugotest/hugotest.go @@ -9,8 +9,9 @@ import ( ) // Site makes a small Hugo site in a bare repository and returns its -// clone URL. Its titles are "Page title · Site". -func Site(t testing.TB) string { +// clone URL. Its titles are "Page title · Site". Extra files are added to +// (or replace) the site's own. +func Site(t testing.TB, extra ...map[string]string) string { t.Helper() dir := t.TempDir() src := filepath.Join(dir, "src") @@ -24,6 +25,11 @@ func Site(t testing.TB) string { "content/blog/first-post/index.md": "+++\ntitle = \"First post\"\n+++\nHello.\n", "content/about.md": "---\ntitle: About us\nurl: /company/\n---\nWho we are.\n", } + for _, e := range extra { + for name, body := range e { + files[name] = body + } + } for name, body := range files { p := filepath.Join(src, name) os.MkdirAll(filepath.Dir(p), 0o755) diff --git a/internal/hugorepo/repo.go b/internal/hugorepo/repo.go index f0118ab..d39f2e0 100644 --- a/internal/hugorepo/repo.go +++ b/internal/hugorepo/repo.go @@ -17,6 +17,7 @@ import ( "regexp" "strconv" "strings" + "sync" "time" "golang.org/x/net/html" @@ -31,6 +32,58 @@ type Repo struct { Author string // "Name " for commits touched []string // files written outside content/, to commit + release func() +} + +var ( + locksMu sync.Mutex + locks = map[string]*sync.Mutex{} +) + +// Acquire takes the working copy for one job: syncing resets it, so two +// jobs mustn't share it at once. Release gives it back. +func (r *Repo) Acquire() { + locksMu.Lock() + mu := locks[r.Dir] + if mu == nil { + mu = &sync.Mutex{} + locks[r.Dir] = mu + } + locksMu.Unlock() + mu.Lock() + r.release = mu.Unlock +} + +// Release gives the working copy back; it's safe to call when not held. +func (r *Repo) Release() { + if r.release != nil { + r.release() + r.release = nil + } +} + +// Commit is one commit on the published branch. +type Commit struct { + Hash, Author, Subject string + At time.Time +} + +// Log is the latest commits on the published branch, newest first. +func (r *Repo) Log(ctx context.Context, n int) ([]Commit, error) { + out, err := r.git(ctx, "log", "-n", strconv.Itoa(n), "--format=%H%x1f%an%x1f%at%x1f%s", "origin/"+r.Branch) + if err != nil { + return nil, err + } + var cs []Commit + for _, l := range strings.Split(strings.TrimSpace(out), "\n") { + f := strings.Split(l, "\x1f") + if len(f) != 4 { + continue + } + sec, _ := strconv.ParseInt(f[2], 10, 64) + cs = append(cs, Commit{Hash: f[0], Author: f[1], At: time.Unix(sec, 0), Subject: f[3]}) + } + return cs, nil } // git runs a git command in the working copy, with the token as an HTTP @@ -167,6 +220,17 @@ func cleanPath(p string) string { return p } +// PathOf is the path a content file (relative to content/) is published +// at: its front matter's url, else its slug, else where it sits. +func (r *Repo) PathOf(rel string) string { + us := urlsFor(rel, filepath.Join(r.Dir, "content", rel)) + fm := frontMatter(filepath.Join(r.Dir, "content", rel)) + if fm["url"] != "" || fm["slug"] != "" { + return us[len(us)-1] + } + return us[0] +} + // urlsFor are the paths a content file may be published at: from where it // sits (with and without a leading language folder), and from its front // matter's url or slug. diff --git a/internal/seo/briefs.go b/internal/seo/briefs.go index 0e3652c..522623e 100644 --- a/internal/seo/briefs.go +++ b/internal/seo/briefs.go @@ -475,10 +475,11 @@ func (ap *Applier) ApplyBrief(ctx context.Context, d *db.DB, id int64, confirmed } func (ap *Applier) applyBrief(ctx context.Context, d *db.DB, b *Brief) error { - wc, full, branch, err := ap.workingCopy(ctx) + wc, full, branch, err := ap.WorkingCopy(ctx) if err != nil { return err } + defer wc.Release() canBuild, note := buildCheck(ctx, wc) work := fmt.Sprintf("supermarket/page-%d", b.ID) if err := wc.NewBranch(ctx, work); err != nil { diff --git a/internal/seo/changes.go b/internal/seo/changes.go index d97400c..20d6934 100644 --- a/internal/seo/changes.go +++ b/internal/seo/changes.go @@ -524,9 +524,10 @@ func (ap *Applier) Apply(ctx context.Context, d *db.DB, id int64) error { return err } -// workingCopy is a fresh copy of the site's published branch, with the -// repository's full name and that branch. -func (ap *Applier) workingCopy(ctx context.Context) (*hugorepo.Repo, string, string, error) { +// WorkingCopy is a fresh copy of the site's published branch, with the +// repository's full name and that branch. The copy is held for the caller, +// who must Release it. +func (ap *Applier) WorkingCopy(ctx context.Context) (*hugorepo.Repo, string, string, error) { if ap.Gitea == nil { return nil, "", "", errors.New("save a Gitea token under Settings → Search engines first") } @@ -547,7 +548,9 @@ func (ap *Applier) workingCopy(ctx context.Context) (*hugorepo.Repo, string, str } wc := &hugorepo.Repo{Dir: filepath.Join(ap.ReposDir, strings.ReplaceAll(full, "/", "__")), CloneURL: repo.CloneURL, Token: ap.Gitea.Token(), Branch: branch, Author: ap.Author} + wc.Acquire() if err := wc.Sync(ctx); err != nil { + wc.Release() return nil, "", "", err } return wc, full, branch, nil @@ -568,10 +571,11 @@ func buildCheck(ctx context.Context, wc *hugorepo.Repo) (bool, string) { } func (ap *Applier) apply(ctx context.Context, d *db.DB, c *Change) error { - wc, full, branch, err := ap.workingCopy(ctx) + wc, full, branch, err := ap.WorkingCopy(ctx) if err != nil { return err } + defer wc.Release() u, err := url.Parse(c.Page) if err != nil { return err diff --git a/internal/seo/engines.go b/internal/seo/engines.go index b0cdd4e..cdcae24 100644 --- a/internal/seo/engines.go +++ b/internal/seo/engines.go @@ -200,10 +200,11 @@ func (ap *Applier) SetupSite(ctx context.Context, d *db.DB, site, key string, no } func (ap *Applier) setupSite(ctx context.Context, site, key string, st *Setup) error { - wc, full, branch, err := ap.workingCopy(ctx) + wc, full, branch, err := ap.WorkingCopy(ctx) if err != nil { return err } + defer wc.Release() canBuild, note := buildCheck(ctx, wc) work := "supermarket/search-engines" if err := wc.NewBranch(ctx, work); err != nil { @@ -271,10 +272,11 @@ func (ap *Applier) setupSite(ctx context.Context, site, key string, st *Setup) e // updates it if it's there: used for the open metrics page. The build // checks the page comes out. func (ap *Applier) PublishPage(ctx context.Context, pagePath, title, description, body, why string) (*gitea.Pull, string, error) { - wc, full, branch, err := ap.workingCopy(ctx) + wc, full, branch, err := ap.WorkingCopy(ctx) if err != nil { return nil, "", err } + defer wc.Release() canBuild, note := buildCheck(ctx, wc) pagePath = "/" + strings.Trim(pagePath, "/") + "/" work := "supermarket/page" + strings.TrimSuffix(strings.ReplaceAll(pagePath, "/", "-"), "-") diff --git a/internal/sites/catalog.go b/internal/sites/catalog.go new file mode 100644 index 0000000..a495f91 --- /dev/null +++ b/internal/sites/catalog.go @@ -0,0 +1,380 @@ +// Package sites reads and builds a Hugo website whose pages are made of +// sections: each page's front matter has a `sections:` list, and each +// section's `type` names a partial in layouts/partials/sections/. The +// catalogue of a site's section types comes from the site itself (its +// partials, its README, and how its pages use them), so new pages are +// made only of what the site already knows how to show. +package sites + +import ( + "bufio" + "bytes" + "io/fs" + "os" + "path/filepath" + "regexp" + "slices" + "sort" + "strings" + + "gopkg.in/yaml.v3" +) + +// SectionType is one kind of section the site can show. +type SectionType struct { + Name string + Doc string // from the README, when it says what the type takes + Fields []Field // seen in the site's pages, most used first + Layout []string // fields the layout reads, its helpers' included + Pages []string // paths of the pages that use it + Uses int // how many times it's used, all pages together + Example string // one real use, as YAML + Missing bool // used by pages, but there's no partial for it + + exampleSize int +} + +// Field is a field seen in use, with the keys of its list items when it's +// a list of maps. +type Field struct { + Name string + Items []string + Count int +} + +// Page is one content page. +type Page struct { + File string // relative to the repository + Path string // where it's published + Title string + Types []string // its sections' types, in order + Draft bool + Sections bool // it's built from sections (not a Markdown body) +} + +// Catalog is what a site is made of. +type Catalog struct { + Types []SectionType + Helpers []string // partials the sections share (headings, buttons…) + Pages []Page +} + +// Type finds a section type by name. +func (c *Catalog) Type(name string) *SectionType { + for i := range c.Types { + if c.Types[i].Name == name { + return &c.Types[i] + } + } + return nil +} + +// Has says whether the site has the section type. +func (c *Catalog) Has(name string) bool { + t := c.Type(name) + return t != nil && !t.Missing +} + +// PathFunc says where a content file (relative to content/) is published. +type PathFunc func(rel string) string + +var ( + partialRef = regexp.MustCompile(`partial\s+"sections/([\w-]+)\.html"\s*(?:(\$s|\.)(?:\s|-?\}\}|\)))?`) + dollarS = regexp.MustCompile(`\$s\.([a-z]\w*)`) + bareDot = regexp.MustCompile(`(?:^|[\s(])\.([a-z]\w*)`) + readmeList = regexp.MustCompile("^\\s*[-*]\\s+`([\\w-]+)`\\s+[—–-]+\\s+(.+)$") + readmeRow = regexp.MustCompile("^\\|\\s*`([\\w-]+)`\\s*\\|\\s*(.+?)\\s*\\|\\s*$") +) + +// Read reads the catalogue from a working copy of the site. +func Read(dir string, pathOf PathFunc) (*Catalog, error) { + partDir := filepath.Join(dir, "layouts", "partials", "sections") + entries, err := os.ReadDir(partDir) + if err != nil && !os.IsNotExist(err) { + return nil, err + } + partials := map[string]string{} + for _, e := range entries { + if !e.IsDir() && strings.HasSuffix(e.Name(), ".html") { + raw, err := os.ReadFile(filepath.Join(partDir, e.Name())) + if err != nil { + return nil, err + } + partials[strings.TrimSuffix(e.Name(), ".html")] = string(raw) + } + } + // Partials named by another partial, or by render-sections, are + // helpers unless a page uses them as a type. + referenced := map[string]bool{} + calls := map[string][]string{} // partial → helpers it hands the section to + for name, src := range partials { + for _, m := range partialRef.FindAllStringSubmatch(src, -1) { + referenced[m[1]] = true + if m[2] != "" { + calls[name] = append(calls[name], m[1]) + } + } + } + if raw, err := os.ReadFile(filepath.Join(dir, "layouts", "partials", "render-sections.html")); err == nil { + for _, m := range partialRef.FindAllStringSubmatch(string(raw), -1) { + referenced[m[1]] = true + } + } + + c := &Catalog{} + uses := map[string]*SectionType{} + fieldCount := map[string]map[string]*Field{} + get := func(name string) *SectionType { + t := uses[name] + if t == nil { + t = &SectionType{Name: name} + uses[name] = t + fieldCount[name] = map[string]*Field{} + } + return t + } + + root := filepath.Join(dir, "content") + err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + if os.IsNotExist(err) && p == root { + return fs.SkipDir + } + return err + } + if d.IsDir() || !strings.EqualFold(filepath.Ext(p), ".md") { + return nil + } + rel, _ := filepath.Rel(root, p) + pg := Page{File: filepath.ToSlash(filepath.Join("content", rel)), Path: pathOf(rel)} + fm, node, err := readFrontMatter(p) + if err != nil || fm == nil { + // Not YAML (or not readable): listed, but not read for sections. + pg.Title = otherTitle(p) + c.Pages = append(c.Pages, pg) + return nil + } + pg.Title, _ = fm["title"].(string) + pg.Draft, _ = fm["draft"].(bool) + secs, _ := fm["sections"].([]any) + pg.Sections = len(secs) > 0 + secNodes := sectionNodes(node) + for i, s := range secs { + m, ok := s.(map[string]any) + if !ok { + continue + } + name, _ := m["type"].(string) + if name == "" { + continue + } + pg.Types = append(pg.Types, name) + t := get(name) + t.Uses++ + if !slices.Contains(t.Pages, pg.Path) { + t.Pages = append(t.Pages, pg.Path) + } + for k, v := range m { + if k == "type" { + continue + } + f := fieldCount[name][k] + if f == nil { + f = &Field{Name: k} + fieldCount[name][k] = f + } + f.Count++ + if list, ok := v.([]any); ok { + for _, it := range list { + if im, ok := it.(map[string]any); ok { + for ik := range im { + if !slices.Contains(f.Items, ik) { + f.Items = append(f.Items, ik) + } + } + } + } + } + } + if (t.Example == "" || len(m) > t.exampleSize) && i < len(secNodes) { + t.Example, t.exampleSize = example(secNodes[i]), len(m) + } + } + c.Pages = append(c.Pages, pg) + return nil + }) + if err != nil { + return nil, err + } + + for name := range partials { + if referenced[name] && uses[name] == nil { + c.Helpers = append(c.Helpers, name) + continue + } + get(name) + } + docs := readmeDocs(dir) + for name, t := range uses { + _, has := partials[name] + t.Missing = !has + t.Doc = docs[name] + for _, f := range fieldCount[name] { + sort.Strings(f.Items) + t.Fields = append(t.Fields, *f) + } + sort.Slice(t.Fields, func(i, j int) bool { + if t.Fields[i].Count != t.Fields[j].Count { + return t.Fields[i].Count > t.Fields[j].Count + } + return t.Fields[i].Name < t.Fields[j].Name + }) + if has { + t.Layout = layoutFields(name, partials, calls, map[string]bool{}) + } + c.Types = append(c.Types, *t) + } + sort.Slice(c.Types, func(i, j int) bool { + if c.Types[i].Uses != c.Types[j].Uses { + return c.Types[i].Uses > c.Types[j].Uses + } + return c.Types[i].Name < c.Types[j].Name + }) + sort.Strings(c.Helpers) + sort.Slice(c.Pages, func(i, j int) bool { return c.Pages[i].Path < c.Pages[j].Path }) + return c, nil +} + +// layoutFields are the section fields a partial reads, and those of the +// helpers it hands the section to. +func layoutFields(name string, partials map[string]string, calls map[string][]string, seen map[string]bool) []string { + if seen[name] { + return nil + } + seen[name] = true + src := partials[name] + set := map[string]bool{} + re := bareDot + if strings.Contains(src, "$s :=") { + re = dollarS + } + for _, m := range re.FindAllStringSubmatch(stripComments(src), -1) { + set[m[1]] = true + } + for _, h := range calls[name] { + for _, f := range layoutFields(h, partials, calls, seen) { + set[f] = true + } + } + delete(set, "type") + out := make([]string, 0, len(set)) + for f := range set { + out = append(out, f) + } + sort.Strings(out) + return out +} + +var comments = regexp.MustCompile(`(?s)\{\{-?\s*/\*.*?\*/\s*-?\}\}`) + +func stripComments(s string) string { return comments.ReplaceAllString(s, "") } + +// readmeDocs reads what the README says each type takes: rows of a table +// ("| `hero` | fields |") or list items ("- `paths` — what it is"). +func readmeDocs(dir string) map[string]string { + out := map[string]string{} + for _, name := range []string{"README.md", "readme.md", "README"} { + raw, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil { + continue + } + sc := bufio.NewScanner(bytes.NewReader(raw)) + sc.Buffer(make([]byte, 64<<10), 1<<20) + for sc.Scan() { + line := sc.Text() + var m []string + if m = readmeRow.FindStringSubmatch(line); m == nil { + m = readmeList.FindStringSubmatch(line) + } + if m == nil { + continue + } + if prev := out[m[1]]; prev != "" { + out[m[1]] = prev + " " + strings.TrimSpace(m[2]) + } else { + out[m[1]] = strings.TrimSpace(m[2]) + } + } + break + } + return out +} + +// readFrontMatter reads a page's YAML front matter, as a map and as a +// node (which keeps the fields' order, for examples). Pages with TOML or +// JSON front matter come back nil: section pages use YAML. +func readFrontMatter(path string) (map[string]any, *yaml.Node, error) { + raw, err := os.ReadFile(path) + if err != nil { + return nil, nil, err + } + raw = bytes.TrimPrefix(raw, []byte("\ufeff")) + if !bytes.HasPrefix(raw, []byte("---")) { + return nil, nil, nil + } + rest := raw[3:] + if i := bytes.IndexByte(rest, '\n'); i >= 0 { + rest = rest[i+1:] + } + end := bytes.Index(rest, []byte("\n---")) + if end < 0 { + return nil, nil, nil + } + var fm map[string]any + if err := yaml.Unmarshal(rest[:end+1], &fm); err != nil { + return nil, nil, err + } + var node yaml.Node + _ = yaml.Unmarshal(rest[:end+1], &node) + return fm, &node, nil +} + +// sectionNodes are the items of the front matter's sections list. +func sectionNodes(doc *yaml.Node) []*yaml.Node { + if doc == nil || len(doc.Content) == 0 { + return nil + } + m := doc.Content[0] + if m.Kind != yaml.MappingNode { + return nil + } + for i := 0; i+1 < len(m.Content); i += 2 { + if m.Content[i].Value == "sections" && m.Content[i+1].Kind == yaml.SequenceNode { + return m.Content[i+1].Content + } + } + return nil +} + +var tomlTitle = regexp.MustCompile(`(?m)^title\s*=\s*["']([^"']*)["']`) + +// otherTitle reads the title of a page with TOML front matter. +func otherTitle(path string) string { + raw, err := os.ReadFile(path) + if err != nil || !bytes.HasPrefix(raw, []byte("+++")) { + return "" + } + if m := tomlTitle.FindSubmatch(raw); m != nil { + return string(m[1]) + } + return "" +} + +// example is one section as YAML, in its own field order. +func example(n *yaml.Node) string { + raw, err := yaml.Marshal(&yaml.Node{Kind: yaml.SequenceNode, Content: []*yaml.Node{n}}) + if err != nil { + return "" + } + return strings.TrimRight(string(raw), "\n") +} diff --git a/internal/sites/catalog_test.go b/internal/sites/catalog_test.go new file mode 100644 index 0000000..0eaf483 --- /dev/null +++ b/internal/sites/catalog_test.go @@ -0,0 +1,110 @@ +package sites + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +// Files is a small site built from sections, for tests. +var Files = map[string]string{ + "README.md": "# Site\n\n| Type | Fields |\n|---|---|\n| `hero` | `title`, `subhead`, `ctas` |\n\n- `faq` — questions: `items` of `q` + `a`\n", + "layouts/partials/render-sections.html": `{{ range .Params.sections }}{{ if eq .type "hero" }}{{ partial "sections/hero.html" . }}{{ else }}{{ partial "sections/wrapper.html" . }}{{ end }}{{ end }}`, + "layouts/partials/sections/wrapper.html": `
{{ partial (printf "sections/%s.html" .type) . }}
`, + "layouts/partials/sections/head.html": `{{/* the heading: .ignored */}}{{ with .kicker }}

{{ . }}

{{ end }}{{ with .headline }}

{{ . }}

{{ end }}`, + "layouts/partials/sections/ctas.html": `{{ range . }}{{ .label }}{{ end }}`, + "layouts/partials/sections/hero.html": `

{{ .title }}

{{ .subhead }}

{{ partial "sections/ctas.html" .ctas }}`, + "layouts/partials/sections/faq.html": "{{ $s := . }}{{ partial \"sections/head.html\" $s }}{{ range $s.items }}

{{ .q }}

{{ .a }}{{ end }}", + "layouts/partials/sections/stats.html": "{{ $s := . }}{{ range $s.items }}{{ .value }}{{ end }}", + "content/_index.md": "---\ntitle: Home\nsections:\n - type: hero\n title: Hello\n subhead: There\n ctas:\n - label: Start\n url: /start/\n - type: faq\n headline: Questions\n items:\n - q: Why?\n a: Because.\n---\n", + "content/pricing.md": "---\ntitle: Pricing\nsections:\n - type: hero\n title: Prices\n - type: widget\n size: 3\n---\n", + "content/blog/post.md": "+++\ntitle = \"A post\"\n+++\nHello.\n", + "content/notes.md": "---\ntitle: Notes\ndraft: true\n---\nJust text.\n", +} + +func write(t *testing.T, files map[string]string) string { + dir := t.TempDir() + for name, body := range files { + p := filepath.Join(dir, name) + os.MkdirAll(filepath.Dir(p), 0o755) + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + return dir +} + +func path(rel string) string { + rel = strings.TrimSuffix(filepath.ToSlash(rel), ".md") + rel = strings.Trim(strings.TrimSuffix(rel, "_index"), "/") + if rel == "" { + return "/" + } + return "/" + rel + "/" +} + +func TestRead(t *testing.T) { + c, err := Read(write(t, Files), path) + if err != nil { + t.Fatal(err) + } + var names []string + for _, ty := range c.Types { + names = append(names, ty.Name) + } + // Most used first; stats has a layout but no page uses it yet; the + // widget has no layout. + if want := []string{"hero", "faq", "widget", "stats"}; !slices.Equal(names, want) { + t.Errorf("types: %v, want %v", names, want) + } + if want := []string{"ctas", "head", "wrapper"}; !slices.Equal(c.Helpers, want) { + t.Errorf("helpers: %v", c.Helpers) + } + hero := c.Type("hero") + if hero.Uses != 2 || !slices.Equal(hero.Pages, []string{"/", "/pricing/"}) || hero.Doc != "`title`, `subhead`, `ctas`" { + t.Errorf("hero: %+v", hero) + } + if hero.Fields[0].Name != "title" || hero.Fields[0].Count != 2 { + t.Errorf("hero fields: %+v", hero.Fields) + } + for _, f := range hero.Fields { + if f.Name == "ctas" && !slices.Equal(f.Items, []string{"label", "url"}) { + t.Errorf("ctas items: %v", f.Items) + } + } + // ctas is handed .ctas, not the section, so its fields aren't the hero's. + if !slices.Equal(hero.Layout, []string{"ctas", "subhead", "title"}) { + t.Errorf("hero layout: %v", hero.Layout) + } + faq := c.Type("faq") + if faq.Doc != "questions: `items` of `q` + `a`" || !slices.Equal(faq.Layout, []string{"headline", "items", "kicker"}) { + t.Errorf("faq: %+v", faq) + } + if !strings.HasPrefix(faq.Example, "- type: faq\n headline: Questions") || !strings.Contains(faq.Example, "- q: Why?") { + t.Errorf("faq example: %s", faq.Example) + } + if w := c.Type("widget"); !w.Missing || c.Has("widget") || !c.Has("stats") || c.Type("stats").Uses != 0 { + t.Errorf("widget: %+v", w) + } + if len(c.Pages) != 4 || c.Pages[1].Path != "/blog/post/" || c.Pages[1].Title != "A post" { + t.Fatalf("pages: %+v", c.Pages) + } + home := c.Pages[0] + if home.Path != "/" || home.Title != "Home" || !home.Sections || !slices.Equal(home.Types, []string{"hero", "faq"}) || home.File != "content/_index.md" { + t.Errorf("home: %+v", home) + } + for _, p := range c.Pages { + if p.Path == "/notes/" && (!p.Draft || p.Sections) { + t.Errorf("notes: %+v", p) + } + } +} + +func TestReadEmpty(t *testing.T) { + c, err := Read(t.TempDir(), path) + if err != nil || len(c.Types) != 0 || len(c.Pages) != 0 { + t.Errorf("%+v %v", c, err) + } +} diff --git a/internal/web/server.go b/internal/web/server.go index 14a1ba4..1c12c92 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -11,6 +11,7 @@ import ( "net" "net/http" "net/url" + "regexp" "strconv" "strings" "sync" @@ -175,6 +176,8 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("POST /metrics/spend", s.metricsSpendAdd) mux.HandleFunc("POST /metrics/spend/{id}/delete", s.metricsSpendDelete) mux.HandleFunc("POST /metrics/customers/{id}", s.metricsCustomerMatch) + mux.HandleFunc("GET /sites", s.sitesPage) + mux.HandleFunc("POST /sites/sync", s.sitesSync) mux.HandleFunc("GET /seo", s.seoPage) mux.HandleFunc("GET /seo/check", s.seoCheckPage) mux.HandleFunc("GET /seo/engines", s.seoEnginesPage) @@ -284,11 +287,19 @@ func sameOrigin(r *http.Request) bool { return false } +var backticks = regexp.MustCompile("`([^`]+)`") + +// ticks shows Markdown's `code` spans as code, the rest as plain text. +func ticks(s string) template.HTML { + return template.HTML(backticks.ReplaceAllString(template.HTMLEscapeString(s), "$1")) +} + func (s *Server) loadTemplates() error { funcs := template.FuncMap{ "lines": func(v []string) string { return strings.Join(v, "\n") }, "join": strings.Join, "ago": ago, + "ticks": ticks, "add": func(a, b int) int { return a + b }, "hasPrefix": strings.HasPrefix, "sourceLabel": prospects.SourceLabel, @@ -413,7 +424,7 @@ var modules = []module{ {"prospects", "Prospects", "Phase 2", "Test buying signals through the whole funnel, from finding prospects to payment; add the people you approve to EspoCRM through Hermes.", "/signals"}, {"seo", "SEO", "Phase 3", "Run the weekly SEO loop from Search Console: what ranks, what moved, and the changes waiting for your yes, opened as pull requests on your Hugo repositories.", "/seo"}, {"metrics", "Metrics", "Phase 4", "MRR, NRR, CAC and CLV from Stripe, with pipeline influence from EspoCRM.", "/metrics"}, - {"sites", "Sites", "Phase 5", "Build pages and sites from a component library and publish them through Gitea.", ""}, + {"sites", "Sites", "Phase 5", "Build pages from your website's own sections, preview them, and publish them as pull requests on Gitea.", "/sites"}, } // Modules is for the menu. diff --git a/internal/web/server_test.go b/internal/web/server_test.go index fc9dd66..8cf05ec 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -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", + "/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", "/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} { rec := do(h, http.MethodGet, path, nil, nil) if rec.Code != http.StatusOK { diff --git a/internal/web/sites.go b/internal/web/sites.go new file mode 100644 index 0000000..6e661fc --- /dev/null +++ b/internal/web/sites.go @@ -0,0 +1,155 @@ +package web + +import ( + "context" + "net/http" + "path/filepath" + "strconv" + "strings" + "time" + + "supermarket/internal/api/gitea" + "supermarket/internal/hugorepo" + "supermarket/internal/profile" + "supermarket/internal/sites" +) + +// siteRepo is a website with a Hugo repository, from the profile. +type siteRepo struct { + Index int + URL string + Base string // the URL without a trailing slash, for links + Repo string // owner/name + Branch string // as set in the profile; "" for the default + Err string // why the repository can't be read +} + +// siteSynced is what the last sync of a site's working copy found. +type siteSynced struct { + At time.Time `json:"at"` + Branch string `json:"branch"` + Err string `json:"error,omitempty"` +} + +func siteSyncKey(full string) string { return "sites:synced:" + full } + +func (s *Server) siteRepos() []siteRepo { + p, _ := profile.Load(s.DB) + if p == nil { + return nil + } + var out []siteRepo + for i, w := range p.Websites { + sr := siteRepo{Index: i, URL: w.URL, Base: strings.TrimRight(w.URL, "/"), Branch: w.Branch} + if w.Repo == "" { + sr.Err = "no Hugo repository set" + } else if _, full, err := gitea.ParseRepo(w.Repo); err != nil { + sr.Err = err.Error() + } else { + sr.Repo = full + } + out = append(out, sr) + } + return out +} + +func (s *Server) siteDir(full string) string { + return filepath.Join(s.DataDir, "sites", strings.ReplaceAll(full, "/", "__")) +} + +func (s *Server) currentSite(r *http.Request) ([]siteRepo, *siteRepo) { + all := s.siteRepos() + want, err := strconv.Atoi(r.URL.Query().Get("site")) + if err != nil { + want, err = strconv.Atoi(r.PostFormValue("site")) + } + for i := range all { + if err == nil && all[i].Index == want { + return all, &all[i] + } + } + for i := range all { + if all[i].Repo != "" { + return all, &all[i] + } + } + return all, nil +} + +func (s *Server) sitesPage(w http.ResponseWriter, r *http.Request) { + s.renderSites(w, r, "") +} + +func (s *Server) renderSites(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, "Synced": siteSynced{}} + if cur != nil && cur.Repo != "" { + var synced siteSynced + if ok, _ := s.DB.GetJSON(siteSyncKey(cur.Repo), &synced); ok { + data["Synced"], data["HasSynced"] = synced, true + if !synced.At.IsZero() { + wc := &hugorepo.Repo{Dir: s.siteDir(cur.Repo), Branch: synced.Branch} + wc.Acquire() + cat, err := sites.Read(wc.Dir, wc.PathOf) + if err == nil { + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + data["Commits"], _ = wc.Log(ctx, 8) + cancel() + } + wc.Release() + if err != nil { + errMsg = "Couldn't read the working copy: " + err.Error() + } else { + data["Catalog"] = cat + data["SectionPages"], data["OtherPages"] = splitPages(cat.Pages) + } + } + } + } + s.render(w, r, "sites", page{Title: "Sites", Nav: "sites/site", Error: errMsg, Data: data}) +} + +func splitPages(ps []sites.Page) (withSections, other []sites.Page) { + for _, p := range ps { + if p.Sections { + withSections = append(withSections, p) + } else { + other = append(other, p) + } + } + return +} + +// sitesSync brings the site's working copy up to date with its published +// branch. +func (s *Server) sitesSync(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, "Set this website's Hugo repository in Settings → Profile first.") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute) + defer cancel() + ap := s.applier(seoSite{Index: cur.Index, URL: cur.URL}) + synced := siteSynced{At: time.Now()} + wc, _, branch, err := ap.WorkingCopy(ctx) + if err != nil { + var old siteSynced + if ok, _ := s.DB.GetJSON(siteSyncKey(cur.Repo), &old); ok { + synced = old // keep showing the last good copy + } + synced.Err = err.Error() + } else { + wc.Release() + synced.Branch = branch + } + if err := s.DB.PutJSON(siteSyncKey(cur.Repo), synced); err != nil { + s.serverError(w, err) + return + } + http.Redirect(w, r, "/sites?site="+strconv.Itoa(cur.Index), http.StatusSeeOther) +} diff --git a/internal/web/sites_test.go b/internal/web/sites_test.go new file mode 100644 index 0000000..d2d6ab1 --- /dev/null +++ b/internal/web/sites_test.go @@ -0,0 +1,66 @@ +package web + +import ( + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "supermarket/internal/hugorepo/hugotest" + "supermarket/internal/profile" + "supermarket/internal/secrets" +) + +func TestSitesPage(t *testing.T) { + clone := hugotest.Site(t, map[string]string{ + "README.md": "| `hero` | `title`, `subhead` |\n", + "layouts/partials/sections/hero.html": `

{{ .title }}

{{ .subhead }}

`, + "layouts/partials/sections/faq.html": "{{ $s := . }}{{ range $s.items }}{{ .q }}{{ end }}", + "content/landing.md": "---\ntitle: Landing\nsections:\n - type: hero\n title: Hello\n subhead: There\n - type: gizmo\n---\n", + }) + 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) + + if body := do(h, http.MethodGet, "/sites", nil, nil).Body.String(); !strings.Contains(body, "Add your website") { + t.Errorf("no sites: %s", body) + } + profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: "https://us.example/", Repo: "Us/site"}}}) + body := do(h, http.MethodGet, "/sites", nil, nil).Body.String() + if !strings.Contains(body, "Not read yet") || !strings.Contains(body, "disabled") { + t.Errorf("before reading: %s", body) + } + postForm(h, "/settings/search", url.Values{"gitea_url": {g.URL}, secrets.GiteaToken: {"tok"}}) + if rec := postForm(h, "/sites/sync", url.Values{"site": {"0"}}); rec.Code != http.StatusSeeOther { + t.Fatalf("sync: %d %s", rec.Code, rec.Body.String()) + } + body = do(h, http.MethodGet, "/sites?site=0", nil, nil).Body.String() + for _, want := range []string{"Read from the repository", "branch main", "init", // the commit + "hero", "1 use on 1 page", "The README says: title, subhead", + "faq", "not used yet", "gizmo", "no layout", + `href="https://us.example/landing/"`, "hero · gizmo", "- type: hero\n title: Hello", + "other pages, written in Markdown", "First post"} { + if !strings.Contains(body, want) { + t.Errorf("missing %q in %s", want, body) + } + } + if strings.Contains(body, "error-text") { + t.Errorf("an error: %s", body) + } + + // A failed read keeps the last good copy and says why. + g.Close() + postForm(h, "/sites/sync", url.Values{"site": {"0"}}) + body = do(h, http.MethodGet, "/sites", nil, nil).Body.String() + if !strings.Contains(body, "The last read failed") || !strings.Contains(body, "hero") { + t.Errorf("after a failed read: %s", body) + } +} diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 5898946..8d88996 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -59,6 +59,11 @@ Publish {{end}} + {{if eq .ID "sites"}} + + {{end}} {{if eq .ID "prospects"}}