// 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" "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 } // 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. func (r *Repo) Diff(ctx context.Context) (string, error) { 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, "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 } // 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", firstLine(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 }