From fbc6d220b2df93a84bcbddfca44de77e160fa959 Mon Sep 17 00:00:00 2001 From: John Coffey Date: Mon, 19 Oct 2026 09:35:10 -0700 Subject: [PATCH] lastmod: git dates pages by their last commit With lastmod: git in site.yaml, a page without updated: in its front matter gets the date of the last commit that changed its source file, or today while it has changes not yet committed. The sitemap, feeds and .Lastmod use it. Git runs read-only: no optional locks and no file-system monitor. Outside a repository, pages keep their front matter dates. --- internal/site/config.go | 7 +++ internal/site/gitdates.go | 78 ++++++++++++++++++++++++++++++ internal/site/gitdates_test.go | 88 ++++++++++++++++++++++++++++++++++ internal/site/load.go | 11 +++++ internal/site/page.go | 7 ++- 5 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 internal/site/gitdates.go create mode 100644 internal/site/gitdates_test.go diff --git a/internal/site/config.go b/internal/site/config.go index 7f6b5aa..d68414d 100644 --- a/internal/site/config.go +++ b/internal/site/config.go @@ -65,6 +65,10 @@ type Config struct { // Cart turns on the shop's cart (cart: true, or cart: { page: /basket/ }): // HotDog's cart script, kept in the visitor's browser, for the shop pack. Cart *CartConfig `yaml:"cart"` + // Lastmod "git" dates each page by the last commit that changed its + // source file, for the sitemap, feeds and .Lastmod, unless its front + // matter says when it was updated. Empty: front matter dates only. + Lastmod string `yaml:"lastmod"` // Cards draws a social card for every page without its own image // (`cards: true`, or a map to choose the font, colors and logo). Cards *CardsConfig `yaml:"cards"` @@ -253,6 +257,9 @@ func LoadConfig(dir string) (*Config, error) { return nil, fmt.Errorf("site.yaml: verify.%s should be the code only (the content of the meta tag), not the whole tag", name) } } + if c.Lastmod != "" && c.Lastmod != "git" { + return nil, fmt.Errorf("site.yaml: lastmod %q should be git, or left out", c.Lastmod) + } if c.Fediverse != "" && !fediverseRe.MatchString(c.Fediverse) { return nil, fmt.Errorf("site.yaml: fediverse %q should be a handle like @name@instance.social", c.Fediverse) } diff --git a/internal/site/gitdates.go b/internal/site/gitdates.go new file mode 100644 index 0000000..f7e76f1 --- /dev/null +++ b/internal/site/gitdates.go @@ -0,0 +1,78 @@ +package site + +import ( + "bytes" + "os" + "os/exec" + "path" + "strings" + "time" +) + +// gitDates dates the files under content/ by git history, for `lastmod: +// git`: the last commit that touched each one, keyed by its path under +// content/ (slash-separated). A file with changes not yet committed, or not +// yet added, is dated today, so building before a commit gives the date the +// commit will have. Outside a git repository, or without git, it returns +// nothing and pages keep their front matter dates. +// +// Only history git already has is read: in a shallow clone, files last +// changed before the clone's depth have no date. +func gitDates(dir string, today time.Time) map[string]time.Time { + prefix, err := git(dir, "rev-parse", "--show-prefix") + if err != nil { + return nil + } + content := strings.TrimSpace(string(prefix)) + "content/" + dates := map[string]time.Time{} + // Newest commit first: the first date seen for a file is its latest. + // Merge commits list no files, so a file gets its own commit's date. + out, err := git(dir, "log", "--format=%x00%cI", "--name-only", "--no-renames", "-z", "--", "content") + if err != nil { + return nil + } + var when time.Time + for _, f := range bytes.Split(out, []byte{0}) { + s := strings.Trim(string(f), "\n") + if s == "" { + continue + } + // A commit's date comes right after the NUL that --format starts + // with; its files follow, one per NUL. + if t, err := time.Parse(time.RFC3339, s); err == nil && !strings.Contains(s, "/") { + when = t + continue + } + rel, ok := strings.CutPrefix(s, content) + if !ok || when.IsZero() { + continue + } + if _, seen := dates[rel]; !seen { + dates[rel] = when + } + } + // Changed, added or new files under content/: today. + out, err = git(dir, "status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames", "--", "content") + if err != nil { + return dates + } + for _, e := range bytes.Split(out, []byte{0}) { + if len(e) < 4 || e[2] != ' ' { + continue + } + if rel, ok := strings.CutPrefix(string(e[3:]), content); ok && path.Clean(rel) == rel { + dates[rel] = today + } + } + return dates +} + +// git runs a read-only git command in dir. Optional locks are off, so it +// never writes to the index, and the file-system monitor is off, so a +// repository's own config can't make it run a program. +func git(dir string, args ...string) ([]byte, error) { + args = append([]string{"-C", dir, "--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "core.quotePath=false"}, args...) + cmd := exec.Command("git", args...) + cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0", "GIT_OPTIONAL_LOCKS=0") + return cmd.Output() +} diff --git a/internal/site/gitdates_test.go b/internal/site/gitdates_test.go new file mode 100644 index 0000000..a558962 --- /dev/null +++ b/internal/site/gitdates_test.go @@ -0,0 +1,88 @@ +package site + +import ( + "os" + "os/exec" + "path/filepath" + "testing" + "time" +) + +// TestGitLastmod dates pages by their last commit, today for changes not +// yet committed, and leaves front matter's updated: in charge. The site is +// in a subfolder of its repository, as a monorepo would have it. +func TestGitLastmod(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git is not installed") + } + repo := t.TempDir() + dir := filepath.Join(repo, "site") + run := func(date string, args ...string) { + t.Helper() + cmd := exec.Command("git", append([]string{"-C", repo}, args...)...) + cmd.Env = append(os.Environ(), "GIT_AUTHOR_DATE="+date, "GIT_COMMITTER_DATE="+date, + "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.org", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.org", + "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + put := func(rel, body string) { + p := filepath.Join(dir, rel) + os.MkdirAll(filepath.Dir(p), 0o755) + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + put("site.yaml", "name: T\nurl: https://example.org\nlastmod: git\n") + put("content/a.md", "---\ntitle: A\n---\n") + put("content/docs/b.md", "---\ntitle: B\n---\n") + put("content/c.md", "---\ntitle: C\nupdated: 2020-01-02\n---\n") + run("", "init", "-q") + run("2026-03-01T10:00:00Z", "add", ".") + run("2026-03-01T10:00:00Z", "commit", "-q", "-m", "one") + put("content/a.md", "---\ntitle: A, again\n---\n") + run("2026-05-07T23:30:00-07:00", "commit", "-q", "-am", "two") + put("content/docs/b.md", "---\ntitle: B, changed\n---\n") + put("content/new.md", "---\ntitle: New\n---\n") + + now := time.Date(2026, 10, 19, 15, 0, 0, 0, time.UTC) + s, err := Load(dir, Options{Now: now}) + if err != nil { + t.Fatal(err) + } + want := map[string]string{ + "a.md": "2026-05-07", // the second commit, in its own zone + "docs/b.md": "2026-10-19", // changed, not committed + "new.md": "2026-10-19", // not added yet + "c.md": "2020-01-02", // updated: wins + } + for _, p := range s.Pages { + if w, ok := want[p.Source]; ok { + if got := p.Lastmod().Format("2006-01-02"); got != w { + t.Errorf("%s: lastmod %s, want %s", p.Source, got, w) + } + delete(want, p.Source) + } + } + if len(want) > 0 { + t.Errorf("pages not found: %v", want) + } + + // Without the setting, or outside git, there are no commit dates. + put("site.yaml", "name: T\nurl: https://example.org\n") + if s, _ = Load(dir, Options{Now: now}); s.PageFrom("a.md").Lastmod().IsZero() == false { + t.Error("dated a page without lastmod: git") + } + plain := t.TempDir() + os.WriteFile(filepath.Join(plain, "site.yaml"), []byte("name: T\nurl: https://example.org\nlastmod: git\n"), 0o644) + os.MkdirAll(filepath.Join(plain, "content"), 0o755) + os.WriteFile(filepath.Join(plain, "content", "a.md"), []byte("---\ntitle: A\n---\n"), 0o644) + if s, err = Load(plain, Options{Now: now}); err != nil || !s.PageFrom("a.md").Lastmod().IsZero() { + t.Errorf("outside git: %v", err) + } + put("site.yaml", "name: T\nurl: https://example.org\nlastmod: mtime\n") + if _, err := Load(dir, Options{Now: now}); err == nil { + t.Error("accepted lastmod: mtime") + } +} diff --git a/internal/site/load.go b/internal/site/load.go index b0e0f5c..6dcc014 100644 --- a/internal/site/load.go +++ b/internal/site/load.go @@ -183,6 +183,17 @@ func Load(dir string, opt Options) (*Site, error) { return nil, err } } + if cfg.Lastmod == "git" { + today := now.In(s.Location) + today = time.Date(today.Year(), today.Month(), today.Day(), 0, 0, 0, 0, s.Location) + dates := gitDates(dir, today) + for _, p := range s.Pages { + p.Committed = dates[p.Source] + if _, edited := opt.Overrides[p.Source]; edited { + p.Committed = today // unsaved in the editor: not committed yet + } + } + } s.placeCollections() s.resolveSourceLinks() s.assemble() diff --git a/internal/site/page.go b/internal/site/page.go index 44df1aa..e14311d 100644 --- a/internal/site/page.go +++ b/internal/site/page.go @@ -23,6 +23,7 @@ type Page struct { Summary string Date time.Time Updated time.Time + Committed time.Time // the source file's last commit (lastmod: git) Draft bool NoIndex bool Layout string @@ -119,11 +120,15 @@ func (p *Page) ReadingTime() int { return m } -// Lastmod is the date a sitemap should give: updated, else date. +// Lastmod is the date a sitemap should give: updated, else the later of +// the last commit (lastmod: git) and date. func (p *Page) Lastmod() time.Time { if !p.Updated.IsZero() { return p.Updated } + if p.Committed.After(p.Date) { + return p.Committed + } return p.Date } -- 2.54.0