// Package hugorepo works on a Hugo website's Git repository: a working // copy kept under the data folder, finding the content file behind a page, // editing its front matter, building the site to check a change, and // pushing a branch. It never pushes to the branch that gets published. package hugorepo import ( "bufio" "bytes" "context" "errors" "fmt" "io/fs" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" "sync" "time" "golang.org/x/net/html" ) // Repo is a working copy. type Repo struct { Dir string // the working copy CloneURL string // https://…/owner/name.git Token string // sent as a header, never stored in the copy Branch string // the branch that gets published 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 // header so it never lands in .git/config. func (r *Repo) git(ctx context.Context, args ...string) (string, error) { full := []string{"-c", "http.extraHeader=Authorization: token " + r.Token, "-c", "credential.helper="} if name, email, ok := splitAuthor(r.Author); ok { full = append(full, "-c", "user.name="+name, "-c", "user.email="+email) } full = append(full, args...) cmd := exec.CommandContext(ctx, "git", full...) cmd.Dir = r.Dir cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0", "GIT_ASKPASS=true") out, err := cmd.CombinedOutput() if err != nil { msg := strings.TrimSpace(strings.ReplaceAll(string(out), r.Token, "***")) return msg, fmt.Errorf("git %s: %s", args[0], firstLine(msg)) } return string(out), nil } func firstLine(s string) string { for _, l := range strings.Split(s, "\n") { if l = strings.TrimSpace(l); l != "" && !strings.HasPrefix(l, "hint:") { return l } } return s } func splitAuthor(a string) (name, email string, ok bool) { i, j := strings.Index(a, "<"), strings.Index(a, ">") if i < 0 || j < i { return "", "", false } return strings.TrimSpace(a[:i]), a[i+1 : j], true } // Sync makes the working copy a clean copy of the published branch: a // clone the first time, a fetch and hard reset after that. func (r *Repo) Sync(ctx context.Context) error { if _, err := os.Stat(filepath.Join(r.Dir, ".git")); errors.Is(err, fs.ErrNotExist) { if err := os.MkdirAll(filepath.Dir(r.Dir), 0o755); err != nil { return err } parent := &Repo{Dir: filepath.Dir(r.Dir), Token: r.Token} if _, err := parent.git(ctx, "clone", "--quiet", "--branch", r.Branch, r.CloneURL, filepath.Base(r.Dir)); err != nil { return err } _, err := r.git(ctx, "submodule", "update", "--init", "--recursive", "--quiet") return err } for _, args := range [][]string{ {"fetch", "--quiet", "--prune", "origin"}, {"checkout", "--quiet", "--force", r.Branch}, {"reset", "--quiet", "--hard", "origin/" + r.Branch}, {"clean", "-fdq"}, {"submodule", "update", "--init", "--recursive", "--quiet"}, } { if _, err := r.git(ctx, args...); err != nil { return err } } return nil } // Branch starts a new branch from the published one. func (r *Repo) NewBranch(ctx context.Context, name string) error { _, err := r.git(ctx, "checkout", "--quiet", "-B", name, "origin/"+r.Branch) return err } // Diff is the working copy's uncommitted change, new files included. func (r *Repo) Diff(ctx context.Context) (string, error) { if _, err := r.git(ctx, append([]string{"add", "-A", "--intent-to-add", "content"}, r.touched...)...); err != nil { return "", err } return r.git(ctx, "diff") } // CommitAndPush commits everything changed and pushes the current branch. func (r *Repo) CommitAndPush(ctx context.Context, branch, message string) error { if _, err := r.git(ctx, append([]string{"add", "-A", "content"}, r.touched...)...); err != nil { return err } if _, err := r.git(ctx, "commit", "--quiet", "-am", message); err != nil { return err } _, err := r.git(ctx, "push", "--quiet", "--force", "origin", "HEAD:refs/heads/"+branch) return err } // --- Finding a page's file --- var contentExts = map[string]bool{".md": true, ".markdown": true, ".html": true, ".htm": true} // FindContent returns the content file (relative to the repository) that // makes a page, from its path ("/blog/post/"). It understands index.md and // _index.md, and url and slug in front matter. func (r *Repo) FindContent(pagePath string) (string, error) { want := cleanPath(pagePath) root := filepath.Join(r.Dir, "content") var found []string err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { if err != nil || d.IsDir() || !contentExts[strings.ToLower(filepath.Ext(p))] { return err } rel, _ := filepath.Rel(root, p) for _, u := range urlsFor(rel, p) { if u == want { found = append(found, filepath.ToSlash(filepath.Join("content", rel))) break } } return nil }) if err != nil { return "", fmt.Errorf("reading the content folder: %w", err) } switch len(found) { case 0: return "", fmt.Errorf("no content file makes %s", want) case 1: return found[0], nil } return "", fmt.Errorf("several content files could make %s: %s", want, strings.Join(found, ", ")) } func cleanPath(p string) string { p = "/" + strings.Trim(strings.ToLower(p), "/") + "/" if p == "//" { return "/" } 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. func urlsFor(rel, full string) []string { rel = filepath.ToSlash(rel) dir, file := filepath.Split(rel) base := strings.TrimSuffix(file, filepath.Ext(file)) var p string if base == "index" || base == "_index" { p = dir } else { p = dir + base } out := []string{cleanPath(urlize(p))} if parts := strings.SplitN(strings.Trim(p, "/"), "/", 2); len(parts[0]) == 2 { rest := "" if len(parts) == 2 { rest = parts[1] } out = append(out, cleanPath(urlize(rest))) } fm := frontMatter(full) if u := fm["url"]; u != "" { out = append(out, cleanPath(u)) } if s := fm["slug"]; s != "" && base != "_index" { out = append(out, cleanPath(urlize(dir+s))) } return out } var spaces = regexp.MustCompile(`\s+`) // urlize does what Hugo does to a path: lower case, spaces to hyphens. func urlize(p string) string { return spaces.ReplaceAllString(strings.ToLower(p), "-") } // frontMatter reads a file's simple front matter keys (title, url, slug, // description), YAML or TOML. func frontMatter(path string) map[string]string { out := map[string]string{} f, err := os.Open(path) if err != nil { return out } defer f.Close() sc := bufio.NewScanner(f) sc.Buffer(make([]byte, 64<<10), 1<<20) if !sc.Scan() { return out } delim := strings.TrimSpace(sc.Text()) if delim != "---" && delim != "+++" { return out } sep := ":" if delim == "+++" { sep = "=" } for sc.Scan() { line := sc.Text() if strings.TrimSpace(line) == delim { break } if strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") { continue } k, v, ok := strings.Cut(line, sep) if !ok { continue } out[strings.ToLower(strings.TrimSpace(k))] = unquote(strings.TrimSpace(v)) } return out } func unquote(v string) string { if len(v) >= 2 && (v[0] == '"' && v[len(v)-1] == '"') { if s, err := strconv.Unquote(v); err == nil { return s } } if len(v) >= 2 && v[0] == '\'' && v[len(v)-1] == '\'' { return strings.ReplaceAll(v[1:len(v)-1], "''", "'") } return v } // FrontMatterValue reads one front matter key of a content file. func (r *Repo) FrontMatterValue(rel, key string) string { return frontMatter(filepath.Join(r.Dir, rel))[strings.ToLower(key)] } // SetFrontMatter sets a top-level front matter key, YAML or TOML, adding // it if it isn't there. func (r *Repo) SetFrontMatter(rel, key, value string) error { path := filepath.Join(r.Dir, rel) raw, err := os.ReadFile(path) if err != nil { return err } lines := strings.Split(string(raw), "\n") if len(lines) == 0 { return errors.New(rel + " is empty") } delim := strings.TrimSpace(lines[0]) var line string switch delim { case "---": line = key + ": " + strconv.Quote(value) case "+++": line = key + " = " + strconv.Quote(value) default: return fmt.Errorf("%s has no YAML or TOML front matter", rel) } sep := map[string]string{"---": ":", "+++": "="}[delim] end := -1 for i := 1; i < len(lines); i++ { if strings.TrimSpace(lines[i]) == delim { end = i break } } if end < 0 { return fmt.Errorf("%s's front matter doesn't end", rel) } done := false for i := 1; i < end; i++ { k, _, ok := strings.Cut(lines[i], sep) if ok && !strings.HasPrefix(lines[i], " ") && strings.EqualFold(strings.TrimSpace(k), key) { lines[i] = line // A YAML block value (key: | or >) continues on indented lines. for i+1 < end && (strings.HasPrefix(lines[i+1], " ") || strings.HasPrefix(lines[i+1], "\t")) { lines = append(lines[:i+1], lines[i+2:]...) end-- } done = true break } } if !done { lines = append(lines[:end], append([]string{line}, lines[end:]...)...) } return os.WriteFile(path, []byte(strings.Join(lines, "\n")), 0o644) } // --- Building --- // HugoVersion is the Hugo in the image, or "" if there's none. func HugoVersion(ctx context.Context) string { out, err := exec.CommandContext(ctx, "hugo", "version").Output() if err != nil { return "" } return strings.TrimSpace(string(out)) } // Build builds the site into a temporary folder, returned for reading; // the caller removes it. func (r *Repo) Build(ctx context.Context) (string, error) { out, err := os.MkdirTemp("", "supermarket-hugo-") if err != nil { return "", err } ctx, cancel := context.WithTimeout(ctx, 5*time.Minute) defer cancel() cmd := exec.CommandContext(ctx, "hugo", "--quiet", "--destination", out, "--cleanDestinationDir") cmd.Dir = r.Dir var buf bytes.Buffer 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", hugoError(buf.String())) } return out, nil } // BuiltHead reads the title and meta description a built page has. func BuiltHead(outDir, pagePath string) (title, description string, err error) { p := strings.Trim(pagePath, "/") candidates := []string{filepath.Join(outDir, p, "index.html"), filepath.Join(outDir, p+".html")} var raw []byte for _, c := range candidates { if raw, err = os.ReadFile(c); err == nil { break } } if err != nil { return "", "", fmt.Errorf("the build has no page at %s", pagePath) } doc, err := html.Parse(bytes.NewReader(raw)) if err != nil { return "", "", err } var walk func(*html.Node) walk = func(n *html.Node) { if n.Type == html.ElementNode { switch n.Data { case "title": if title == "" && n.FirstChild != nil { title = strings.Join(strings.Fields(n.FirstChild.Data), " ") } case "meta": var name, content string for _, a := range n.Attr { switch strings.ToLower(a.Key) { case "name": name = strings.ToLower(a.Val) case "content": content = a.Val } } if name == "description" && description == "" { description = strings.Join(strings.Fields(content), " ") } } } for c := n.FirstChild; c != nil; c = c.NextSibling { walk(c) } } walk(doc) return title, description, nil } // --- Writing pages --- // Field is a front matter key and value. type Field struct{ Key, Value string } // NewPage writes a new content file with YAML front matter. It refuses to // overwrite a file that exists. func (r *Repo) NewPage(rel string, fields []Field, body string) error { path := filepath.Join(r.Dir, rel) if !strings.HasPrefix(filepath.Clean(path), filepath.Clean(filepath.Join(r.Dir, "content"))+string(filepath.Separator)) { return fmt.Errorf("%s isn't in the content folder", rel) } if _, err := os.Stat(path); err == nil { return fmt.Errorf("%s already exists", rel) } if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return err } var b strings.Builder b.WriteString("---\n") for _, f := range fields { b.WriteString(f.Key + ": " + strconv.Quote(f.Value) + "\n") } b.WriteString("---\n\n") b.WriteString(strings.TrimSpace(body) + "\n") return os.WriteFile(path, []byte(b.String()), 0o644) } // ReplaceBody keeps a content file's front matter and replaces what follows. func (r *Repo) ReplaceBody(rel, body string) error { path := filepath.Join(r.Dir, rel) raw, err := os.ReadFile(path) if err != nil { return err } lines := strings.Split(string(raw), "\n") delim := strings.TrimSpace(lines[0]) if delim != "---" && delim != "+++" { return fmt.Errorf("%s has no YAML or TOML front matter", rel) } end := -1 for i := 1; i < len(lines); i++ { if strings.TrimSpace(lines[i]) == delim { end = i break } } if end < 0 { return fmt.Errorf("%s's front matter doesn't end", rel) } out := strings.Join(lines[:end+1], "\n") + "\n\n" + strings.TrimSpace(body) + "\n" return os.WriteFile(path, []byte(out), 0o644) } // --- Files outside content --- // inside resolves a path in the repository, refusing ones that leave it. func (r *Repo) inside(rel string) (string, error) { p := filepath.Clean(filepath.Join(r.Dir, rel)) if !strings.HasPrefix(p, filepath.Clean(r.Dir)+string(filepath.Separator)) { return "", fmt.Errorf("%s is outside the repository", rel) } return p, nil } // Exists reports whether a file is in the working copy. func (r *Repo) Exists(rel string) bool { p, err := r.inside(rel) if err != nil { return false } _, err = os.Stat(p) return err == nil } // WriteFile writes a file anywhere in the repository and marks it to be // committed. func (r *Repo) WriteFile(rel, content string) error { p, err := r.inside(rel) if err != nil { return err } if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { return err } if err := os.WriteFile(p, []byte(content), 0o644); err != nil { return err } r.touched = append(r.touched, filepath.ToSlash(rel)) return nil } // ConfigFile is the site's main Hugo configuration file, or "". func (r *Repo) ConfigFile() string { for _, name := range []string{"hugo.toml", "hugo.yaml", "hugo.yml", "config.toml", "config.yaml", "config.yml", "config/_default/hugo.toml", "config/_default/hugo.yaml", "config/_default/config.toml", "config/_default/config.yaml"} { if r.Exists(name) { return name } } return "" } var disableKinds = regexp.MustCompile(`(?m)^(\s*disableKinds\s*[:=]\s*\[)([^\]]*)(\])`) // EnableSitemap takes "sitemap" out of the config's disableKinds, when it's // written on one line. It reports whether it changed anything. func (r *Repo) EnableSitemap() (bool, error) { cfg := r.ConfigFile() if cfg == "" { return false, nil } p, _ := r.inside(cfg) raw, err := os.ReadFile(p) if err != nil { return false, err } changed := false out := disableKinds.ReplaceAllStringFunc(string(raw), func(m string) string { parts := disableKinds.FindStringSubmatch(m) var keep []string for _, k := range strings.Split(parts[2], ",") { if t := strings.Trim(strings.TrimSpace(k), `"'`); strings.EqualFold(t, "sitemap") { changed = true continue } if strings.TrimSpace(k) != "" { keep = append(keep, strings.TrimSpace(k)) } } return parts[1] + strings.Join(keep, ", ") + parts[3] }) if !changed { return false, nil } return true, r.WriteFile(cfg, out) } // BuiltFile reads a file from a build. func BuiltFile(outDir, rel string) (string, error) { raw, err := os.ReadFile(filepath.Join(outDir, rel)) return string(raw), err } // UpsertPage writes a content file, or, if it exists, replaces its body and // sets the given front matter fields. func (r *Repo) UpsertPage(rel string, fields []Field, body string) error { if !r.Exists(rel) { return r.NewPage(rel, fields, body) } if err := r.ReplaceBody(rel, body); err != nil { return err } for _, f := range fields { if err := r.SetFrontMatter(rel, f.Key, f.Value); err != nil { return err } } 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 }