Phase 6 part 5, step 2: start a new site
Sites → New site fills an empty Gitea repository with the theme, a hugo.toml in the site's brand and a starter home page: checked that the repository is empty and builds with Hugo, then the first commit is pushed to its default branch. The site joins the profile, and a First pages card builds its Home, About, Contact and product pages with the page builder; About and Contact join the top menu. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -8,6 +8,7 @@ import (
|
||||
"os"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -235,6 +236,9 @@ Rules:
|
||||
out.Path = in.Path
|
||||
}
|
||||
out.Path = CleanPath(out.Path)
|
||||
if in.Kind == "home" {
|
||||
out.Path = "/"
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
@@ -462,6 +466,12 @@ func tag(link, campaign, content string) string {
|
||||
// FrontMatter is a page's content file: YAML front matter with its title,
|
||||
// description and sections, and no body.
|
||||
func FrontMatter(title, description, sectionsYAML string) (string, error) {
|
||||
return frontMatter(title, description, sectionsYAML, "", 0)
|
||||
}
|
||||
|
||||
// frontMatter is FrontMatter, with the page in a menu at weight when menu
|
||||
// isn't "".
|
||||
func frontMatter(title, description, sectionsYAML, menu string, weight int) (string, error) {
|
||||
var secs yaml.Node
|
||||
if err := yaml.Unmarshal([]byte(sectionsYAML), &secs); err != nil || len(secs.Content) == 0 {
|
||||
return "", errors.New("the sections aren't valid YAML")
|
||||
@@ -473,6 +483,11 @@ func FrontMatter(title, description, sectionsYAML string) (string, error) {
|
||||
str("date"), str(time.Now().Format("2006-01-02")),
|
||||
str("sections"), secs.Content[0],
|
||||
}}
|
||||
if menu != "" {
|
||||
m.Content = append(m.Content[:6], append([]*yaml.Node{str("menus"), {Kind: yaml.MappingNode, Content: []*yaml.Node{
|
||||
str(menu), {Kind: yaml.MappingNode, Content: []*yaml.Node{str("weight"), {Kind: yaml.ScalarNode, Tag: "!!int", Value: strconv.Itoa(weight)}}},
|
||||
}}}, m.Content[6:]...)...)
|
||||
}
|
||||
var b strings.Builder
|
||||
enc := yaml.NewEncoder(&b)
|
||||
enc.SetIndent(2)
|
||||
@@ -489,7 +504,10 @@ func FrontMatter(title, description, sectionsYAML string) (string, error) {
|
||||
// with a build, and opens a pull request if pr is set and none is open.
|
||||
// The page must have been checked and its claims confirmed.
|
||||
func Push(ctx context.Context, d *db.DB, ap *seo.Applier, p *SitePage, pr bool) error {
|
||||
if strings.TrimSpace(p.Title) == "" || p.Path == "" || p.Path == "/" {
|
||||
if p.Kind == "home" {
|
||||
p.Path = "/"
|
||||
}
|
||||
if strings.TrimSpace(p.Title) == "" || p.Path == "" || (p.Path == "/" && p.Kind != "home") {
|
||||
return errors.New("give the page a title and an address")
|
||||
}
|
||||
p.Status, p.Error = PageWorking, ""
|
||||
@@ -516,6 +534,14 @@ func push(ctx context.Context, ap *seo.Applier, p *SitePage, pr bool) error {
|
||||
return err
|
||||
}
|
||||
defer wc.Release()
|
||||
if p.File == "" && p.Kind == "home" {
|
||||
// The home page replaces the site's own.
|
||||
file, err := wc.FindContent("/")
|
||||
if err != nil {
|
||||
file = "content/_index.md"
|
||||
}
|
||||
p.File = file
|
||||
}
|
||||
if p.File == "" {
|
||||
if file, err := wc.FindContent(p.Path); err == nil {
|
||||
return fmt.Errorf("the site already has a page at %s (%s): choose another address", p.Path, file)
|
||||
@@ -526,7 +552,11 @@ func push(ctx context.Context, ap *seo.Applier, p *SitePage, pr bool) error {
|
||||
if err := wc.NewBranch(ctx, p.Branch); err != nil {
|
||||
return err
|
||||
}
|
||||
body, err := FrontMatter(p.Title, p.Description, p.Sections)
|
||||
menu := ""
|
||||
if menuWeight(p.Kind) > 0 {
|
||||
menu = "main"
|
||||
}
|
||||
body, err := frontMatter(p.Title, p.Description, p.Sections, menu, menuWeight(p.Kind))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
package sites
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"supermarket/internal/api/gitea"
|
||||
"supermarket/internal/hugorepo"
|
||||
"supermarket/internal/theme"
|
||||
)
|
||||
|
||||
// NewSite is what a new site starts from.
|
||||
type NewSite struct {
|
||||
Repo string // owner/name: an empty repository the user made
|
||||
URL string // where it will be published, https://…
|
||||
Title string
|
||||
Tagline string
|
||||
Email string // where lead forms send while they aren't connected
|
||||
Dark string // #rrggbb
|
||||
Primary string
|
||||
Accent string
|
||||
Font string // a Google Fonts family
|
||||
Logo string // an image's address, or ""
|
||||
}
|
||||
|
||||
var (
|
||||
hexColor = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
|
||||
fontName = regexp.MustCompile(`^[A-Za-z0-9 ]{2,40}$`)
|
||||
)
|
||||
|
||||
// Fonts are offered for a new site (any Google Fonts family works).
|
||||
var Fonts = []string{"Inter", "IBM Plex Sans", "Manrope", "DM Sans", "Source Sans 3", "Work Sans", "Lato", "Merriweather Sans"}
|
||||
|
||||
// Defaults are the theme's own brand: Federated Computer's.
|
||||
func Defaults() NewSite {
|
||||
return NewSite{Dark: "#001a2b", Primary: "#e0ff4f", Accent: "#614efa", Font: "Inter"}
|
||||
}
|
||||
|
||||
// Check checks a new site's settings and tidies them.
|
||||
func (n *NewSite) Check() error {
|
||||
n.Repo, n.URL, n.Title = strings.TrimSpace(n.Repo), strings.TrimRight(strings.TrimSpace(n.URL), "/"), strings.TrimSpace(n.Title)
|
||||
n.Tagline, n.Email, n.Logo = strings.TrimSpace(n.Tagline), strings.TrimSpace(n.Email), strings.TrimSpace(n.Logo)
|
||||
if _, full, err := gitea.ParseRepo(n.Repo); err != nil {
|
||||
return fmt.Errorf("the repository: %v", err)
|
||||
} else {
|
||||
n.Repo = full
|
||||
}
|
||||
if u, err := url.Parse(n.URL); err != nil || u.Scheme != "https" || u.Host == "" || (u.Path != "" && u.Path != "/") {
|
||||
return errors.New("the site's address must be like https://www.example.com")
|
||||
}
|
||||
if n.Title == "" {
|
||||
return errors.New("give the site a name")
|
||||
}
|
||||
for _, v := range []string{n.Title, n.Tagline, n.Email, n.Logo} {
|
||||
if strings.ContainsFunc(v, unicode.IsControl) {
|
||||
return errors.New("the name, tagline, email and logo can't contain line breaks or tabs")
|
||||
}
|
||||
}
|
||||
if n.Email != "" && !strings.Contains(n.Email, "@") {
|
||||
return errors.New("that isn't an email address")
|
||||
}
|
||||
for _, c := range []*string{&n.Dark, &n.Primary, &n.Accent} {
|
||||
*c = strings.TrimSpace(*c)
|
||||
if !hexColor.MatchString(*c) {
|
||||
return fmt.Errorf("%q isn't a color like #1d1238", *c)
|
||||
}
|
||||
}
|
||||
n.Font = strings.TrimSpace(n.Font)
|
||||
if !fontName.MatchString(n.Font) {
|
||||
return errors.New("the font must be a Google Fonts family, like Inter")
|
||||
}
|
||||
if n.Logo != "" {
|
||||
if u, err := url.Parse(n.Logo); err != nil || (u.Scheme != "https" && !strings.HasPrefix(n.Logo, "/")) {
|
||||
return errors.New("the logo must be an https:// address, or a path on the site like /images/logo.svg")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func q(s string) string { return strconv.Quote(s) }
|
||||
|
||||
// Files are the new site's first commit: the theme, hugo.toml, a starter
|
||||
// home page, a README and a .gitignore.
|
||||
func (n NewSite) Files() map[string]string {
|
||||
files := map[string]string{}
|
||||
for p, body := range theme.Files() {
|
||||
files[theme.Dir+"/"+p] = body
|
||||
}
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "baseURL = %s\nlanguageCode = \"en-us\"\ntitle = %s\ntheme = %s\n", q(n.URL+"/"), q(n.Title), q(theme.Name))
|
||||
b.WriteString("disableKinds = [\"taxonomy\", \"term\"]\n\n[params]\n")
|
||||
fmt.Fprintf(&b, " tagline = %s\n\n[params.brand]\n", q(n.Tagline))
|
||||
fmt.Fprintf(&b, " dark = %s\n primary = %s\n accent = %s\n font = %s\n", q(n.Dark), q(n.Primary), q(n.Accent), q(n.Font))
|
||||
if n.Logo != "" {
|
||||
fmt.Fprintf(&b, " logo = %s\n", q(n.Logo))
|
||||
}
|
||||
b.WriteString("\n[params.header]\n ctas = [{ label = \"Contact us\", url = \"/contact/\", style = \"primary\" }]\n")
|
||||
fmt.Fprintf(&b, "\n[params.footer]\n tagline = %s\n groups = [{ title = \"Company\", menu = \"footer_company\" }]\n", q(n.Tagline))
|
||||
b.WriteString("\n# Where the lead forms post: EspoCRM's Lead Capture (Supermarket → Sites → Lead forms).\n")
|
||||
fmt.Fprintf(&b, "[params.leads]\n action = \"\"\n email = %s\n", q(n.Email))
|
||||
b.WriteString("\n[[menu.main]]\n name = \"Home\"\n url = \"/\"\n weight = 1\n")
|
||||
files["hugo.toml"] = b.String()
|
||||
|
||||
tagline := n.Tagline
|
||||
if tagline == "" {
|
||||
tagline = "Welcome."
|
||||
}
|
||||
files["content/_index.md"] = fmt.Sprintf(`---
|
||||
title: %s
|
||||
description: %s
|
||||
sections:
|
||||
- type: hero
|
||||
title: %s
|
||||
subhead: %s
|
||||
ctas:
|
||||
- label: "Contact us"
|
||||
url: "/contact/"
|
||||
style: primary
|
||||
- type: final-cta
|
||||
headline: "Talk to us"
|
||||
body: "Tell us what you need, and we'll get back to you."
|
||||
ctas:
|
||||
- label: "Contact us"
|
||||
url: "/contact/"
|
||||
style: primary
|
||||
---
|
||||
`, q(n.Title), q(tagline), q(n.Title), q(tagline))
|
||||
files["README.md"] = fmt.Sprintf(`# %s
|
||||
|
||||
The website at %s, a [Hugo](https://gohugo.io/) site made with
|
||||
Supermarket's theme (`+"`themes/supermarket`"+`; its README lists the section
|
||||
types and the settings in `+"`hugo.toml`"+`).
|
||||
|
||||
Pages are in `+"`content/`"+`: each page's front matter has a `+"`sections:`"+` list.
|
||||
Supermarket changes the site through pull requests; merging publishes.
|
||||
Run `+"`hugo server`"+` to see it locally.
|
||||
`, n.Title, n.URL)
|
||||
files[".gitignore"] = "/public/\n/resources/_gen/\n.hugo_build.lock\n"
|
||||
return files
|
||||
}
|
||||
|
||||
// Create makes the site: it checks the repository is empty and Supermarket
|
||||
// may push to it, builds the files with Hugo (when there is one) so nothing
|
||||
// broken is pushed, then makes the first commit on the default branch and
|
||||
// leaves the working copy at dir. It returns the branch.
|
||||
func Create(ctx context.Context, g *gitea.Client, n NewSite, dir, author string) (string, error) {
|
||||
if err := n.Check(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if g == nil {
|
||||
return "", errors.New("save a Gitea token under Settings → Search engines first")
|
||||
}
|
||||
repo, err := g.GetRepo(ctx, n.Repo)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("couldn't read %s on Gitea (create it first, empty): %w", n.Repo, err)
|
||||
}
|
||||
if !repo.Permissions.Push {
|
||||
return "", fmt.Errorf("the Gitea token can't push to %s", n.Repo)
|
||||
}
|
||||
if !repo.Empty {
|
||||
return "", fmt.Errorf("%s isn't empty: Supermarket only starts sites in an empty repository (create it without a README or license)", n.Repo)
|
||||
}
|
||||
branch := repo.DefaultBranch
|
||||
if branch == "" {
|
||||
branch = "main"
|
||||
}
|
||||
files := n.Files()
|
||||
if hugorepo.HugoVersion(ctx) != "" {
|
||||
tmp, err := os.MkdirTemp("", "supermarket-newsite-")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer os.RemoveAll(tmp)
|
||||
for rel, body := range files {
|
||||
p := filepath.Join(tmp, rel)
|
||||
os.MkdirAll(filepath.Dir(p), 0o755)
|
||||
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
out, err := hugorepo.BuildDir(ctx, tmp)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("the new site wouldn't build: %w", err)
|
||||
}
|
||||
os.RemoveAll(out)
|
||||
}
|
||||
wc := &hugorepo.Repo{Dir: dir, CloneURL: repo.CloneURL, Token: g.Token(), Branch: branch, Author: author}
|
||||
wc.Acquire()
|
||||
defer wc.Release()
|
||||
if _, err := os.Stat(dir); err == nil {
|
||||
// A copy left from before (an earlier attempt): the repository is
|
||||
// empty, so there's nothing in it to keep.
|
||||
if err := os.RemoveAll(dir); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if err := hugorepo.InitPush(ctx, wc, files, "Start the site with Supermarket's theme"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return branch, nil
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package sites
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"supermarket/internal/hugorepo"
|
||||
)
|
||||
|
||||
func TestNewSiteFiles(t *testing.T) {
|
||||
n := Defaults()
|
||||
n.Repo, n.URL, n.Title, n.Tagline, n.Email = " https://gitea.example/Us/acme.git ", "https://www.acme.example/", `Acme "Widgets" & Co`, "Wïdgets, for everyone", "hi@acme.example"
|
||||
if err := n.Check(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n.Repo != "Us/acme" || n.URL != "https://www.acme.example" {
|
||||
t.Errorf("tidied: %+v", n)
|
||||
}
|
||||
f := n.Files()
|
||||
if !strings.Contains(f["hugo.toml"], `title = "Acme \"Widgets\" & Co"`) {
|
||||
t.Errorf("hugo.toml:\n%s", f["hugo.toml"])
|
||||
}
|
||||
// Hugo reads the settings and builds the site, the title as given.
|
||||
if _, err := exec.LookPath("hugo"); err == nil {
|
||||
dir := t.TempDir()
|
||||
for rel, body := range f {
|
||||
os.MkdirAll(filepath.Join(dir, filepath.Dir(rel)), 0o755)
|
||||
os.WriteFile(filepath.Join(dir, rel), []byte(body), 0o644)
|
||||
}
|
||||
out, err := hugorepo.BuildDir(context.Background(), dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(out)
|
||||
home, _ := os.ReadFile(filepath.Join(out, "index.html"))
|
||||
if !strings.Contains(string(home), "<title>Acme "Widgets" & Co — Wïdgets, for everyone</title>") {
|
||||
t.Errorf("built home: %.600s", home)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(f["content/_index.md"], `title: "Acme \"Widgets\" & Co"`) || f["themes/supermarket/VERSION"] != "1\n" {
|
||||
t.Errorf("home: %s", f["content/_index.md"])
|
||||
}
|
||||
for _, bad := range []NewSite{{Title: "x\ny"}, {Dark: "red"}, {Font: "Comic<Sans>"}, {Logo: "javascript:alert(1)"}, {URL: "https://x.example/path"}} {
|
||||
m := Defaults()
|
||||
m.Repo, m.URL, m.Title = "Us/acme", "https://acme.example", "Acme"
|
||||
if bad.Title != "" {
|
||||
m.Title = bad.Title
|
||||
}
|
||||
if bad.Dark != "" {
|
||||
m.Dark = bad.Dark
|
||||
}
|
||||
if bad.Font != "" {
|
||||
m.Font = bad.Font
|
||||
}
|
||||
if bad.Logo != "" {
|
||||
m.Logo = bad.Logo
|
||||
}
|
||||
if bad.URL != "" {
|
||||
m.URL = bad.URL
|
||||
}
|
||||
if err := m.Check(); err == nil {
|
||||
t.Errorf("accepted %+v", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,23 @@ var Kinds = []struct{ ID, Label, Guide string }{
|
||||
"A side-by-side \"<us> vs <competitor>\" page: a short verdict, a comparison table, who each one is best for (honestly, including when the competitor fits better), an FAQ, a call to action. Say only what you're given about the competitor."},
|
||||
{"blog", "Blog post",
|
||||
"A blog post that teaches something useful to our customers, mostly text sections, ending with one call to action."},
|
||||
{"home", "Home page",
|
||||
"The site's home page (it replaces the current one): what the company does and for whom in the hero, its products or services, why choose it, proof it really has, and a call to action, ending with the closing band."},
|
||||
{"about", "About page",
|
||||
"An about page: who the company is, what it believes, how it works, where it is; only facts given here. It joins the top menu."},
|
||||
{"contact", "Contact page",
|
||||
"A contact page built around the site's lead form (the form section): a short heading, what happens after someone writes, the form with name, email, organization and a message, and other ways to reach the company. It joins the top menu."},
|
||||
}
|
||||
|
||||
// menuWeight is where a kind of page goes in the top menu (0: not in it).
|
||||
func menuWeight(kind string) int {
|
||||
switch kind {
|
||||
case "about":
|
||||
return 80
|
||||
case "contact":
|
||||
return 90
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// KindLabel is a kind's name for people.
|
||||
|
||||
Reference in New Issue
Block a user