various changes

c0427d5fc7c0… · Ryan Schanzenbacher ·

parent 3a50036d96eb… view tree

Changed files

FileChanges
go.mod +12 −2 raw
go.sum +18 −0 raw
gpgverif +12 −0 raw
internal/core/core.go +114 −17 raw
internal/core/errorpage.go +65 −0 raw
internal/core/nav.go +70 −0 raw
internal/core/route.go +13 −0 raw
internal/core/server.go +30 −13 raw
internal/core/watch.go +196 −0 raw
internal/gitx/git.go +281 −15 raw
internal/gitx/git_test.go +93 −0 raw
internal/modules/blob.go +60 −6 raw
internal/modules/blob_test.go +121 −0 raw
internal/modules/commit.go +1 −1 raw
internal/modules/compare.go +1 −1 raw
internal/modules/example_authors.go +1 −1 raw
internal/modules/graph.go +39 −3 raw
internal/modules/highlight.go +79 −0 raw
internal/modules/log.go +38 −3 raw
internal/modules/meta.go +1 −1 raw
internal/modules/readme.go +8 −2 raw
internal/modules/repos.go +33 −3 raw
internal/modules/structured.go +364 −0 raw
internal/modules/structured_test.go +158 −0 raw
internal/site/routes.go +13 −11 raw
main.go +4 −33 raw
static/css/base.css +466 −0 raw
static/css/blob.css +144 −0 raw
static/css/diff.css +33 −0 raw
static/css/graph.css +30 −0 raw
static/css/readme.css +66 −0 raw
static/css/repo-list.css +41 −0 raw
static/css/repo.css +46 −0 raw
static/js/structured.js +273 −0 raw
static/style.css +0 −348 raw
templates/layouts/base.html +38 −25 raw
templates/layouts/partials.html +36 −21 raw
templates/views/blob.html +53 −16 raw
templates/views/commit.html +38 −16 raw
templates/views/compare.html +41 −18 raw
templates/views/graph.html +46 −19 raw
templates/views/index.html +23 −9 raw
templates/views/log.html +66 −5 raw
templates/views/refs.html +54 −28 raw
templates/views/repo.html +0 −41 raw
templates/views/tree.html +84 −9 raw
diff --git a/go.mod b/go.mod
index 8a61730..503bebb 100644
--- a/go.mod
+++ b/go.mod
@@ -1,5 +1,15 @@
module gsg
-go 1.22
+go 1.23
-require github.com/yuin/goldmark v1.8.5
+require (
+ github.com/alecthomas/chroma/v2 v2.24.1
+ github.com/fsnotify/fsnotify v1.10.1
+ github.com/yuin/goldmark v1.8.5
+ gopkg.in/yaml.v3 v3.0.1
+)
+
+require (
+ github.com/dlclark/regexp2 v1.12.0 // indirect
+ golang.org/x/sys v0.13.0 // indirect
+)
diff --git a/go.sum b/go.sum
index 98fbe0d..1a01f6d 100644
--- a/go.sum
+++ b/go.sum
@@ -1,2 +1,20 @@
+github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=
+github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
+github.com/alecthomas/chroma/v2 v2.24.1 h1:m5ffpfZbIb++k8AqFEKy9uVgY12xIQtBsQlc6DfZJQM=
+github.com/alecthomas/chroma/v2 v2.24.1/go.mod h1:l+ohZ9xRXIbGe7cIW+YZgOGbvuVLjMps/FYN/CwuabI=
+github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs=
+github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
+github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8=
+github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
+github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
+github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
+github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
+github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
github.com/yuin/goldmark v1.8.5 h1:r6N5afV5qj/5S4UTch8agZHJ8UxNCMwX7WjkkJam2NA=
github.com/yuin/goldmark v1.8.5/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
+golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
+golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/gpgverif b/gpgverif
new file mode 100644
index 0000000..362bb5d
--- /dev/null
+++ b/gpgverif
@@ -0,0 +1,12 @@
+Config (per-repo, cgit-style, matching the existing pattern): git --git-dir=/srv/git/foo.git config gsg.gpgkeyring /path/to/keys.asc, where the file is one or more ASCII-armored public keys.
+
+How it works:
+- At startup, if a repo has gsg.gpgkeyring set, Repo.UseKeyring builds an isolated GNUPGHOME (under /tmp, not os.TempDir() — macOS's longer default temp path pushes gpg-agent's Unix socket past its ~104-byte limit and silently breaks) and imports only that file's keys into it.
+- On import failure, it logs a warning and disables verification for that repo rather than failing the whole server.
+- Repo.Log (used by the log module, n=20) now optionally asks git for %G? %GS %GK per commit — gated on both the caller wanting it and the repo actually having a keyring, so no wasted gpg forks. LogAll (the unbounded graph walk) deliberately never requests it — verifying every signed commit across full history would risk blowing the per-request timeout.
+- A commit is "verified" if %G? is G or U — a signature valid against an imported key gets U, not G, since a bare keyring has no ownertrust database. Trust here comes from the operator putting the key in the file, not GPG's web-of-trust.
+- Signed-but-unknown-key commits (%G? = E, the common case on a partial keyring) render as a neutral "unknown key" badge, not a red failure — confirmed this distinction empirically since it's easy to get backwards.
+
+UI: log.html gains a "Signature" column, shown only when the repo has verification configured. Green verified / neutral unknown key / red bad signature (and expired/revoked variants) / dash for unsigned.
+
+Tested end-to-end against real signed/unsigned/foreign-key commits across three repo configs (verified, plain, bad-keyring-path), including the misconfiguration path.
diff --git a/internal/core/core.go b/internal/core/core.go
index d76f058..cdc447f 100644
--- a/internal/core/core.go
+++ b/internal/core/core.go
@@ -8,6 +8,7 @@ import (
"sort"
"strings"
"sync"
+ "sync/atomic"
"gsg/internal/gitx"
)
@@ -19,9 +20,80 @@ type Site struct {
BaseURL string
Root string // directory containing bare repos
- // Repos is every discovered repository. Site-scoped routes (the
- // index page, the index endpoint) read it through the `repos` module.
- Repos []Handle
+ idx atomic.Pointer[repoIndex]
+ mu sync.Mutex // serializes upsert/remove; RepoList/Lookup never block
+}
+
+// repoIndex is an immutable snapshot, swapped in whole by upsert/remove so
+// readers (RepoList, Lookup) never need a lock.
+type repoIndex struct {
+ list []Handle // every known repo, hidden or not -- repos.go filters Hidden itself
+ bySlug map[string]Handle // non-hidden only, for URL routing
+}
+
+// RepoList is every discovered repository. Site-scoped routes (the index
+// page, the index endpoint) read it through the `repos` module.
+func (s *Site) RepoList() []Handle {
+ if idx := s.idx.Load(); idx != nil {
+ return idx.list
+ }
+ return nil
+}
+
+// Lookup resolves a repo by slug for per-repo routes. Hidden repos are not
+// found here, the same way they were excluded from Server's old repos map.
+func (s *Site) Lookup(slug string) (Handle, bool) {
+ idx := s.idx.Load()
+ if idx == nil {
+ return Handle{}, false
+ }
+ h, ok := idx.bySlug[slug]
+ return h, ok
+}
+
+// upsert and remove are the only writers of the repo index, both called
+// exclusively from watch.go's reconcile -- at startup and at runtime alike,
+// through the same code path.
+func (s *Site) upsert(h Handle) {
+ s.mutate(func(list []Handle) []Handle {
+ for i, e := range list {
+ if e.Info.Slug == h.Info.Slug {
+ list[i] = h
+ return list
+ }
+ }
+ return append(list, h)
+ })
+}
+
+func (s *Site) remove(slug string) {
+ s.mutate(func(list []Handle) []Handle {
+ for i, e := range list {
+ if e.Info.Slug == slug {
+ return append(list[:i], list[i+1:]...)
+ }
+ }
+ return list
+ })
+}
+
+func (s *Site) mutate(f func([]Handle) []Handle) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ var cur []Handle
+ if idx := s.idx.Load(); idx != nil {
+ cur = append([]Handle(nil), idx.list...)
+ }
+ next := f(cur)
+
+ bySlug := make(map[string]Handle, len(next))
+ for _, h := range next {
+ if !h.Info.Hidden {
+ bySlug[h.Info.Slug] = h
+ }
+ }
+ s.idx.Store(&repoIndex{list: next, bySlug: bySlug})
}
// Handle pairs an open repository with its configuration.
@@ -40,6 +112,7 @@ type Handle struct {
// clone = git://...
// hide = true
// section = infra
+// gpgkeyring = /path/to/keys.asc
//
// Set them with: git --git-dir=/srv/git/foo.git config gsg.title "Foo"
type RepoInfo struct {
@@ -50,6 +123,14 @@ type RepoInfo struct {
Clone string
Section string
Hidden bool
+
+ // GPGKeyring is the configured path to a file of armored public keys
+ // (gsg.gpgkeyring), if any. Reading it here is just config; the actual
+ // import into an isolated keyring happens once at startup (see
+ // gitx.Repo.UseKeyring) and, on failure, this is cleared again so
+ // templates don't advertise a verification column that isn't backed
+ // by anything.
+ GPGKeyring string
}
func LoadRepoInfo(r *gitx.Repo) RepoInfo {
@@ -69,6 +150,7 @@ func LoadRepoInfo(r *gitx.Repo) RepoInfo {
Clone: r.ConfigFirst("gsg.clone", "gitweb.url"),
Section: r.ConfigFirst("gsg.section", "gitweb.category"),
Hidden: strings.EqualFold(r.Config("gsg.hide"), "true"),
+ GPGKeyring: r.Config("gsg.gpgkeyring"),
}
}
@@ -85,6 +167,10 @@ type Ctx struct {
Path string
Vars map[string]string
+ // Nav is the repo-scoped tab bar, built once in Server.serve from the
+ // route table (see nav.go). Empty for site-scoped routes.
+ Nav []NavItem
+
// Commit is Ref resolved to a full SHA. Everything a module computes
// at a given Commit is immutable, which is what makes the shared
// cache and ETags correct rather than merely convenient.
@@ -114,32 +200,43 @@ func NewCtx(site *Site, r *gitx.Repo, info RepoInfo, ref string) *Ctx {
Vars: map[string]string{}, cache: map[string]result{}}
}
-// CacheKey identifies an immutable module result. Empty when the result
-// cannot be cached (no resolved commit).
+// contentIdentity captures every input that can change what a route
+// renders at a fixed commit -- the commit itself, plus anything that can
+// change without the commit moving. Vars are part of it: /compare/a..b and
+// /compare/a...b resolve to the same head commit, so without the base ref
+// in here the second request was served the first one's diff. GPGKeyring
+// is part of it for the same reason: watch.go's reconcile can change a
+// repo's keyring under commits whose SHAs haven't moved, and a page
+// fetched before that would otherwise cache "unsigned" forever.
//
-// Vars are part of the key. They were not, originally, and the bug was
-// exactly the kind this cache is supposed to be immune to: /compare/a..b
-// and /compare/a...b resolve to the same head commit, so the second
-// request was served the first one's diff. Anything that changes what a
-// module computes has to be in the key, not just the commit it hangs off.
-func (c *Ctx) CacheKey(name string, args []string) string {
- if c.Commit == "" || c.Store == nil {
- return ""
- }
- var b strings.Builder
- b.WriteString(c.Info.Slug + "|" + c.Commit + "|" + c.Path + "|" + name + "|")
- b.WriteString(strings.Join(args, "\x00"))
+// CacheKey and the response ETag (server.go) are both built from this, so
+// a new Var or a keyring change can't invalidate one without invalidating
+// the other -- that used to be two hand-maintained lists that had already
+// drifted (the ETag was missing GPGKeyring and any Var besides baseSHA).
+func (c *Ctx) contentIdentity() string {
keys := make([]string, 0, len(c.Vars))
for k := range c.Vars {
keys = append(keys, k)
}
sort.Strings(keys)
+ var b strings.Builder
+ b.WriteString(c.Commit + "|" + c.Info.GPGKeyring)
for _, k := range keys {
b.WriteString("|" + k + "=" + c.Vars[k])
}
return b.String()
}
+// CacheKey identifies an immutable module result. Empty when the result
+// cannot be cached (no resolved commit).
+func (c *Ctx) CacheKey(name string, args []string) string {
+ if c.Commit == "" || c.Store == nil {
+ return ""
+ }
+ return c.Info.Slug + "|" + c.Path + "|" + name + "|" +
+ strings.Join(args, "\x00") + "|" + c.contentIdentity()
+}
+
// Derive returns a shallow copy for a different path, with a fresh cache.
func (c *Ctx) Derive(path string, vars map[string]string) *Ctx {
n := NewCtx(c.Site, c.Repo, c.Info, c.Ref)
diff --git a/internal/core/errorpage.go b/internal/core/errorpage.go
new file mode 100644
index 0000000..365396e
--- /dev/null
+++ b/internal/core/errorpage.go
@@ -0,0 +1,65 @@
+package core
+
+import (
+ "bytes"
+ "fmt"
+ "html/template"
+ "net/http"
+)
+
+// errorTmpl is compiled from a literal, not from the theme's template
+// files -- a broken view template is exactly the situation this page has
+// to survive, so it cannot depend on LoadTemplates succeeding.
+var errorTmpl = template.Must(template.New("error").Parse(`<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>{{.Code}} {{.Status}} &middot; {{.Site}}</title>
+<link rel="stylesheet" href="/static/css/base.css">
+</head>
+<body>
+<main class="wrap error-page">
+ <p class="error-code">{{.Code}}</p>
+ <h1 class="page-title">{{.Status}}</h1>
+ <p class="page-subtitle">{{.Message}}</p>
+ <p><a href="/">&larr; back to {{.Site}}</a></p>
+</main>
+</body>
+</html>
+`))
+
+// renderErrorPage never returns an error: if the template somehow fails to
+// execute, it falls back to a plain-text body rather than propagating.
+func renderErrorPage(code int, site string) (body []byte, contentType string) {
+ data := struct {
+ Code int
+ Status, Message, Site string
+ }{
+ Code: code,
+ Status: http.StatusText(code),
+ Message: friendlyMessage(code),
+ Site: site,
+ }
+ var buf bytes.Buffer
+ if err := errorTmpl.Execute(&buf, data); err != nil {
+ return []byte(fmt.Sprintf("%d %s\n", code, http.StatusText(code))), "text/plain; charset=utf-8"
+ }
+ return buf.Bytes(), "text/html; charset=utf-8"
+}
+
+// friendlyMessage keeps the diagnostic detail out of the response body --
+// that stays in the server log -- while still telling a human what class
+// of problem they hit.
+func friendlyMessage(code int) string {
+ switch code {
+ case http.StatusNotFound:
+ return "We couldn't find that repository, ref, or path."
+ case http.StatusBadRequest:
+ return "That request doesn't look right."
+ case http.StatusRequestEntityTooLarge:
+ return "That response is too large to display in full."
+ default:
+ return "Something went wrong rendering this page. The details were logged."
+ }
+}
diff --git a/internal/core/nav.go b/internal/core/nav.go
new file mode 100644
index 0000000..8f6692c
--- /dev/null
+++ b/internal/core/nav.go
@@ -0,0 +1,70 @@
+package core
+
+import "strings"
+
+// NavItem is one entry in the repo-scoped navigation -- the top tab bar
+// and the page-nav chips both render the same slice, built from the route
+// table so a new tab is a one-line addition to site/routes.go, not a
+// second place to remember.
+type NavItem struct {
+ Label string
+ Href string
+ Active bool
+}
+
+// BuildNav derives the repo-scoped nav from every route whose NavLabel is
+// set, in route-table order. current is the name of the route being
+// served, used to mark the matching tab active.
+func BuildNav(routes []Route, current, slug, ref string) []NavItem {
+ if slug == "" {
+ return nil
+ }
+ var items []NavItem
+ for _, rt := range routes {
+ if rt.Scope != ScopeRepo || rt.NavLabel == "" {
+ continue
+ }
+ items = append(items, NavItem{
+ Label: rt.NavLabel,
+ Href: navHref(rt, slug, ref),
+ // The "repo" route (bare /{repo}/) renders tree.html at its
+ // root, same as "tree" does at path "" -- so the files tab
+ // lights up on both, even though "repo" carries no NavLabel
+ // of its own and never appears in this loop as a tab.
+ Active: rt.Name == current || (rt.Name == "tree" && current == "repo"),
+ })
+ }
+ return items
+}
+
+// navHref builds the href for a nav tab from its route pattern: the fixed
+// segment right after {repo}, plus the ref if the route is ref-addressed
+// ({rest...} or {rev}). Routes addressed only by {$} (graph, refs) link to
+// their bare index instead.
+func navHref(rt Route, slug, ref string) string {
+ seg := navSegment(rt.Pattern)
+ href := "/" + slug + "/"
+ if seg != "" {
+ href += seg + "/"
+ }
+ if strings.Contains(rt.Pattern, "{rest...}") || strings.Contains(rt.Pattern, "{rev}") {
+ href += ref
+ }
+ return href
+}
+
+// navSegment extracts the literal path element between {repo} and the
+// next wildcard, e.g. "GET /{repo}/tree/{rest...}" -> "tree". Returns ""
+// for patterns with no such segment (e.g. "GET /{repo}/{$}").
+func navSegment(pattern string) string {
+ p := pattern
+ if i := strings.IndexByte(p, ' '); i >= 0 {
+ p = p[i+1:]
+ }
+ p = strings.TrimPrefix(p, "/{repo}/")
+ seg, _, _ := strings.Cut(p, "/")
+ if strings.HasPrefix(seg, "{") {
+ return ""
+ }
+ return seg
+}
diff --git a/internal/core/route.go b/internal/core/route.go
index cbaa382..4a3800e 100644
--- a/internal/core/route.go
+++ b/internal/core/route.go
@@ -80,6 +80,10 @@ type Route struct {
// URL -- anything addressed by a commit SHA. Those get a year-long
// Cache-Control; ref-addressed URLs get revalidation instead.
Immutable bool
+ // NavLabel, when set on a ScopeRepo route, adds a tab for it to the
+ // repo-scoped navigation (see nav.go) -- the top tab bar and the
+ // page-nav chips both derive from this instead of hardcoding links.
+ NavLabel string
}
type Scope int
@@ -89,6 +93,15 @@ const (
ScopeSite // no repository in the URL
)
+// Page sizes for routes that paginate via ?ofs=. Kept in core (not
+// modules) so buildCtx can quantize an incoming ofs to a real page
+// boundary without an import cycle. Must match the literal args the
+// log.html/graph.html templates pass to `mod "log"`/`mod "graph"`.
+const (
+ LogPageSize = 20
+ GraphPageSize = 150
+)
+
// httpError lets a module or endpoint choose the status code.
type httpError struct {
Code int
diff --git a/internal/core/server.go b/internal/core/server.go
index 93ce421..adf677c 100644
--- a/internal/core/server.go
+++ b/internal/core/server.go
@@ -8,6 +8,7 @@ import (
"io/fs"
"log/slog"
"net/http"
+ "strconv"
"strings"
"sync"
"time"
@@ -31,7 +32,6 @@ type Server struct {
templates TemplateSet
tmplTag string // changes when templates change; part of every ETag
cache Store
- repos map[string]Handle
}
func NewServer(site *Site, routes []Route, tfs fs.FS, cacheSize int) (*Server, error) {
@@ -41,12 +41,6 @@ func NewServer(site *Site, routes []Route, tfs fs.FS, cacheSize int) (*Server, e
Timeout: 10 * time.Second,
MaxGit: 8 << 20,
cache: NewLRU(cacheSize),
- repos: map[string]Handle{},
- }
- for _, h := range site.Repos {
- if !h.Info.Hidden {
- s.repos[h.Info.Slug] = h
- }
}
if err := s.loadTemplates(); err != nil {
return nil, err
@@ -115,6 +109,7 @@ func (s *Server) serve(rt Route, w http.ResponseWriter, r *http.Request) {
s.fail(w, r, rt, err)
return
}
+ c.Nav = BuildNav(s.Routes, rt.Name, c.Info.Slug, c.Ref)
// ETag is derived from the resolved commit SHA, not the response body,
// so a conditional request costs one ref lookup instead of a render.
@@ -123,10 +118,10 @@ func (s *Server) serve(rt Route, w http.ResponseWriter, r *http.Request) {
ts := s.templates
s.mu.RUnlock()
- // Vars carry the second endpoint of a compare, so a moving base ref
- // still changes the ETag.
- etag := `"` + shortHash(rt.Name, r.URL.Path, r.URL.RawQuery,
- c.Commit, c.Vars["baseSHA"], tag) + `"`
+ // contentIdentity carries the commit, keyring, and every Var (e.g.
+ // compare's base ref) -- the same fragment module results are keyed
+ // on, so this can't drift out of sync with what CacheKey covers.
+ etag := `"` + shortHash(rt.Name, r.URL.Path, r.URL.RawQuery, tag, c.contentIdentity()) + `"`
w.Header().Set("ETag", etag)
if rt.Immutable && c.Commit != "" {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
@@ -158,7 +153,7 @@ func (s *Server) buildCtx(ctx contexter, rt Route, r *http.Request) (*Ctx, error
}
slug := r.PathValue("repo")
- h, ok := s.repos[slug]
+ h, ok := s.Site.Lookup(slug)
if !ok {
return nil, Errorf(http.StatusNotFound, "no such repository %q", slug)
}
@@ -210,6 +205,18 @@ func (s *Server) buildCtx(ctx contexter, rt Route, r *http.Request) (*Ctx, error
c.Vars["baseSHA"], c.Vars["headSHA"] = baseSHA, c.Commit
c.Vars["dots"] = dots
}
+ if rt.Name == "log" || rt.Name == "graph" {
+ pageSize := LogPageSize
+ if rt.Name == "graph" {
+ pageSize = GraphPageSize
+ }
+ if v := r.URL.Query().Get("ofs"); v != "" {
+ if ofs, err := strconv.Atoi(v); err == nil && ofs > 0 {
+ ofs -= ofs % pageSize // snap to a page boundary before it can become a cache key
+ c.Vars["ofs"] = strconv.Itoa(ofs)
+ }
+ }
+ }
return c, nil
}
@@ -223,7 +230,17 @@ func (s *Server) fail(w http.ResponseWriter, r *http.Request, rt Route, err erro
} else {
s.Log.Info("request rejected", "route", rt.Name, "path", r.URL.Path, "status", code, "err", err)
}
- http.Error(w, http.StatusText(code), code)
+
+ // serve() sets ETag/Cache-Control before Render runs, assuming success.
+ // An error response must never inherit those, especially the
+ // year-long immutable Cache-Control on commit routes.
+ w.Header().Del("ETag")
+ w.Header().Set("Cache-Control", "no-store")
+
+ body, cType := renderErrorPage(code, s.Site.Name)
+ w.Header().Set("Content-Type", cType)
+ w.WriteHeader(code)
+ w.Write(body)
}
func shortHash(parts ...string) string {
diff --git a/internal/core/watch.go b/internal/core/watch.go
new file mode 100644
index 0000000..48e4beb
--- /dev/null
+++ b/internal/core/watch.go
@@ -0,0 +1,196 @@
+package core
+
+import (
+ "fmt"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+
+ "github.com/fsnotify/fsnotify"
+
+ "gsg/internal/gitx"
+)
+
+// discoverConcurrency bounds how many repositories are opened at once during
+// the initial scan. Each one is a handful of git forks plus, for
+// keyring-bearing repos, a gpg import -- unbounded parallelism would fork
+// thousands of processes at once on a large install.
+const discoverConcurrency = 16
+
+// watcher owns every repo directly under root: which ones are currently
+// open, and the fsnotify watch that tells it when to look again. reconcile
+// is the single entry point for loading, reloading, or dropping a repo --
+// used identically by the initial scan and by every later filesystem event.
+type watcher struct {
+ site *Site
+ root string
+ fsw *fsnotify.Watcher
+
+ mu sync.Mutex
+ repos map[string]*gitx.Repo // open repos, by directory name -- reused across reconciles
+ dirName map[string]string // git-dir path -> directory name, for event dispatch
+
+ debMu sync.Mutex
+ debounce map[string]*time.Timer
+}
+
+// Start discovers every repository under site.Root, then watches root and
+// each repo's git-dir for changes for the life of the process. It returns
+// once the initial scan completes, the same as the old discover() did.
+func Start(site *Site) error {
+ fsw, err := fsnotify.NewWatcher()
+ if err != nil {
+ return fmt.Errorf("config watch: %w", err)
+ }
+ if err := fsw.Add(site.Root); err != nil {
+ fsw.Close()
+ return fmt.Errorf("config watch: %w", err)
+ }
+
+ w := &watcher{
+ site: site,
+ root: site.Root,
+ fsw: fsw,
+ repos: map[string]*gitx.Repo{},
+ dirName: map[string]string{},
+ debounce: map[string]*time.Timer{},
+ }
+
+ entries, err := os.ReadDir(site.Root)
+ if err != nil {
+ fsw.Close()
+ return err
+ }
+
+ sem := make(chan struct{}, discoverConcurrency)
+ var wg sync.WaitGroup
+ for _, e := range entries {
+ if !e.IsDir() {
+ continue
+ }
+ wg.Add(1)
+ go func(name string) {
+ defer wg.Done()
+ sem <- struct{}{}
+ defer func() { <-sem }()
+ w.reconcile(name)
+ }(e.Name())
+ }
+ wg.Wait()
+
+ if len(site.RepoList()) == 0 {
+ fsw.Close()
+ return fmt.Errorf("no repositories found under %s", site.Root)
+ }
+
+ go w.run()
+ return nil
+}
+
+// reconcile loads, reloads, or drops exactly one repo, named by its
+// directory under root. It is existence-driven rather than event-driven --
+// it doesn't ask what kind of filesystem event caused this call, only
+// whether root/name currently exists and is a valid repo -- which is what
+// lets the same function serve both the initial concurrent scan and the
+// one-at-a-time runtime event loop with no special-casing between them.
+func (w *watcher) reconcile(name string) {
+ dir := filepath.Join(w.root, name)
+
+ w.mu.Lock()
+ r, known := w.repos[name]
+ w.mu.Unlock()
+
+ if _, err := os.Stat(dir); err != nil {
+ if known {
+ w.mu.Lock()
+ delete(w.repos, name)
+ w.fsw.Remove(r.Dir)
+ delete(w.dirName, r.Dir)
+ w.mu.Unlock()
+ w.site.remove(r.Slug)
+ }
+ return
+ }
+
+ if !known {
+ var err error
+ if r, err = gitx.Open(dir); err != nil {
+ return // not a repo (or a bare clone still being populated)
+ }
+ w.mu.Lock()
+ w.repos[name] = r
+ w.fsw.Add(r.Dir) // catches this repo's own config/description writes from here on
+ w.dirName[r.Dir] = name
+ w.mu.Unlock()
+ }
+
+ info := LoadRepoInfo(r)
+
+ // Converge the keyring to whatever's configured now, on this call just
+ // like any other -- no "only import the first time" special case.
+ if info.GPGKeyring != r.KeyringPath() {
+ if info.GPGKeyring == "" {
+ r.ClearKeyring()
+ } else if err := r.UseKeyring(info.GPGKeyring); err != nil {
+ slog.Warn("gpg keyring: verification disabled", "repo", info.Slug, "err", err)
+ info.GPGKeyring = ""
+ }
+ }
+
+ w.site.upsert(Handle{Repo: r, Info: info})
+}
+
+// run consumes filesystem events for the life of the process. A repo dir
+// appearing, disappearing, or being renamed under root is dispatched by its
+// (new) name; a write to a known repo's config or description file is
+// dispatched by that repo's name.
+func (w *watcher) run() {
+ for {
+ select {
+ case ev, ok := <-w.fsw.Events:
+ if !ok {
+ return
+ }
+ if filepath.Dir(ev.Name) == w.root {
+ w.scheduleReconcile(filepath.Base(ev.Name))
+ continue
+ }
+ if base := filepath.Base(ev.Name); base == "config" || base == "description" {
+ w.mu.Lock()
+ name := w.dirName[filepath.Dir(ev.Name)]
+ w.mu.Unlock()
+ if name != "" {
+ w.scheduleReconcile(name)
+ }
+ }
+ case err, ok := <-w.fsw.Errors:
+ if !ok {
+ return
+ }
+ slog.Warn("config watch error", "err", err)
+ }
+ }
+}
+
+// scheduleReconcile coalesces bursts of events for the same repo -- a single
+// `git config` write is a lockfile create plus a rename, i.e. at least two
+// raw events for one logical change -- into a single reconcile call.
+func (w *watcher) scheduleReconcile(name string) {
+ const debounceDelay = 200 * time.Millisecond
+
+ w.debMu.Lock()
+ defer w.debMu.Unlock()
+
+ if t, ok := w.debounce[name]; ok {
+ t.Reset(debounceDelay)
+ return
+ }
+ w.debounce[name] = time.AfterFunc(debounceDelay, func() {
+ w.debMu.Lock()
+ delete(w.debounce, name)
+ w.debMu.Unlock()
+ w.reconcile(name)
+ })
+}
diff --git a/internal/gitx/git.go b/internal/gitx/git.go
index 85e491f..b7b38e2 100644
--- a/internal/gitx/git.go
+++ b/internal/gitx/git.go
@@ -13,6 +13,7 @@ import (
"regexp"
"strconv"
"strings"
+ "sync"
"time"
)
@@ -35,6 +36,34 @@ type Repo struct {
ctx context.Context
maxBytes int64
+
+ // gpgHome, once set by UseKeyring, is an isolated GNUPGHOME containing
+ // only the keys the operator imported for this repo. Its presence is
+ // also the signal to Log/LogAll to ask git for signature status at all.
+ gpgHome string
+
+ // keyringPath is the gsg.gpgkeyring value that produced gpgHome, so a
+ // caller can tell whether the configured keyring has changed without
+ // tracking that separately. Empty when no keyring is imported.
+ keyringPath string
+
+ // memo caches HeadRef/Refs for the lifetime of one request. It is a
+ // pointer, allocated fresh by WithContext, rather than a plain field:
+ // Repo is copied by value (see WithContext), so a mutex or map field
+ // here directly would either trip go vet's copylocks check or -- worse
+ // -- share its map header with the copy, leaking one request's cache
+ // into the long-lived Repo every Handle keeps between requests. nil on
+ // that long-lived Repo and in any Repo not built via WithContext (e.g.
+ // tests): HeadRef/Refs just skip the cache in that case.
+ memo *repoMemo
+}
+
+type repoMemo struct {
+ mu sync.Mutex
+ headRef *string
+ haveRefs bool
+ refs []Ref
+ refsErr error
}
// WithContext returns a view of the repo bound to a request context and an
@@ -45,6 +74,7 @@ func (r *Repo) WithContext(ctx context.Context, maxBytes int64) *Repo {
c := *r
c.ctx = ctx
c.maxBytes = maxBytes
+ c.memo = &repoMemo{}
return &c
}
@@ -82,6 +112,11 @@ func (r *Repo) run(args ...string) ([]byte, error) {
cmd := exec.CommandContext(ctx, "git", full...)
// Refuse to inherit anything that alters git's behaviour.
cmd.Env = []string{"GIT_CONFIG_NOSYSTEM=1", "HOME=/nonexistent", "GIT_TERMINAL_PROMPT=0", "PATH=" + os.Getenv("PATH")}
+ if r.gpgHome != "" {
+ // git shells out to gpg to check %G?; gpg picks this up from its
+ // own environment, which it inherits from git's.
+ cmd.Env = append(cmd.Env, "GNUPGHOME="+r.gpgHome)
+ }
var out, errb bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &errb
@@ -122,6 +157,62 @@ func (r *Repo) ConfigFirst(keys ...string) string {
return ""
}
+// -------------------------------------------------------------------- gpg
+
+// UseKeyring points every subsequent git invocation on this Repo (via
+// GNUPGHOME, see run) at an isolated homedir containing only the keys
+// imported from path. Without this, %G? signature checks would fall back
+// to the host's default keyring -- whatever happens to be trusted there,
+// not what this repo's operator vetted.
+//
+// The homedir is created directly under /tmp rather than os.TempDir():
+// gpg-agent's control socket is a Unix domain socket, capped at ~104
+// bytes, and a long TMPDIR (macOS's is typically 50+ characters) pushes
+// the full path over that limit and breaks key generation/import in a way
+// that just prints "no agent running" with no useful exit code to catch.
+func (r *Repo) UseKeyring(path string) error {
+ dir, err := os.MkdirTemp("/tmp", "gsg-gpg-")
+ if err != nil {
+ return fmt.Errorf("gpg keyring: %w", err)
+ }
+ if err := os.Chmod(dir, 0700); err != nil {
+ return fmt.Errorf("gpg keyring: %w", err)
+ }
+ cmd := exec.Command("gpg", "--batch", "--quiet", "--import", path)
+ cmd.Env = []string{"GNUPGHOME=" + dir, "HOME=/nonexistent", "PATH=" + os.Getenv("PATH")}
+ var errb bytes.Buffer
+ cmd.Stderr = &errb
+ if err := cmd.Run(); err != nil {
+ os.RemoveAll(dir)
+ return fmt.Errorf("gpg keyring: import %s: %w: %s", path, err, strings.TrimSpace(errb.String()))
+ }
+
+ // Only swap the new homedir in -- and clean up the old one -- once the
+ // import has actually succeeded, so a bad reconfigure logs a warning and
+ // leaves the previously-working keyring active rather than breaking it.
+ old := r.gpgHome
+ r.gpgHome, r.keyringPath = dir, path
+ if old != "" {
+ os.RemoveAll(old)
+ }
+ return nil
+}
+
+// KeyringPath is the gsg.gpgkeyring value currently imported, or "" if no
+// keyring is active. Callers use this to detect when the configured keyring
+// has changed, on any call -- the first or the hundredth -- without needing
+// to track that separately.
+func (r *Repo) KeyringPath() string { return r.keyringPath }
+
+// ClearKeyring reverts to unverified signatures, removing any imported
+// keyring's isolated homedir.
+func (r *Repo) ClearKeyring() {
+ if r.gpgHome != "" {
+ os.RemoveAll(r.gpgHome)
+ }
+ r.gpgHome, r.keyringPath = "", ""
+}
+
const placeholderDesc = "Unnamed repository; edit this file 'description' to name the repository."
// DescriptionFile reads the legacy `description` file, ignoring git's placeholder.
@@ -148,6 +239,27 @@ type Ref struct {
}
func (r *Repo) Refs() ([]Ref, error) {
+ if r.memo != nil {
+ r.memo.mu.Lock()
+ if r.memo.haveRefs {
+ refs, err := r.memo.refs, r.memo.refsErr
+ r.memo.mu.Unlock()
+ return refs, err
+ }
+ r.memo.mu.Unlock()
+ }
+
+ refs, err := r.refs()
+
+ if r.memo != nil {
+ r.memo.mu.Lock()
+ r.memo.refs, r.memo.refsErr, r.memo.haveRefs = refs, err, true
+ r.memo.mu.Unlock()
+ }
+ return refs, err
+}
+
+func (r *Repo) refs() ([]Ref, error) {
const f = "%(refname:short)" + escF + "%(objectname)" + escF +
"%(creatordate:iso-strict)" + escF + "%(subject)" + escF + "%(refname)"
out, err := r.run("for-each-ref", "--format="+f, "refs/heads", "refs/tags")
@@ -190,12 +302,9 @@ func (r *Repo) Resolve(ref string) (string, error) {
return "", fmt.Errorf("invalid ref %q", ref)
}
if shaRE.MatchString(ref) {
- if _, err := r.run("cat-file", "-e", ref+"^{commit}"); err != nil {
- return "", fmt.Errorf("unknown commit %q", ref)
- }
- out, err := r.run("rev-parse", "--verify", ref+"^{commit}")
+ out, err := r.run("rev-parse", "--verify", "--quiet", ref+"^{commit}")
if err != nil {
- return "", err
+ return "", fmt.Errorf("unknown commit %q", ref)
}
return strings.TrimSpace(string(out)), nil
}
@@ -244,6 +353,26 @@ func (r *Repo) SplitRefPath(rest string) (ref, path string) {
// HeadRef resolves the repo's default branch, rather than guessing main/master.
func (r *Repo) HeadRef() string {
+ if r.memo != nil {
+ r.memo.mu.Lock()
+ cached := r.memo.headRef
+ r.memo.mu.Unlock()
+ if cached != nil {
+ return *cached
+ }
+ }
+
+ head := r.headRef()
+
+ if r.memo != nil {
+ r.memo.mu.Lock()
+ r.memo.headRef = &head
+ r.memo.mu.Unlock()
+ }
+ return head
+}
+
+func (r *Repo) headRef() string {
out, err := r.run("symbolic-ref", "--short", "HEAD")
if err != nil {
return "HEAD"
@@ -262,41 +391,109 @@ type Commit struct {
Subject string
Body string
Parents []string
+
+ // Signature is only populated when the caller asked for it (Log, when
+ // the repo has a keyring -- see Repo.UseKeyring). SigStatus is git's
+ // raw %G? code: G/U good, B bad, X/Y expired, R revoked, E unchecked,
+ // N unsigned or "" when signature checks weren't requested at all.
+ SigStatus string
+ Signer string
+ KeyID string
+}
+
+// Verified reports a good signature from a key in the repo's configured
+// keyring. A bare gpg homedir has no ownertrust database, so a genuinely
+// valid signature from a freshly-imported key comes back "U" (valid, trust
+// unknown), not "G" -- trust here comes from the key being in the
+// operator's keyring file, not from GPG's own web-of-trust bookkeeping.
+func (c Commit) Verified() bool { return c.SigStatus == "G" || c.SigStatus == "U" }
+
+// Signed reports whether the commit carries a signature at all, good or
+// not -- lets a template tell "bad signature" apart from "no signature".
+func (c Commit) Signed() bool { return c.SigStatus != "" && c.SigStatus != "N" }
+
+// Unchecked reports a signature git could not evaluate against the
+// keyring at all -- almost always because the signing key just isn't in
+// it. That is not evidence of tampering the way B/X/Y/R are, so it should
+// read as "we don't know", not as a failure.
+func (c Commit) Unchecked() bool { return c.SigStatus == "E" }
+
+// SigLabel is a short human-readable rendering of SigStatus, for the log
+// view's badge.
+func (c Commit) SigLabel() string {
+ switch c.SigStatus {
+ case "G", "U":
+ return "verified"
+ case "B":
+ return "bad signature"
+ case "X":
+ return "expired signature"
+ case "Y":
+ return "expired key"
+ case "R":
+ return "revoked key"
+ case "E":
+ return "signature not checked"
+ default:
+ return "unsigned"
+ }
}
// Log walks history from rev in ONE git process. n <= 0 means unbounded.
// Never call this once per commit; fork overhead dominates at scale.
-func (r *Repo) Log(rev string, n int) ([]Commit, error) {
+// When verify is true, each commit also carries its signature status --
+// only pass true for small, bounded logs: git forks gpg once per signed
+// commit to check it.
+func (r *Repo) Log(rev string, n, skip int, verify bool) ([]Commit, error) {
if r.empty {
return nil, nil
}
- format := strings.Join([]string{"%H", "%an", "%ae", "%aI", "%P", "%s", "%b"}, escLogF)
+ verify = verify && r.gpgHome != "" // no keyring configured: nothing to check against
+ fields := []string{"%H", "%an", "%ae", "%aI", "%P", "%s"}
+ if verify {
+ fields = append(fields, "%G?", "%GS", "%GK")
+ }
+ fields = append(fields, "%b")
+ format := strings.Join(fields, escLogF)
args := []string{"log", "--format=" + escLogR + format}
if n > 0 {
args = append(args, "-n", strconv.Itoa(n))
}
+ if skip > 0 {
+ args = append(args, "--skip", strconv.Itoa(skip))
+ }
args = append(args, rev)
- return r.parseLog(r.run(args...))
+ out, err := r.run(args...)
+ return r.parseLog(out, err, verify)
}
-func (r *Repo) parseLog(out []byte, err error) ([]Commit, error) {
+func (r *Repo) parseLog(out []byte, err error, verify bool) ([]Commit, error) {
if err != nil {
return nil, err
}
+ nfields := 7
+ if verify {
+ nfields = 10
+ }
var commits []Commit
for _, rec := range strings.Split(string(out), sepR) {
rec = strings.TrimRight(rec, "\n")
if rec == "" {
continue
}
- p := strings.SplitN(rec, sepF, 7)
- if len(p) < 7 {
+ p := strings.SplitN(rec, sepF, nfields)
+ if len(p) < nfields {
continue
}
t, _ := time.Parse(time.RFC3339, p[3])
c := Commit{
SHA: p[0], Author: p[1], Email: p[2], When: t,
- Subject: p[5], Body: strings.TrimSpace(p[6]),
+ Subject: p[5],
+ }
+ if verify {
+ c.SigStatus, c.Signer, c.KeyID, c.Body = p[6], p[7], p[8], strings.TrimSpace(p[9])
+ } else {
+ c.Body = strings.TrimSpace(p[6])
}
if len(c.SHA) >= 8 {
c.Short = c.SHA[:8]
@@ -326,8 +523,12 @@ func (r *Repo) LogAll(n int) ([]Commit, error) {
return nil, nil
}
format := strings.Join([]string{"%H", "%an", "%ae", "%aI", "%P", "%s", "%b"}, escLogF)
- return r.parseLog(r.run("log", "--all", "--topo-order", "--date-order",
- "-n", strconv.Itoa(n), "--format="+escLogR+format))
+ // Never request signature status here: this walks every ref unbounded
+ // for the graph view, and git forks gpg per signed commit -- fine at
+ // Log's n=20, not fine here.
+ out, err := r.run("log", "--all", "--topo-order", "--date-order",
+ "-n", strconv.Itoa(n), "--format="+escLogR+format)
+ return r.parseLog(out, err, false)
}
// ------------------------------------------------------------------- trees
@@ -341,7 +542,8 @@ type Entry struct {
Path string // full path from repo root
}
-func (e Entry) IsDir() bool { return e.Type == "tree" }
+func (e Entry) IsDir() bool { return e.Type == "tree" }
+func (e Entry) IsSubmodule() bool { return e.Type == "commit" }
// Tree lists one directory level at rev.
func (r *Repo) Tree(rev, path string) ([]Entry, error) {
@@ -379,6 +581,70 @@ func (r *Repo) Tree(rev, path string) ([]Entry, error) {
return entries, nil
}
+// Stat looks up a single path's own tree entry (its mode/type/sha as
+// recorded by its parent tree), regardless of depth. Unlike Blob, this
+// works for gitlinks (submodules), since it never tries to read object
+// contents.
+func (r *Repo) Stat(rev, path string) (Entry, bool, error) {
+ out, err := r.run("ls-tree", "-z", "--long", rev, "--", path)
+ if err != nil {
+ return Entry{}, false, err
+ }
+ rec := strings.TrimSuffix(string(out), "\x00")
+ if rec == "" {
+ return Entry{}, false, nil
+ }
+ head, name, ok := strings.Cut(rec, "\t")
+ if !ok {
+ return Entry{}, false, nil
+ }
+ f := strings.Fields(head)
+ if len(f) < 3 {
+ return Entry{}, false, nil
+ }
+ e := Entry{Mode: f[0], Type: f[1], SHA: f[2], Name: filepath.Base(name), Path: name}
+ if len(f) > 3 {
+ e.Size, _ = strconv.ParseInt(f[3], 10, 64)
+ }
+ return e, true, nil
+}
+
+// SubmoduleURL looks up the remote configured for a submodule path in
+// .gitmodules at rev. Best-effort: a missing or unparsable file just means
+// no URL is shown alongside the pinned commit.
+func (r *Repo) SubmoduleURL(rev, path string) string {
+ raw, err := r.Blob(rev, ".gitmodules")
+ if err != nil {
+ return ""
+ }
+ var inSection, sectionMatches bool
+ for _, line := range strings.Split(string(raw), "\n") {
+ line = strings.TrimSpace(line)
+ if strings.HasPrefix(line, "[submodule") {
+ inSection = true
+ sectionMatches = false
+ continue
+ }
+ if !inSection {
+ continue
+ }
+ key, val, ok := strings.Cut(line, "=")
+ if !ok {
+ continue
+ }
+ key, val = strings.TrimSpace(key), strings.TrimSpace(val)
+ switch key {
+ case "path":
+ sectionMatches = val == path
+ case "url":
+ if sectionMatches {
+ return val
+ }
+ }
+ }
+ return ""
+}
+
// ------------------------------------------------------------------ diffs
type FileStat struct {
diff --git a/internal/gitx/git_test.go b/internal/gitx/git_test.go
new file mode 100644
index 0000000..cc3b760
--- /dev/null
+++ b/internal/gitx/git_test.go
@@ -0,0 +1,93 @@
+package gitx
+
+import (
+ "os"
+ "os/exec"
+ "testing"
+)
+
+// runGit drives git directly (not through Repo.run, which doesn't exist
+// yet at setup time) with the same kind of isolation Repo.run uses --
+// GIT_CONFIG_NOSYSTEM and a throwaway HOME -- so the test behaves the same
+// on a machine with commit.gpgsign=true globally as it does in CI.
+func runGit(t *testing.T, dir string, args ...string) {
+ t.Helper()
+ cmd := exec.Command("git", append([]string{"-C", dir, "-c", "commit.gpgsign=false"}, args...)...)
+ cmd.Env = []string{
+ "PATH=" + os.Getenv("PATH"),
+ "HOME=" + dir,
+ "GIT_CONFIG_NOSYSTEM=1",
+ "GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@example.com",
+ "GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@example.com",
+ }
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("git %v: %v\n%s", args, err, out)
+ }
+}
+
+// newTestRepo builds a real repository with one empty commit, a branch
+// "feature/x" (a branch name containing a slash), a second branch
+// "release", and a tag "release/1.0". The last two coexist by construction
+// deliberately: refs/heads and refs/tags are separate namespaces, so
+// "release" (a branch) and "release/1.0" (a tag) can both exist even
+// though a branch "release" and a branch "release/1.0" could not -- git
+// refuses that, since a ref name is a path and "release" can't be both a
+// file and a directory. Opened through gitx.Open, because SplitRefPath
+// resolves against Refs(), which shells out to `git for-each-ref` -- there
+// is no faking that, it has to be a real repo with real refs.
+func newTestRepo(t *testing.T) *Repo {
+ t.Helper()
+ dir := t.TempDir()
+ runGit(t, dir, "init", "-q", "-b", "main")
+ runGit(t, dir, "commit", "-q", "--allow-empty", "-m", "init")
+ runGit(t, dir, "branch", "feature/x")
+ runGit(t, dir, "branch", "release")
+ runGit(t, dir, "tag", "release/1.0")
+
+ r, err := Open(dir)
+ if err != nil {
+ t.Fatalf("Open: %v", err)
+ }
+ return r
+}
+
+// TestSplitRefPath guards the longest-prefix-wins rule that lets ref names
+// contain slashes. A naive split at the first "/" gets both of the two
+// interesting cases here wrong: it would send "feature/x/src/main.go" to
+// ref "feature" (not a ref at all) instead of branch "feature/x", and it
+// would send "release/1.0/docs/readme.md" to branch "release" instead of
+// the more specific tag "release/1.0" -- the real ambiguity SplitRefPath
+// exists to resolve, since both "release" and "release/1.0" are valid refs
+// here and only the longest match is the intended one.
+func TestSplitRefPath(t *testing.T) {
+ r := newTestRepo(t)
+
+ cases := []struct {
+ name string
+ rest string
+ wantRef string
+ wantPath string
+ }{
+ {"single-segment branch with a path", "main/src/main.go", "main", "src/main.go"},
+ {"slashed branch name resolves in full, not just its first segment",
+ "feature/x/src/main.go", "feature/x", "src/main.go"},
+ {"slashed tag wins over a shorter branch that's also a valid prefix",
+ "release/1.0/docs/readme.md", "release/1.0", "docs/readme.md"},
+ {"shorter branch still resolves when no longer candidate matches",
+ "release/README.md", "release", "README.md"},
+ {"slashed branch with no path", "feature/x", "feature/x", ""},
+ {"empty rest falls back to HEAD", "", "main", ""},
+ {"no ref matches: whole thing is a path at HEAD",
+ "no/such/branch/file.go", "main", "no/such/branch/file.go"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ ref, path := r.SplitRefPath(tc.rest)
+ if ref != tc.wantRef || path != tc.wantPath {
+ t.Errorf("SplitRefPath(%q) = (%q, %q), want (%q, %q)",
+ tc.rest, ref, path, tc.wantRef, tc.wantPath)
+ }
+ })
+ }
+}
diff --git a/internal/modules/blob.go b/internal/modules/blob.go
index b2d9b71..dab96e1 100644
--- a/internal/modules/blob.go
+++ b/internal/modules/blob.go
@@ -2,6 +2,7 @@ package modules
import (
"bytes"
+ "html/template"
"net/http"
"strings"
"unicode/utf8"
@@ -10,15 +11,45 @@ import (
)
type Blob struct {
- Path string
- Size int
- Binary bool
- Lines []Line
+ Path string
+ Size int
+ Binary bool
+ Lines []Line
+ Submodule *Submodule
+ Lang string // "json" or "yaml", when the path implies one; "" otherwise
+ ParseErr *ParseNote // set when Lang is non-empty and the content doesn't parse
+ Oversize bool // Lang is set, but the file is too large to parse and index
+}
+
+// Structured reports whether the fold/search/reference tooling applies to
+// this file. A recognised extension is not enough on its own: past
+// maxStructuredSize the view falls back to plain numbered lines.
+func (b Blob) Structured() bool { return b.Lang != "" && !b.Oversize }
+
+// StructuredLimit is the size past which that tooling switches itself off,
+// so the banner explaining the fallback can name the threshold.
+func (b Blob) StructuredLimit() int { return maxStructuredSize }
+
+// Submodule describes a gitlink entry (mode 160000): a pointer to a commit
+// in another repository rather than file content, so there is nothing to
+// diff or display line-by-line.
+type Submodule struct {
+ SHA string
+ Remote string // from .gitmodules, best-effort; empty if not found
}
+// Line is one rendered source line. Everything past Text is structure the
+// blob view uses to fold, filter and cross-reference JSON/YAML, and is zero
+// for every other language.
type Line struct {
N int
- Text string
+ Text template.HTML
+
+ Depth int // nesting level, in indent units
+ FoldTo int // last line of the block this one opens; 0 if it opens none
+ Key string // mapping key declared here, for key-scoped search
+ Anchor *Anchor // YAML anchor declared here
+ Ref *StructRef // YAML alias resolved here
}
func init() { core.Register("blob", blobMod) }
@@ -33,6 +64,12 @@ func blobMod(c *core.Ctx, args ...string) (any, error) {
if path == "" {
return nil, core.Errorf(http.StatusNotFound, "no path")
}
+ if entry, ok, _ := c.Repo.Stat(c.Commit, path); ok && entry.Type == "commit" {
+ return Blob{Path: path, Submodule: &Submodule{
+ SHA: entry.SHA,
+ Remote: c.Repo.SubmoduleURL(c.Commit, path),
+ }}, nil
+ }
raw, err := c.Repo.Blob(c.Commit, path)
if err != nil {
return nil, core.Errorf(http.StatusNotFound, "no such file %q", path)
@@ -47,9 +84,26 @@ func blobMod(c *core.Ctx, args ...string) (any, error) {
b.Binary = true
return b, nil
}
- for i, t := range strings.Split(strings.TrimRight(string(raw), "\n"), "\n") {
+ b.Lang = structuredLang(path)
+ b.Oversize = b.Lang != "" && len(raw) > maxStructuredSize
+ if b.Structured() {
+ b.ParseErr = validateStructured(b.Lang, raw)
+ }
+
+ hl, ok := highlightLines(path, raw)
+ if !ok {
+ for _, t := range strings.Split(strings.TrimRight(string(raw), "\n"), "\n") {
+ hl = append(hl, template.HTML(template.HTMLEscapeString(t)))
+ }
+ } else if b.Structured() {
+ hl = withIndentGuides(hl, indentUnit(raw))
+ }
+ for i, t := range hl {
b.Lines = append(b.Lines, Line{N: i + 1, Text: t})
}
+ if b.Structured() {
+ annotateStructure(b.Lines, raw, b.Lang)
+ }
return b, nil
}
diff --git a/internal/modules/blob_test.go b/internal/modules/blob_test.go
new file mode 100644
index 0000000..70762f8
--- /dev/null
+++ b/internal/modules/blob_test.go
@@ -0,0 +1,121 @@
+package modules
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "gsg/internal/core"
+ "gsg/internal/gitx"
+)
+
+// blobCtx commits files into a throwaway repository and returns a Ctx
+// pointing at it. Isolation matches internal/gitx's own test helper, so a
+// machine with commit.gpgsign=true globally behaves like CI.
+func blobCtx(t *testing.T, files map[string]string) *core.Ctx {
+ t.Helper()
+ dir := t.TempDir()
+ env := []string{
+ "PATH=" + os.Getenv("PATH"),
+ "HOME=" + dir,
+ "GIT_CONFIG_NOSYSTEM=1",
+ "GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@example.com",
+ "GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@example.com",
+ }
+ git := func(args ...string) {
+ t.Helper()
+ cmd := exec.Command("git", append([]string{"-C", dir, "-c", "commit.gpgsign=false"}, args...)...)
+ cmd.Env = env
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("git %v: %v\n%s", args, err, out)
+ }
+ }
+ git("init", "-q", ".")
+ for name, body := range files {
+ if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ git("add", "-A")
+ git("commit", "-qm", "fixture")
+
+ repo, err := gitx.Open(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sha, err := repo.Resolve("HEAD")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return &core.Ctx{Repo: repo, Ref: "HEAD", Commit: sha}
+}
+
+func blobAt(t *testing.T, c *core.Ctx, path string) Blob {
+ t.Helper()
+ c.Path = path
+ v, err := blobMod(c)
+ if err != nil {
+ t.Fatalf("blob %q: %v", path, err)
+ }
+ b, ok := v.(Blob)
+ if !ok {
+ t.Fatalf("blob %q: got %T", path, v)
+ }
+ return b
+}
+
+// Past maxStructuredSize a config file is served as plain numbered lines:
+// no parse, no fold ranges, no anchor resolution -- and Oversize set so the
+// view can say why rather than silently dropping the tooling.
+func TestStructuredSizeGate(t *testing.T) {
+ var big strings.Builder
+ big.WriteString("items: &items\n")
+ for i := 0; big.Len() <= maxStructuredSize; i++ {
+ fmt.Fprintf(&big, " - name: item-%d\n value: %d\n", i, i)
+ }
+ small := "items: &items\n - name: a\ncopy: *items\n"
+
+ c := blobCtx(t, map[string]string{"big.yaml": big.String(), "small.yaml": small})
+
+ b := blobAt(t, c, "big.yaml")
+ if b.Lang != "yaml" {
+ t.Errorf("Lang = %q, want yaml", b.Lang)
+ }
+ if !b.Oversize || b.Structured() {
+ t.Errorf("Oversize = %v, Structured = %v; want true, false", b.Oversize, b.Structured())
+ }
+ if b.ParseErr != nil {
+ t.Errorf("oversize file was parsed anyway: %+v", b.ParseErr)
+ }
+ if len(b.Lines) == 0 {
+ t.Fatal("oversize file rendered no lines")
+ }
+ for _, l := range b.Lines {
+ if l.FoldTo != 0 || l.Depth != 0 || l.Key != "" || l.Anchor != nil || l.Ref != nil {
+ t.Fatalf("line %d carries structure past the size limit: %+v", l.N, l)
+ }
+ }
+
+ s := blobAt(t, c, "small.yaml")
+ if !s.Structured() || s.Oversize {
+ t.Fatalf("small file: Structured = %v, Oversize = %v", s.Structured(), s.Oversize)
+ }
+ if s.Lines[0].Anchor == nil || s.Lines[2].Ref == nil {
+ t.Error("small file lost its anchor/alias annotations")
+ }
+ if s.Lines[0].FoldTo != 2 {
+ t.Errorf("small file FoldTo = %d, want 2", s.Lines[0].FoldTo)
+ }
+}
+
+// A non-config file is never structured, whatever its size.
+func TestPlainFileIsNotStructured(t *testing.T) {
+ c := blobCtx(t, map[string]string{"main.go": "package main\n\nfunc main() {}\n"})
+ b := blobAt(t, c, "main.go")
+ if b.Structured() || b.Oversize || b.Lang != "" {
+ t.Errorf("go file: Lang = %q, Structured = %v, Oversize = %v", b.Lang, b.Structured(), b.Oversize)
+ }
+}
diff --git a/internal/modules/commit.go b/internal/modules/commit.go
index 5a037f3..713c1e8 100644
--- a/internal/modules/commit.go
+++ b/internal/modules/commit.go
@@ -17,7 +17,7 @@ func commitMod(c *core.Ctx, args ...string) (any, error) {
if c.Commit == "" {
return nil, core.Errorf(http.StatusNotFound, "no commit")
}
- log, err := c.Repo.Log(c.Commit, 1)
+ log, err := c.Repo.Log(c.Commit, 1, 0, false)
if err != nil {
return nil, err
}
diff --git a/internal/modules/compare.go b/internal/modules/compare.go
index 980f1bc..b58a1eb 100644
--- a/internal/modules/compare.go
+++ b/internal/modules/compare.go
@@ -52,7 +52,7 @@ func compareMod(c *core.Ctx, args ...string) (any, error) {
}
cmp.Diff = d
- if log, err := c.Repo.Log(from+".."+head, 250); err == nil {
+ if log, err := c.Repo.Log(from+".."+head, 250, 0, false); err == nil {
cmp.Commits = log
}
return cmp, nil
diff --git a/internal/modules/example_authors.go b/internal/modules/example_authors.go
index fb30007..7ca32c3 100644
--- a/internal/modules/example_authors.go
+++ b/internal/modules/example_authors.go
@@ -30,7 +30,7 @@ func authorsMod(c *core.Ctx, args ...string) (any, error) {
if rev == "" {
rev = c.Ref
}
- log, err := c.Repo.Log(rev, n)
+ log, err := c.Repo.Log(rev, n, 0, false)
if err != nil {
return nil, err
}
diff --git a/internal/modules/graph.go b/internal/modules/graph.go
index c513c1a..db71a0e 100644
--- a/internal/modules/graph.go
+++ b/internal/modules/graph.go
@@ -21,6 +21,10 @@ import (
type Graph struct {
Rows []Row
Lanes int
+
+ Ofs, PageSize int
+ HasPrev, HasNext bool
+ PrevOfs, NextOfs int
}
type Row struct {
@@ -43,15 +47,29 @@ type Row struct {
func init() { core.Register("graph", graphMod) }
-// graph: the DAG across every ref. {{ mod "graph" "120" }}
+// graph: the DAG across every ref. {{ mod "graph" "120" }} -- default
+// core.GraphPageSize. Paginated via the ?ofs= query param on the graph
+// route (see buildCtx), which core.GraphPageSize must match.
+//
+// Lane assignment below is a single forward pass that carries state
+// (`active`) across every row, so a page can't be computed by slicing the
+// git fetch with --skip -- that would reset `active` at the page boundary
+// and corrupt lane continuity. Instead every request walks the full range
+// from the top of history through the end of the requested page, and only
+// the rendered rows are sliced down to the page afterward, once Lanes and
+// each row's Rail SVG have already been computed against the full range.
func graphMod(c *core.Ctx, args ...string) (any, error) {
- n := 150
+ n := core.GraphPageSize
if len(args) > 0 {
if v, err := strconv.Atoi(args[0]); err == nil && v > 0 {
n = v
}
}
- commits, err := c.Repo.LogAll(n)
+ ofs, _ := strconv.Atoi(c.Var("ofs"))
+ if ofs < 0 {
+ ofs = 0
+ }
+ commits, err := c.Repo.LogAll(ofs + n + 1) // from the top; no --skip, see above
if err != nil {
return nil, err
}
@@ -115,6 +133,24 @@ func graphMod(c *core.Ctx, args ...string) (any, error) {
if g.Lanes == 0 {
g.Lanes = 1
}
+
+ total := len(g.Rows)
+ end := ofs + n
+ hasNext := total > end
+ if end > total {
+ end = total
+ }
+ start := ofs
+ if start > total {
+ start = total
+ }
+ g.Rows = g.Rows[start:end]
+ g.Ofs, g.PageSize = ofs, n
+ g.HasPrev, g.PrevOfs = ofs > 0, ofs-n
+ if g.PrevOfs < 0 {
+ g.PrevOfs = 0
+ }
+ g.HasNext, g.NextOfs = hasNext, end
return g, nil
}
diff --git a/internal/modules/highlight.go b/internal/modules/highlight.go
new file mode 100644
index 0000000..8c7431d
--- /dev/null
+++ b/internal/modules/highlight.go
@@ -0,0 +1,79 @@
+package modules
+
+import (
+ "html/template"
+ "strings"
+
+ "github.com/alecthomas/chroma/v2"
+ "github.com/alecthomas/chroma/v2/lexers"
+)
+
+// maxHighlightSize bounds how much source chroma will tokenise. Past this,
+// a file falls back to plain (still viewable, just uncoloured) text rather
+// than risk a slow lex on something pathological.
+const maxHighlightSize = 512 * 1024
+
+// highlightLines lexes src by the language implied by path and returns one
+// escaped, span-wrapped HTML fragment per line. ok is false when path has no
+// recognised language or src is too large to bother lexing; callers should
+// fall back to plain escaped lines in that case.
+func highlightLines(path string, src []byte) (lines []template.HTML, ok bool) {
+ if len(src) > maxHighlightSize {
+ return nil, false
+ }
+ lexer := lexers.Match(path)
+ if lexer == nil {
+ return nil, false
+ }
+ it, err := chroma.Coalesce(lexer).Tokenise(nil, string(src))
+ if err != nil {
+ return nil, false
+ }
+ for _, toks := range chroma.SplitTokensIntoLines(it.Tokens()) {
+ var b strings.Builder
+ for i, tok := range toks {
+ // SplitTokensIntoLines keeps each line's newline attached to
+ // its last token; drop it so it doesn't render as a blank
+ // row inside the (white-space: pre) table cell.
+ if i == len(toks)-1 {
+ tok.Value = strings.TrimSuffix(tok.Value, "\n")
+ }
+ esc := template.HTMLEscapeString(tok.Value)
+ if cls := tokenClass(tok.Type); cls != "" {
+ b.WriteString(`<span class="`)
+ b.WriteString(cls)
+ b.WriteString(`">`)
+ b.WriteString(esc)
+ b.WriteString(`</span>`)
+ } else {
+ b.WriteString(esc)
+ }
+ }
+ lines = append(lines, template.HTML(b.String()))
+ }
+ return lines, true
+}
+
+// tokenClass buckets chroma's ~70 token types down to the handful of colours
+// the theme actually defines (see --syn-* in base.css). Punctuation,
+// operators and plain names are left uncoloured on purpose -- a source line
+// with every token tinted reads as noise, not signal.
+func tokenClass(t chroma.TokenType) string {
+ switch {
+ case t.InCategory(chroma.Comment):
+ return "tok-c"
+ case t.InCategory(chroma.Keyword):
+ return "tok-k"
+ case t.InSubCategory(chroma.LiteralString):
+ return "tok-s"
+ case t.InSubCategory(chroma.LiteralNumber):
+ return "tok-n"
+ case t == chroma.NameFunction, t == chroma.NameFunctionMagic,
+ t == chroma.NameClass, t == chroma.NameNamespace,
+ t == chroma.NameBuiltin, t == chroma.NameBuiltinPseudo,
+ t == chroma.NameTag, t == chroma.NameDecorator:
+ return "tok-fn"
+ default:
+ return ""
+ }
+}
diff --git a/internal/modules/log.go b/internal/modules/log.go
index 37fb3b1..94dfd33 100644
--- a/internal/modules/log.go
+++ b/internal/modules/log.go
@@ -4,21 +4,56 @@ import (
"strconv"
"gsg/internal/core"
+ "gsg/internal/gitx"
)
func init() { core.Register("log", logMod) }
-// log: recent commits. {{ mod "log" "20" }} -- default 25, "0" = all.
+// LogPage is one page of commit history, with enough to render prev/next
+// links without a separate count query (see the n+1 fetch trick below).
+type LogPage struct {
+ Commits []gitx.Commit
+ Ofs, PageSize int
+ HasPrev, HasNext bool
+ PrevOfs, NextOfs int
+}
+
+// log: a page of recent commits. {{ mod "log" "20" }} -- default
+// core.LogPageSize, "0" = all. Paginated via the ?ofs= query param on the
+// log route (see buildCtx), which core.LogPageSize must match.
func logMod(c *core.Ctx, args ...string) (any, error) {
- n := 25
+ n := core.LogPageSize
if len(args) > 0 {
if v, err := strconv.Atoi(args[0]); err == nil {
n = v
}
}
+ ofs, _ := strconv.Atoi(c.Var("ofs"))
+ if ofs < 0 {
+ ofs = 0
+ }
rev := c.Commit
if rev == "" {
rev = c.Ref
}
- return c.Repo.Log(rev, n)
+
+ fetch := n
+ if n > 0 {
+ fetch = n + 1 // one extra row to detect a next page
+ }
+ commits, err := c.Repo.Log(rev, fetch, ofs, true)
+ if err != nil {
+ return nil, err
+ }
+
+ page := LogPage{Ofs: ofs, PageSize: n, HasPrev: ofs > 0, PrevOfs: ofs - n}
+ if page.PrevOfs < 0 {
+ page.PrevOfs = 0
+ }
+ if n > 0 && len(commits) > n {
+ commits = commits[:n]
+ page.HasNext, page.NextOfs = true, ofs+n
+ }
+ page.Commits = commits
+ return page, nil
}
diff --git a/internal/modules/meta.go b/internal/modules/meta.go
index f6f9dad..0ba257a 100644
--- a/internal/modules/meta.go
+++ b/internal/modules/meta.go
@@ -20,7 +20,7 @@ func init() { core.Register("meta", metaMod) }
// the Ctx cache.
func metaMod(c *core.Ctx, args ...string) (any, error) {
m := Meta{RepoInfo: c.Info, DefaultRef: c.Repo.HeadRef()}
- if log, err := c.Repo.Log(c.Ref, 1); err == nil && len(log) > 0 {
+ if log, err := c.Repo.Log(c.Ref, 1, 0, false); err == nil && len(log) > 0 {
m.LastCommit = log[0].When
}
return m, nil
diff --git a/internal/modules/readme.go b/internal/modules/readme.go
index 82642e0..ada1101 100644
--- a/internal/modules/readme.go
+++ b/internal/modules/readme.go
@@ -23,12 +23,18 @@ func readmeMod(c *core.Ctx, args ...string) (any, error) {
if rev == "" {
rev = c.Ref
}
- entries, err := c.Repo.Tree(rev, c.Path)
+ // Same (rev, path) listing the `tree` module already computes for this
+ // page -- go through it instead of forking a second identical ls-tree.
+ v, err := c.Mod("tree")
if err != nil {
return nil, nil
}
+ t, ok := v.(Tree)
+ if !ok {
+ return nil, nil
+ }
present := map[string]bool{}
- for _, e := range entries {
+ for _, e := range t.Entries {
if e.Type == "blob" {
present[e.Name] = true
}
diff --git a/internal/modules/repos.go b/internal/modules/repos.go
index 9709b25..66bc6f6 100644
--- a/internal/modules/repos.go
+++ b/internal/modules/repos.go
@@ -3,6 +3,7 @@ package modules
import (
"fmt"
"sort"
+ "sync"
"time"
"gsg/internal/core"
@@ -15,21 +16,50 @@ type RepoSummary struct {
func init() { core.Register("repos", reposMod) }
+// reposCacheTTL bounds how stale the index page's "last updated" ordering
+// and repo list can be. reposMod is site-scoped, so it never gets a
+// resolved commit and therefore never touches the module cache (see
+// Ctx.CacheKey) -- without this, every hit to "/" or the JSON index forks
+// git twice per repo, unconditionally, no matter how often the page is
+// requested. A few seconds of staleness here is the same trade-off the
+// fsnotify debounce already makes for repo discovery, just applied to one
+// more surface.
+const reposCacheTTL = 5 * time.Second
+
+var reposCache struct {
+ mu sync.Mutex
+ at time.Time
+ val []RepoSummary
+}
+
// repos: every visible repository, newest activity first.
// Site-scoped -- does not touch c.Repo, so it is safe on the site Ctx.
func reposMod(c *core.Ctx, args ...string) (any, error) {
- out := make([]RepoSummary, 0, len(c.Site.Repos))
- for _, h := range c.Site.Repos {
+ reposCache.mu.Lock()
+ if !reposCache.at.IsZero() && time.Since(reposCache.at) < reposCacheTTL {
+ out := reposCache.val
+ reposCache.mu.Unlock()
+ return out, nil
+ }
+ reposCache.mu.Unlock()
+
+ list := c.Site.RepoList()
+ out := make([]RepoSummary, 0, len(list))
+ for _, h := range list {
if h.Info.Hidden {
continue
}
s := RepoSummary{RepoInfo: h.Info}
- if log, err := h.Repo.Log(h.Repo.HeadRef(), 1); err == nil && len(log) > 0 {
+ if log, err := h.Repo.Log(h.Repo.HeadRef(), 1, 0, false); err == nil && len(log) > 0 {
s.LastCommit = log[0].When
}
out = append(out, s)
}
sort.Slice(out, func(i, j int) bool { return out[i].LastCommit.After(out[j].LastCommit) })
+
+ reposCache.mu.Lock()
+ reposCache.val, reposCache.at = out, time.Now()
+ reposCache.mu.Unlock()
return out, nil
}
diff --git a/internal/modules/structured.go b/internal/modules/structured.go
new file mode 100644
index 0000000..b3f1093
--- /dev/null
+++ b/internal/modules/structured.go
@@ -0,0 +1,364 @@
+package modules
+
+import (
+ "bytes"
+ "encoding/json"
+ "html/template"
+ "regexp"
+ "strconv"
+ "strings"
+
+ "gopkg.in/yaml.v3"
+)
+
+// ParseNote reports why a JSON/YAML blob failed to parse, so the blob view
+// can point at the offending line instead of leaving a reader to guess.
+// Line is 0 when the underlying error can't be pinned to one.
+type ParseNote struct {
+ Line int
+ Msg string
+}
+
+// Anchor is a YAML anchor declared on a line, along with how many alias
+// sites in the file point back at it.
+type Anchor struct {
+ Name string
+ Uses int
+}
+
+// StructRef is a resolved YAML alias: which anchor it names, the line that
+// anchor is declared on, and the value it stands for rendered back to YAML.
+// One per line -- a flow sequence like [*a, *b] resolves only its first.
+type StructRef struct {
+ Name string
+ Line int
+ Preview string
+}
+
+// maxStructuredSize bounds the work one file may cost the structured view:
+// a full parse on the server, and a pass over every row in the browser at
+// load. It matches maxHighlightSize on purpose -- past that point the file
+// is already served as plain, unhighlighted text with no indent guides, and
+// folding a file that has neither would be a strange half-feature. Half a
+// megabyte is far above any hand-written config and below the size where a
+// modest laptop notices the per-row work.
+const maxStructuredSize = maxHighlightSize
+
+// structuredLang returns "json" or "yaml" for a recognised config
+// extension, "" otherwise. The blob view only spends the extra parse and
+// indent-guide pass on formats where nesting depth is the whole point.
+func structuredLang(path string) string {
+ p := strings.ToLower(path)
+ switch {
+ case strings.HasSuffix(p, ".json"):
+ return "json"
+ case strings.HasSuffix(p, ".yaml"), strings.HasSuffix(p, ".yml"):
+ return "yaml"
+ default:
+ return ""
+ }
+}
+
+func validateStructured(lang string, raw []byte) *ParseNote {
+ var err error
+ switch lang {
+ case "json":
+ err = json.Unmarshal(raw, new(any))
+ case "yaml":
+ err = yaml.Unmarshal(raw, new(any))
+ default:
+ return nil
+ }
+ if err == nil {
+ return nil
+ }
+ return &ParseNote{Line: parseErrorLine(lang, raw, err), Msg: err.Error()}
+}
+
+var yamlLineRe = regexp.MustCompile(`line (\d+)`)
+
+func parseErrorLine(lang string, raw []byte, err error) int {
+ if lang == "json" {
+ switch e := err.(type) {
+ case *json.SyntaxError:
+ return bytes.Count(raw[:e.Offset], []byte("\n")) + 1
+ case *json.UnmarshalTypeError:
+ return bytes.Count(raw[:e.Offset], []byte("\n")) + 1
+ }
+ return 0
+ }
+ // yaml.v3 errors are plain strings of the form "yaml: line N: ...", or
+ // for TypeError one such string per bad field -- take the first.
+ if m := yamlLineRe.FindStringSubmatch(err.Error()); m != nil {
+ n, _ := strconv.Atoi(m[1])
+ return n
+ }
+ return 0
+}
+
+// indentUnit finds the smallest non-zero run of leading spaces across
+// non-blank lines, so a 4-space file gets one guide per level and a
+// 2-space file doesn't get a spurious extra one.
+func indentUnit(raw []byte) int {
+ unit := 0
+ for _, line := range bytes.Split(raw, []byte("\n")) {
+ n := 0
+ for n < len(line) && line[n] == ' ' {
+ n++
+ }
+ if n == 0 || n == len(line) {
+ continue // blank or all-whitespace
+ }
+ if unit == 0 || n < unit {
+ unit = n
+ }
+ }
+ if unit == 0 {
+ return 2
+ }
+ return unit
+}
+
+// annotateStructure fills in the per-line structure the blob view needs to
+// fold, filter and cross-reference a config file: nesting depth, the extent
+// of the block each line opens, the mapping key it declares, and (YAML only)
+// the anchors and aliases tying parts of the file together.
+//
+// It works off raw rather than the highlighted HTML: indentation is the one
+// signal that means the same thing in both languages, and it survives
+// minified or oddly-formatted input by simply finding nothing to fold.
+func annotateStructure(lines []Line, raw []byte, lang string) {
+ src := bytes.Split(raw, []byte("\n"))
+ unit := indentUnit(raw)
+
+ ind := make([]int, len(src))
+ for i, l := range src {
+ ind[i] = lineIndent(l)
+ }
+ ends := foldEnds(ind)
+
+ keyRe := jsonKeyRe
+ if lang == "yaml" {
+ keyRe = yamlKeyRe
+ }
+ for i := range src {
+ if i >= len(lines) {
+ break
+ }
+ if ind[i] >= 0 {
+ lines[i].Depth = ind[i] / unit
+ if e := ends[i]; e > 0 && e <= len(lines) {
+ lines[i].FoldTo = e
+ }
+ }
+ if m := keyRe.FindSubmatch(src[i]); m != nil {
+ for _, g := range m[1:] {
+ if len(g) > 0 {
+ lines[i].Key = string(g)
+ break
+ }
+ }
+ }
+ }
+ if lang != "yaml" {
+ return
+ }
+ anchors, refs := yamlAnchors(src)
+ for n, a := range anchors {
+ if n >= 1 && n <= len(lines) {
+ lines[n-1].Anchor = a
+ }
+ }
+ for n, r := range refs {
+ if n >= 1 && n <= len(lines) {
+ lines[n-1].Ref = r
+ }
+ }
+}
+
+// lineIndent counts leading spaces, or returns -1 for a line that carries no
+// structure (blank or whitespace-only) so folding steps over it rather than
+// treating column 0 as a dedent.
+func lineIndent(line []byte) int {
+ n := 0
+ for n < len(line) && line[n] == ' ' {
+ n++
+ }
+ if n == len(bytes.TrimRight(line, " \t\r")) {
+ return -1
+ }
+ return n
+}
+
+// foldEnds returns, per line, the 1-based number of the last line belonging
+// to the block that line opens -- 0 when it opens nothing. A line opens a
+// block when the next line carrying structure is indented further, and the
+// block runs until indentation returns to that line's own level or less.
+// Blank lines between siblings are absorbed; blank lines trailing a block
+// are not.
+func foldEnds(ind []int) []int {
+ ends := make([]int, len(ind))
+ type frame struct {
+ ind, idx int
+ child bool
+ }
+ var stack []frame
+ prev := -1 // last line carrying structure
+ for i, in := range ind {
+ if in < 0 {
+ continue
+ }
+ for len(stack) > 0 && stack[len(stack)-1].ind >= in {
+ if t := stack[len(stack)-1]; t.child {
+ ends[t.idx] = prev + 1
+ }
+ stack = stack[:len(stack)-1]
+ }
+ if len(stack) > 0 {
+ stack[len(stack)-1].child = true
+ }
+ stack = append(stack, frame{ind: in, idx: i})
+ prev = i
+ }
+ for _, t := range stack {
+ if t.child {
+ ends[t.idx] = prev + 1
+ }
+ }
+ return ends
+}
+
+var (
+ // The key a line declares, used to scope search to keys rather than
+ // whole lines. Both are deliberately shallow: a miss costs a narrower
+ // search, not a wrong render.
+ yamlKeyRe = regexp.MustCompile(`^\s*(?:-\s+)?(?:"([^"]*)"|'([^']*)'|([^\s#"'][^:#]*?))\s*:(?:\s|$)`)
+ jsonKeyRe = regexp.MustCompile(`^\s*"((?:[^"\\]|\\.)*)"\s*:`)
+)
+
+// yamlAnchors resolves every alias in the file to the line its anchor is
+// declared on, keyed by 1-based line number. Anchors are per-document, so
+// the whole stream is decoded document by document -- a k8s manifest that
+// defines its anchors in the second document would otherwise come back
+// empty. A malformed document ends the walk with whatever was found first;
+// the parse-error banner already reports the failure itself.
+func yamlAnchors(src [][]byte) (map[int]*Anchor, map[int]*StructRef) {
+ anchors := map[int]*Anchor{}
+ refs := map[int]*StructRef{}
+ dec := yaml.NewDecoder(bytes.NewReader(bytes.Join(src, []byte("\n"))))
+ for {
+ var doc yaml.Node
+ if err := dec.Decode(&doc); err != nil {
+ break
+ }
+ walkYAML(&doc, src, anchors, refs)
+ }
+ return anchors, refs
+}
+
+func walkYAML(n *yaml.Node, src [][]byte, anchors map[int]*Anchor, refs map[int]*StructRef) {
+ if n.Anchor != "" {
+ if line := anchorLine(src, n.Anchor, n.Line); line > 0 {
+ if _, ok := anchors[line]; !ok {
+ anchors[line] = &Anchor{Name: n.Anchor}
+ }
+ }
+ }
+ if n.Kind == yaml.AliasNode && n.Alias != nil {
+ target := anchorLine(src, n.Value, n.Alias.Line)
+ if target > 0 {
+ if _, ok := refs[n.Line]; !ok {
+ refs[n.Line] = &StructRef{Name: n.Value, Line: target, Preview: nodePreview(n.Alias)}
+ }
+ if a, ok := anchors[target]; ok {
+ a.Uses++
+ }
+ }
+ }
+ for _, c := range n.Content {
+ walkYAML(c, src, anchors, refs)
+ }
+}
+
+// anchorLine locates the line the "&name" token sits on. A node's own Line
+// is where its *value* begins, which for a block mapping is the line after
+// the key the anchor was written on -- so scan back from there for the
+// token itself and point at that instead.
+func anchorLine(src [][]byte, name string, at int) int {
+ tok := []byte("&" + name)
+ if at > len(src) {
+ at = len(src)
+ }
+ for i := at - 1; i >= 0 && i > at-64; i-- {
+ j := bytes.Index(src[i], tok)
+ if j < 0 {
+ continue
+ }
+ if k := j + len(tok); k < len(src[i]) && isAnchorChar(src[i][k]) {
+ continue // &namelonger
+ }
+ return i + 1
+ }
+ return 0
+}
+
+func isAnchorChar(b byte) bool {
+ return b == '-' || b == '_' || b == '.' ||
+ (b >= '0' && b <= '9') || (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')
+}
+
+// nodePreview renders what an alias actually stands for, short enough to sit
+// in a tooltip. The anchor name is stripped from the copy so the preview
+// reads as the value, not as its declaration.
+func nodePreview(n *yaml.Node) string {
+ c := *n
+ c.Anchor = ""
+ var buf bytes.Buffer
+ enc := yaml.NewEncoder(&buf)
+ enc.SetIndent(2) // yaml.Marshal's default of 4 doesn't match most files
+ if err := enc.Encode(&c); err != nil {
+ return ""
+ }
+ enc.Close()
+ s := strings.TrimRight(buf.String(), "\n")
+ if ls := strings.Split(s, "\n"); len(ls) > 12 {
+ s = strings.Join(append(ls[:12], "…"), "\n")
+ }
+ if len(s) > 480 {
+ s = strings.ToValidUTF8(s[:480], "") + "…"
+ }
+ return s
+}
+
+// withIndentGuides prefixes each line's leading spaces with one guide span
+// per nesting level, so deeply nested JSON/YAML reads like a tree instead
+// of a wall of spaces. Leading whitespace is always plain, unwrapped text
+// at this point (see highlightLines' Text/TextWhitespace handling), so
+// trimming it back off the rendered HTML here is safe.
+func withIndentGuides(lines []template.HTML, unit int) []template.HTML {
+ out := make([]template.HTML, len(lines))
+ for i, l := range lines {
+ s := string(l)
+ n := 0
+ for n < len(s) && s[n] == ' ' {
+ n++
+ }
+ if n < unit {
+ out[i] = l
+ continue
+ }
+ var b strings.Builder
+ levels, rem := n/unit, n%unit
+ for j := 0; j < levels; j++ {
+ b.WriteString(`<span class="ind" style="width:`)
+ b.WriteString(strconv.Itoa(unit))
+ b.WriteString(`ch"></span>`)
+ }
+ if rem > 0 {
+ b.WriteString(strings.Repeat(" ", rem))
+ }
+ b.WriteString(s[n:])
+ out[i] = template.HTML(b.String())
+ }
+ return out
+}
diff --git a/internal/modules/structured_test.go b/internal/modules/structured_test.go
new file mode 100644
index 0000000..4da0c4f
--- /dev/null
+++ b/internal/modules/structured_test.go
@@ -0,0 +1,158 @@
+package modules
+
+import (
+ "html/template"
+ "strings"
+ "testing"
+)
+
+// lines builds the Line slice annotateStructure expects, mirroring what
+// blobMod produces before the structure pass runs.
+func lines(raw string) []Line {
+ out := []Line{}
+ for i, t := range strings.Split(raw, "\n") {
+ out = append(out, Line{N: i + 1, Text: template.HTML(t)})
+ }
+ return out
+}
+
+const sampleYAML = `defaults: &defaults
+ adapter: postgres
+ pool: 5
+
+development:
+ <<: *defaults
+ database: dev
+
+test:
+ <<: *defaults
+ database: test
+ hosts:
+ - a
+ - b
+`
+
+func TestFoldRangesYAML(t *testing.T) {
+ ls := lines(sampleYAML)
+ annotateStructure(ls, []byte(sampleYAML), "yaml")
+
+ want := map[int]int{
+ 1: 3, // defaults: block ends at "pool: 5", not the blank line after
+ 5: 7, // development:
+ 9: 14, // test:, stopping short of the empty line 15
+ 12: 14, // hosts:
+ }
+ for _, l := range ls {
+ if got, ok := want[l.N]; ok {
+ if l.FoldTo != got {
+ t.Errorf("line %d: FoldTo = %d, want %d", l.N, l.FoldTo, got)
+ }
+ } else if l.FoldTo != 0 {
+ t.Errorf("line %d: FoldTo = %d, want none", l.N, l.FoldTo)
+ }
+ }
+ if ls[1].Depth != 1 {
+ t.Errorf("line 2 depth = %d, want 1", ls[1].Depth)
+ }
+ if ls[13].Depth != 2 {
+ t.Errorf("line 14 depth = %d, want 2", ls[13].Depth)
+ }
+}
+
+func TestKeysAndAnchors(t *testing.T) {
+ ls := lines(sampleYAML)
+ annotateStructure(ls, []byte(sampleYAML), "yaml")
+
+ if ls[0].Key != "defaults" {
+ t.Errorf("line 1 key = %q, want %q", ls[0].Key, "defaults")
+ }
+ if ls[13].Key != "" {
+ t.Errorf("line 14 (sequence item) key = %q, want none", ls[13].Key)
+ }
+
+ // The anchor is reported on the line the &token is written on, not on
+ // the line the mapping it names begins.
+ a := ls[0].Anchor
+ if a == nil {
+ t.Fatal("line 1: no anchor")
+ }
+ if a.Name != "defaults" || a.Uses != 2 {
+ t.Errorf("anchor = %+v, want {defaults 2}", *a)
+ }
+
+ for _, n := range []int{6, 10} {
+ r := ls[n-1].Ref
+ if r == nil {
+ t.Fatalf("line %d: no ref", n)
+ }
+ if r.Name != "defaults" || r.Line != 1 {
+ t.Errorf("line %d ref = %+v, want defaults@1", n, *r)
+ }
+ if !strings.Contains(r.Preview, "adapter: postgres") {
+ t.Errorf("line %d preview = %q, want the resolved mapping", n, r.Preview)
+ }
+ }
+}
+
+// Anchors defined in the second document of a stream are still resolved:
+// yaml.Unmarshal would only ever see the first.
+func TestMultiDocumentAnchors(t *testing.T) {
+ const src = `---
+kind: First
+---
+base: &b
+ x: 1
+copy: *b
+`
+ ls := lines(src)
+ annotateStructure(ls, []byte(src), "yaml")
+
+ if ls[3].Anchor == nil || ls[3].Anchor.Name != "b" {
+ t.Fatalf("line 4 anchor = %+v, want b", ls[3].Anchor)
+ }
+ if r := ls[5].Ref; r == nil || r.Line != 4 {
+ t.Fatalf("line 6 ref = %+v, want b@4", r)
+ }
+}
+
+func TestFoldRangesJSON(t *testing.T) {
+ const src = `{
+ "name": "gsg",
+ "deps": {
+ "a": 1
+ },
+ "list": [
+ 2
+ ]
+}`
+ ls := lines(src)
+ annotateStructure(ls, []byte(src), "json")
+
+ if ls[0].FoldTo != 8 {
+ t.Errorf("line 1 FoldTo = %d, want 8", ls[0].FoldTo)
+ }
+ if ls[2].FoldTo != 4 {
+ t.Errorf("line 3 FoldTo = %d, want 4", ls[2].FoldTo)
+ }
+ if ls[5].FoldTo != 7 {
+ t.Errorf("line 6 FoldTo = %d, want 7", ls[5].FoldTo)
+ }
+ if ls[1].Key != "name" {
+ t.Errorf("line 2 key = %q, want %q", ls[1].Key, "name")
+ }
+ // No anchors outside YAML, and a brace inside a string is not structure.
+ if ls[1].Anchor != nil || ls[1].Ref != nil {
+ t.Error("JSON line carries anchor/ref data")
+ }
+}
+
+// Minified JSON has no indentation to fold on; it must degrade to a plain
+// view rather than producing bogus ranges.
+func TestMinifiedJSONHasNoFolds(t *testing.T) {
+ const src = `{"a":{"b":[1,2]},"c":3}`
+ ls := lines(src)
+ annotateStructure(ls, []byte(src), "json")
+ if ls[0].FoldTo != 0 {
+ t.Errorf("FoldTo = %d, want 0", ls[0].FoldTo)
+ }
+}
diff --git a/internal/site/routes.go b/internal/site/routes.go
index e0a6d8e..6d31993 100644
--- a/internal/site/routes.go
+++ b/internal/site/routes.go
@@ -19,13 +19,11 @@ func Routes() []core.Route {
Render: core.JSON{Build: api.IndexEndpoint}},
// ---- per repository ----------------------------------------------
+ // NavLabel order below is the order tabs appear in the repo-scoped
+ // nav (top bar and page-nav chips) -- see core.BuildNav.
{Name: "repo",
Pattern: "GET /{repo}/{$}",
- Render: core.View{Template: "repo.html"}},
-
- {Name: "refs",
- Pattern: "GET /{repo}/refs/{$}",
- Render: core.View{Template: "refs.html"}},
+ Render: core.View{Template: "tree.html"}},
{Name: "api-repo",
Pattern: "GET /{repo}/api/repo.json",
@@ -33,14 +31,14 @@ func Routes() []core.Route {
// {rest...} fuses ref and path; SplitRefPath separates them by
// longest-matching ref, so feature/x/src/main.go works.
- {Name: "log",
- Pattern: "GET /{repo}/log/{rest...}",
- Render: core.View{Template: "log.html"}},
-
- {Name: "tree",
+ {Name: "tree", NavLabel: "files",
Pattern: "GET /{repo}/tree/{rest...}",
Render: core.View{Template: "tree.html"}},
+ {Name: "log", NavLabel: "log",
+ Pattern: "GET /{repo}/log/{rest...}",
+ Render: core.View{Template: "log.html"}},
+
{Name: "blob",
Pattern: "GET /{repo}/blob/{rest...}",
Render: core.View{Template: "blob.html"}},
@@ -51,10 +49,14 @@ func Routes() []core.Route {
Render: core.Raw{Module: "blobraw"}},
// The DAG across every ref.
- {Name: "graph",
+ {Name: "graph", NavLabel: "graph",
Pattern: "GET /{repo}/graph/{$}",
Render: core.View{Template: "graph.html"}},
+ {Name: "refs", NavLabel: "refs",
+ Pattern: "GET /{repo}/refs/{$}",
+ Render: core.View{Template: "refs.html"}},
+
// Arbitrary two-commit diff: /demo/compare/main...feature
{Name: "compare",
Pattern: "GET /{repo}/compare/{range}",
diff --git a/main.go b/main.go
index ccffdd7..2faa1d3 100644
--- a/main.go
+++ b/main.go
@@ -8,23 +8,20 @@
// git --git-dir=/srv/git/foo.git config gsg.title "foo"
// git --git-dir=/srv/git/foo.git config gsg.description "a thing"
// git --git-dir=/srv/git/foo.git config gsg.hide true
+// git --git-dir=/srv/git/foo.git config gsg.gpgkeyring /srv/git/foo-keys.asc
package main
import (
"embed"
"flag"
- "fmt"
"io/fs"
"log"
"log/slog"
"net/http"
"os"
- "path/filepath"
- "sort"
"time"
"gsg/internal/core"
- "gsg/internal/gitx"
_ "gsg/internal/modules" // registers the built-in modules
"gsg/internal/site"
)
@@ -55,16 +52,12 @@ func main() {
func run(root, addr, name, base, tmplDir string, cacheSize int, timeout time.Duration) error {
siteCfg := &core.Site{Name: name, BaseURL: base, Root: root}
- handles, err := discover(root)
- if err != nil {
+ if err := core.Start(siteCfg); err != nil {
return err
}
- if len(handles) == 0 {
- return fmt.Errorf("no repositories found under %s", root)
- }
- siteCfg.Repos = handles
var tfs fs.FS
+ var err error
if tmplDir != "" {
tfs = os.DirFS(tmplDir)
} else if tfs, err = fs.Sub(templateFS, "templates"); err != nil {
@@ -88,7 +81,7 @@ func run(root, addr, name, base, tmplDir string, cacheSize int, timeout time.Dur
mux.Handle("/", srv.Handler())
slog.Info("gsg listening",
- "addr", addr, "repos", len(handles),
+ "addr", addr, "repos", len(siteCfg.RepoList()),
"routes", len(site.Routes()), "modules", len(core.Names()))
hs := &http.Server{
@@ -99,25 +92,3 @@ func run(root, addr, name, base, tmplDir string, cacheSize int, timeout time.Dur
}
return hs.ListenAndServe()
}
-
-// discover finds bare repositories one level below root.
-// Extend to walk recursively if you nest by section.
-func discover(root string) ([]core.Handle, error) {
- entries, err := os.ReadDir(root)
- if err != nil {
- return nil, err
- }
- var handles []core.Handle
- for _, e := range entries {
- if !e.IsDir() {
- continue
- }
- r, err := gitx.Open(filepath.Join(root, e.Name()))
- if err != nil {
- continue // not a repository
- }
- handles = append(handles, core.Handle{Repo: r, Info: core.LoadRepoInfo(r)})
- }
- sort.Slice(handles, func(i, j int) bool { return handles[i].Info.Slug < handles[j].Info.Slug })
- return handles, nil
-}
diff --git a/static/css/base.css b/static/css/base.css
new file mode 100644
index 0000000..c52f976
--- /dev/null
+++ b/static/css/base.css
@@ -0,0 +1,466 @@
+/* gsg — a quiet, text-first interface in the spirit of cgit: hairlines
+ instead of boxes, no shadows, no hover animation. The one indulgence is
+ a black-and-purple signal color -- used for links, hashes, and a thin
+ two-tone stripe at the very top of the page -- so the theme still reads
+ as its own thing rather than "yet another dark git UI".
+
+ Loaded on every page: design tokens, reset, nav, page chrome, and the
+ handful of components (cards, tables, chips, facts-bar, footer,
+ notices) shared by more than one view. View-specific rules live in the
+ other files under static/css/, linked only by the views that need
+ them. */
+
+:root {
+ /* Base — near-black ink */
+ --bg: #0F111A;
+ --bg-elev: #141725;
+ --surface: #1C2032;
+ --surface-2: #24283C;
+ --line: #2A3045;
+ --line-soft: #2E354E;
+
+ /* Foreground */
+ --fg: #FFFFFF;
+ --fg-muted: #9AA0B3;
+ --fg-subtle: #6B7280;
+
+ /* Accent — one signal color, not a rainbow */
+ --accent: #A78BFA;
+ --accent-2: #7C3AED;
+ --accent-grad: linear-gradient(90deg, var(--accent), var(--accent-2));
+
+ /* Status colors */
+ --add: #10B981;
+ --add-bg: rgba(16, 185, 129, 0.15);
+ --del: #EF4444;
+ --del-bg: rgba(239, 68, 68, 0.15);
+
+ /* Counterpart to --accent -- tags and other "second kind of thing"
+ markers use this instead of a shade too close to the purple accent. */
+ --tag: #FAA78B;
+
+ /* Syntax highlighting -- deliberately just four colours (keyword,
+ string, number, name) plus a muted comment, not a full-spectrum
+ scheme. Blob view only; see static/css/blob.css. */
+ --syn-kw: #818CF8;
+ --syn-str: #34D399;
+ --syn-num: #FAA78B;
+ --syn-fn: #60A5FA;
+
+ /* Lane colors — spectrum for telling graph lanes apart, independent
+ of the brand accent above */
+ --lane-0: #818CF8;
+ --lane-1: #10B981;
+ --lane-2: #F59E0B;
+ --lane-3: #EC4899;
+ --lane-4: #3B82F6;
+ --lane-5: #84CC16;
+
+ /* Typography */
+ --mono: ui-monospace, "SFMono-Regular", "JetBrains Mono", "Cascadia Mono",
+ Menlo, Consolas, "Liberation Mono", monospace;
+ --sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+
+ /* Spacing & radius */
+ --r: 8px;
+ --r-sm: 4px;
+ --pad: clamp(.85rem, 2.5vw, 1.5rem);
+}
+
+@media (prefers-color-scheme: light) {
+ :root {
+ --bg: #F3F4F6;
+ --bg-elev: #FFFFFF;
+ --surface: #FFFFFF;
+ --surface-2: #F9FAFB;
+ --line: #E5E7EB;
+ --line-soft: #E5E7EB;
+ --fg: #111827;
+ --fg-muted: #6B7280;
+ --fg-subtle: #9CA3AF;
+ --accent: #7C3AED;
+ --accent-2: #5B21B6;
+ --add: #059669;
+ --del: #DC2626;
+ --tag: #B45309;
+ --syn-kw: #4F46E5;
+ --syn-str: #047857;
+ --syn-num: #B45309;
+ --syn-fn: #1D4ED8;
+ }
+}
+
+/* ---------------------------------------------------------------- reset & base */
+
+*, *::before, *::after { box-sizing: border-box; }
+
+html { -webkit-text-size-adjust: 100%; scroll-behavior: smooth; }
+
+body {
+ margin: 0;
+ background: var(--bg);
+ color: var(--fg);
+ font-family: var(--mono);
+ font-size: 13px;
+ line-height: 1.55;
+ font-variant-ligatures: none;
+ -webkit-font-smoothing: antialiased;
+}
+
+/* The one graphic flourish: a thin two-tone stripe, always at the very
+ top of the viewport. Small enough to be quiet, present enough to be a
+ mark -- the rest of the page is just text and hairlines. */
+body::before {
+ content: "";
+ position: fixed;
+ top: 0; left: 0; right: 0;
+ height: 3px;
+ background: var(--accent-grad);
+ z-index: 200;
+}
+
+a { color: var(--accent); text-decoration: none; }
+a:hover { text-decoration: underline; }
+
+/* Full viewport width, minus a small gutter -- no centered max-width
+ column. Anything wide (tables, diffs, the graph) scrolls inside its own
+ container instead of forcing the page to scroll horizontally. */
+.wrap { width: 100%; margin: 0; padding-inline: var(--pad); }
+
+/* ---------------------------------------------------------------- navigation */
+
+.nav {
+ position: sticky; top: 3px; z-index: 100;
+ background: var(--bg-elev);
+ border-bottom: 1px solid var(--line);
+}
+.nav-inner {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
+ align-items: center;
+ gap: .75rem;
+ height: 3rem;
+}
+
+.nav-start {
+ display: flex; align-items: center; gap: .75rem;
+ grid-column: 1;
+ min-width: 0;
+}
+
+.nav-end {
+ grid-column: 3;
+ justify-self: end;
+}
+
+.brand {
+ display: flex; align-items: center; gap: .5rem;
+ color: var(--fg); font-weight: 700; font-size: .95rem;
+ letter-spacing: -.02em;
+}
+.brand .logo {
+ width: 22px; height: 22px;
+ background: var(--accent);
+ border-radius: var(--r-sm);
+ display: grid; place-items: center;
+ color: var(--bg); font-weight: 700; font-size: .78rem;
+}
+.brand:hover { color: var(--accent); text-decoration: none; }
+
+.repo-name {
+ color: var(--fg); font-weight: 600;
+ margin-left: .5rem;
+}
+.nav-repo-name { color: var(--line); }
+.nav-repo-name:hover { color: var(--accent); }
+
+/* Tabs — plain text, an underline marks the current page */
+.tabs {
+ display: flex; gap: 1rem;
+ grid-column: 2;
+ justify-self: center;
+}
+.tab {
+ padding: .2rem 0;
+ color: var(--fg-muted);
+ font-size: .78rem;
+ border-bottom: 2px solid transparent;
+}
+.tab:hover {
+ color: var(--fg);
+ text-decoration: none;
+}
+.tab.active {
+ color: var(--fg);
+ border-bottom-color: var(--accent);
+}
+
+/* Ref picker — plain, borderless select */
+.refpicker {
+ position: relative;
+}
+.refpicker select {
+ font: inherit; font-size: .78rem;
+ color: var(--fg-muted);
+ background: none;
+ border: 1px solid var(--line);
+ border-radius: var(--r-sm);
+ padding: .25rem 1.75rem .25rem .6rem;
+ cursor: pointer;
+ appearance: none;
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%236B7280' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: right .6rem center;
+ background-size: 10px 10px;
+}
+.refpicker select:hover { border-color: var(--accent); color: var(--fg); }
+.refpicker select:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: -2px;
+}
+
+/* ---------------------------------------------------------------- page layout */
+
+main.wrap { padding-top: 1.25rem; padding-bottom: 2rem; }
+
+/* Hero: a plain text header with a hairline underneath -- no box, no
+ gradient. The page title carries the weight instead of a card. */
+.hero {
+ margin-bottom: 1.25rem;
+ padding-bottom: .9rem;
+ border-bottom: 1px solid var(--line);
+}
+
+.page-title {
+ margin: 0;
+ font-size: 1.3rem;
+ font-weight: 700;
+ letter-spacing: -.02em;
+ line-height: 1.25;
+}
+.page-subtitle {
+ margin: .35rem 0 0;
+ color: var(--fg-muted);
+ font-size: .82rem;
+}
+
+.breadcrumbs {
+ display: flex; flex-wrap: wrap; gap: .4rem;
+ align-items: baseline;
+ margin-top: 1rem;
+ font-size: .9rem;
+ color: var(--fg-muted);
+}
+.breadcrumbs a { color: var(--accent); }
+.breadcrumbs .here { color: var(--fg); }
+
+/* ---------------------------------------------------------------- cards & containers */
+
+/* Reserved for content that genuinely needs a boundary (a diff, a grouped
+ sub-section) -- a thin border, nothing else. Most pages don't use it. */
+.card {
+ border: 1px solid var(--line);
+ border-radius: var(--r);
+ padding: .7rem .9rem;
+ margin-bottom: .75rem;
+}
+
+/* Facts bar — a plain line of label: value pairs, cgit-style, not a grid
+ of stat tiles. */
+.facts-bar {
+ display: flex;
+ flex-wrap: wrap;
+ column-gap: 1.5rem;
+ row-gap: .3rem;
+ margin-bottom: 1rem;
+ font-size: .82rem;
+}
+.fact { display: flex; gap: .4rem; align-items: baseline; }
+.fact-label {
+ color: var(--fg-subtle);
+}
+.fact-label::after { content: ":"; }
+.fact-value {
+ color: var(--fg);
+ font-weight: 600;
+}
+
+/* ---------------------------------------------------------------- tables */
+
+/* Borderless, hairline-separated rows -- like cgit's listings -- rather
+ than a bordered card. Tables can still be wider than the viewport (long
+ paths, many columns on mobile); scrolling lives on the table itself so
+ the page body never gains a horizontal scrollbar. */
+.table-wrap { overflow-x: auto; }
+.table {
+ width: 100%;
+ border-collapse: collapse;
+}
+.table th {
+ color: var(--fg-subtle);
+ font-size: .68rem;
+ text-transform: uppercase;
+ letter-spacing: .07em;
+ padding: .4rem .6rem;
+ text-align: left;
+ font-weight: 600;
+ border-bottom: 1px solid var(--line);
+}
+.table td {
+ padding: .4rem .6rem;
+ border-bottom: 1px solid var(--line-soft);
+ vertical-align: middle;
+}
+.table tr:hover td {
+ background: var(--surface-2);
+}
+
+/* ---------------------------------------------------------------- chips & badges */
+
+.chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: .4rem;
+ list-style: none;
+ margin: 0;
+ padding: 0;
+}
+/* Plain bordered tags, not filled pill badges. */
+.chip {
+ display: inline-flex;
+ align-items: center;
+ gap: .35rem;
+ font-size: .7rem;
+ padding: .2rem .5rem;
+ border: 1px solid var(--line);
+ border-radius: var(--r-sm);
+ color: var(--fg-muted);
+ background: none;
+}
+.chip:hover {
+ border-color: var(--accent);
+ color: var(--fg);
+ text-decoration: none;
+}
+.chip-tag:hover {
+ border-color: var(--tag);
+}
+.chip-branch { color: var(--accent); border-color: currentColor; }
+.chip-tag { color: var(--tag); border-color: currentColor; }
+.chip-ok { color: var(--add); border-color: currentColor; }
+.chip-bad { color: var(--del); border-color: currentColor; }
+
+/* ---------------------------------------------------------------- footer */
+
+footer {
+ margin-top: 1.5rem;
+ padding: 1rem 0;
+ border-top: 1px solid var(--line);
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: .75rem;
+ font-size: .8rem;
+}
+footer .footer-left {
+ display: flex;
+ gap: .75rem;
+ align-items: center;
+}
+footer .footer-right {
+ color: var(--fg-subtle);
+ font-size: .75rem;
+}
+footer a { color: var(--accent); }
+
+/* ---------------------------------------------------------------- notices */
+
+.notice {
+ padding: .5rem .8rem;
+ border-left: 2px solid var(--accent);
+ color: var(--fg-muted);
+ font-size: .8rem;
+ margin: .75rem 0;
+}
+
+/* ---------------------------------------------------------------- error page */
+
+.error-page { padding-top: 3rem; padding-bottom: 3rem; text-align: center; }
+.error-code {
+ font-size: 3rem;
+ font-weight: 700;
+ color: var(--accent);
+ margin: 0;
+ letter-spacing: -.03em;
+}
+.error-page .page-title { margin-top: .25rem; }
+.error-page .page-subtitle { margin-bottom: 1rem; }
+
+/* ---------------------------------------------------------------- responsive */
+
+@media (max-width: 640px) {
+ .nav-inner {
+ display: flex;
+ flex-wrap: wrap;
+ height: auto; padding-block: .5rem;
+ }
+ .nav-start { flex: 1 1 auto; }
+ .nav-end { margin-left: auto; }
+ .tabs {
+ justify-self: auto;
+ width: 100%;
+ order: 3;
+ gap: .75rem;
+ }
+ .facts-bar {
+ flex-direction: column;
+ gap: .25rem;
+ }
+ .hero { padding-bottom: .7rem; }
+ .page-title {
+ font-size: 1.1rem;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ *, *::before, *::after {
+ animation: none !important;
+ transition: none !important;
+ }
+}
+
+/* ---------------------------------------------------------------- utilities */
+
+.hidden { display: none !important; }
+.muted { color: var(--fg-muted); }
+.text-accent { color: var(--accent); }
+.font-mono { font-family: var(--mono); }
+.w-full { width: 100%; }
+.text-right { text-align: right !important; }
+.text-center { text-align: center !important; }
+.text-sm { font-size: .85rem; }
+.text-xs { font-size: .75rem; }
+
+/* Focus states for accessibility */
+:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+}
+
+/* Scrollbar styling */
+::-webkit-scrollbar {
+ height: 8px;
+ width: 8px;
+}
+::-webkit-scrollbar-track {
+ background: var(--bg-elev);
+ border-radius: 4px;
+}
+::-webkit-scrollbar-thumb {
+ background: var(--line);
+ border-radius: 4px;
+}
+::-webkit-scrollbar-thumb:hover {
+ background: var(--fg-subtle);
+}
diff --git a/static/css/blob.css b/static/css/blob.css
new file mode 100644
index 0000000..8d15f4d
--- /dev/null
+++ b/static/css/blob.css
@@ -0,0 +1,144 @@
+/* Blob view — numbered source lines. Owned by views/blob.html */
+
+.source {
+ margin: .75rem 0;
+ background: var(--surface-2);
+ border: 1px solid var(--line);
+ border-radius: var(--r-sm);
+ overflow-x: auto;
+}
+.source table { border-collapse: collapse; font-size: .8rem; }
+.source tr:target { background: rgba(167, 139, 250, 0.18); }
+.source .ln {
+ padding: 0 .75rem;
+ text-align: right;
+ color: var(--fg-subtle);
+ user-select: none;
+ white-space: nowrap;
+ border-right: 1px solid var(--line);
+}
+.source .ln a { color: inherit; }
+.source .lc {
+ padding: 0 .75rem;
+ white-space: pre;
+ width: 100%;
+}
+
+/* Syntax highlighting, set by internal/modules/highlight.go. Tokens without
+ a mapped class (punctuation, operators, plain names) are left uncoloured. */
+.source .tok-k { color: var(--syn-kw); }
+.source .tok-s { color: var(--syn-str); }
+.source .tok-n { color: var(--syn-num); }
+.source .tok-fn { color: var(--syn-fn); }
+.source .tok-c { color: var(--fg-subtle); font-style: italic; }
+
+/* JSON/YAML: a parse-error banner, and per-level indent guides set by
+ internal/modules/structured.go. Width is inlined per span since the
+ indent unit (2 vs 4 spaces) varies by file. */
+.notice-warn { border-left-color: var(--del); }
+.source .ind {
+ display: inline-block;
+ border-left: 1px solid var(--line-soft);
+ height: 1.2em;
+ vertical-align: text-top;
+}
+
+/* Fold controls. The chevron lives in the gutter, but the gutter reserves
+ its width on every row -- otherwise line numbers jog sideways down the
+ file depending on which lines happen to open a block. */
+.source.foldable .ln { position: relative; padding-left: 1.5rem; }
+.source .fold {
+ position: absolute;
+ left: .15rem;
+ top: 0;
+ width: 1.1rem;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--fg-subtle);
+ font: inherit;
+ line-height: inherit;
+ cursor: pointer;
+}
+.source .fold::before { content: "▾"; display: block; }
+.source .fold[aria-expanded="false"]::before { content: "▸"; }
+.source .fold:hover { color: var(--accent); }
+.source tr.is-collapsed .lc::after {
+ content: " " attr(data-fold-note);
+ color: var(--fg-subtle);
+}
+.source tr.is-hidden { display: none; }
+
+/* Search state. Matches are marked at row level: rewriting the cell to wrap
+ hits in <mark> would destroy the highlight spans underneath. */
+.source tr.is-match { background: rgba(167, 139, 250, 0.10); }
+.source tr.is-current { background: rgba(167, 139, 250, 0.28); }
+
+/* YAML anchors and aliases, resolved in internal/modules/structured.go. */
+.source .aref {
+ margin-left: .6rem;
+ padding: 0 .3rem;
+ border: 1px solid var(--line-soft);
+ border-radius: var(--r-sm);
+ color: var(--fg-muted);
+ font-size: .9em;
+ text-decoration: none;
+ white-space: nowrap;
+}
+.source .aref:hover { color: var(--accent); border-color: var(--accent); }
+.source .anchor-uses {
+ margin-left: .6rem;
+ color: var(--fg-subtle);
+ font-size: .85em;
+}
+
+/* Toolbar, built at runtime by static/js/structured.js -- a page without JS
+ never shows it. */
+.sbar {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: .4rem;
+ margin-top: .75rem;
+}
+.sbar-q {
+ flex: 1 1 14rem;
+ min-width: 0;
+ padding: .3rem .5rem;
+ background: var(--surface);
+ border: 1px solid var(--line);
+ border-radius: var(--r-sm);
+ color: var(--fg);
+ font: inherit;
+ font-size: .8rem;
+}
+.sbar-q:focus { outline: none; border-color: var(--accent); }
+.sbar-count {
+ min-width: 5.5rem;
+ color: var(--fg-subtle);
+ font-size: .75rem;
+ text-align: right;
+}
+.sbar-scope { display: flex; }
+.sbar-scope button,
+.sbar-btn {
+ padding: .3rem .55rem;
+ background: var(--surface);
+ border: 1px solid var(--line);
+ color: var(--fg-muted);
+ font: inherit;
+ font-size: .75rem;
+ cursor: pointer;
+}
+.sbar-scope button { border-radius: 0; margin-left: -1px; }
+.sbar-scope button:first-child { border-radius: var(--r-sm) 0 0 var(--r-sm); margin-left: 0; }
+.sbar-scope button:last-child { border-radius: 0 var(--r-sm) var(--r-sm) 0; }
+.sbar-btn { border-radius: var(--r-sm); }
+.sbar-scope button:hover,
+.sbar-btn:not(:disabled):hover { color: var(--fg); border-color: var(--line-soft); }
+.sbar-scope button[aria-pressed="true"],
+.sbar-btn[aria-pressed="true"] {
+ color: var(--accent);
+ border-color: var(--accent);
+}
+.sbar-btn:disabled { opacity: .45; cursor: default; }
diff --git a/static/css/diff.css b/static/css/diff.css
new file mode 100644
index 0000000..9a80ef3
--- /dev/null
+++ b/static/css/diff.css
@@ -0,0 +1,33 @@
+/* Diff & code display — owned by views/commit.html and views/compare.html */
+
+.code-block {
+ margin: .75rem 0;
+ background: var(--surface-2);
+ border: 1px solid var(--line);
+ border-radius: var(--r-sm);
+ overflow-x: auto;
+}
+.code-block pre {
+ margin: 0;
+ padding: .75rem;
+ font-size: .8rem;
+ line-height: 1.55;
+}
+
+.diff { font-size: .8rem; line-height: 1.55; overflow-x: auto; margin: .75rem 0; }
+.diff .pl { white-space: pre; }
+.diff .pl.hunk {
+ color: var(--accent);
+ background: rgba(167, 139, 250, 0.12);
+ border-left: 3px solid var(--accent);
+}
+.diff .pl.add {
+ color: var(--add);
+ background: var(--add-bg);
+ border-left: 3px solid var(--add);
+}
+.diff .pl.del {
+ color: var(--del);
+ background: rgba(239, 68, 68, 0.15);
+ border-left: 3px solid var(--del);
+}
diff --git a/static/css/graph.css b/static/css/graph.css
new file mode 100644
index 0000000..a44aee1
--- /dev/null
+++ b/static/css/graph.css
@@ -0,0 +1,30 @@
+/* Commit graph — owned by views/graph.html */
+
+.graph-table {
+ width: 100%;
+ border-collapse: separate;
+ border-spacing: 0;
+ margin: .75rem 0;
+}
+.graph-table td {
+ padding: 0;
+ height: 30px;
+ white-space: nowrap;
+ vertical-align: middle;
+ border-bottom: 1px solid var(--line-soft);
+}
+.graph-table tr:hover td {
+ background: var(--surface-2);
+}
+.graph-rail { padding: 0; }
+.rail-svg { display: block; }
+.graph-msg {
+ padding: 0 .6rem;
+ font-size: .78rem;
+}
+.graph-who, .graph-when {
+ color: var(--fg-muted);
+ font-size: .7rem;
+ text-align: right;
+ padding: 0 .6rem;
+}
diff --git a/static/css/readme.css b/static/css/readme.css
new file mode 100644
index 0000000..d1c3661
--- /dev/null
+++ b/static/css/readme.css
@@ -0,0 +1,66 @@
+/* README prose — owned by views/repo.html and views/commit.html (commit
+ messages render through the same markdown pipeline) */
+
+.readme {
+ margin-top: 1rem;
+ padding: 1rem 1.25rem;
+ background: var(--surface);
+ border: 1px solid var(--line);
+ border-radius: var(--r);
+ overflow-x: auto;
+}
+.readme h1, .readme h2, .readme h3 {
+ font-family: var(--sans);
+ color: var(--fg);
+ margin-top: 1.25rem;
+ margin-bottom: .5rem;
+}
+.readme h1 { font-size: 1.5rem; border-bottom: 2px solid var(--line); padding-bottom: .5rem; }
+.readme h2 { font-size: 1.25rem; }
+.readme h3 { font-size: 1.05rem; }
+.readme p, .readme ul, .readme ol, .readme blockquote, .readme table {
+ margin: 0 0 1rem;
+}
+.readme ul, .readme ol { padding-left: 1.5rem; }
+.readme li { margin-bottom: .25rem; }
+.readme blockquote {
+ padding: .5rem 1rem;
+ margin: 1rem 0;
+ background: var(--bg-elev);
+ border-left: 3px solid var(--accent);
+ border-radius: 0 var(--r-sm) var(--r-sm) 0;
+ color: var(--fg-muted);
+}
+.readme table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: .85rem;
+}
+.readme th, .readme td {
+ padding: .6rem .8rem;
+ border: 1px solid var(--line);
+}
+.readme th {
+ background: var(--surface-2);
+ color: var(--fg);
+ font-weight: 600;
+}
+.readme code {
+ font-family: var(--mono);
+ font-size: .85rem;
+ background: var(--bg-elev);
+ padding: .1rem .4rem;
+ border-radius: 4px;
+ border: 1px solid var(--line-soft);
+}
+.readme pre {
+ background: var(--bg-elev);
+ padding: 1rem;
+ border-radius: var(--r-sm);
+ overflow-x: auto;
+}
+.readme pre code {
+ padding: 0;
+ background: none;
+ border: none;
+}
diff --git a/static/css/repo-list.css b/static/css/repo-list.css
new file mode 100644
index 0000000..9b0858f
--- /dev/null
+++ b/static/css/repo-list.css
@@ -0,0 +1,41 @@
+/* Repo listing — owned by views/index.html */
+
+.repo-row {
+ display: grid;
+ grid-template-columns: 2fr 3fr auto;
+ gap: 1rem;
+ align-items: center;
+}
+.repo-name a {
+ color: var(--fg);
+ font-weight: 600;
+}
+.repo-name a:hover { color: var(--accent); }
+.repo-owner {
+ display: inline-block;
+ margin-left: .5rem;
+ padding: .05rem .4rem;
+ border-radius: 999px;
+ background: var(--bg-subtle, rgba(127, 127, 127, .15));
+ color: var(--fg-subtle);
+ font-size: .7rem;
+ font-weight: 500;
+ vertical-align: middle;
+}
+.repo-desc {
+ color: var(--fg-muted);
+ font-size: .85rem;
+}
+.repo-meta {
+ color: var(--fg-subtle);
+ font-size: .8rem;
+ text-align: right;
+ white-space: nowrap;
+}
+
+@media (max-width: 640px) {
+ .repo-row {
+ grid-template-columns: 1fr;
+ gap: 0.5rem;
+ }
+}
diff --git a/static/css/repo.css b/static/css/repo.css
new file mode 100644
index 0000000..5ecaf75
--- /dev/null
+++ b/static/css/repo.css
@@ -0,0 +1,46 @@
+/* Repo homepage — owned by views/repo.html */
+
+/* Latest commit — one plain bordered row */
+.latest-commit {
+ display: grid;
+ grid-template-columns: auto 1fr auto;
+ gap: .85rem;
+ align-items: center;
+ padding: .6rem .8rem;
+ border: 1px solid var(--line);
+ border-radius: var(--r-sm);
+ margin-bottom: 1rem;
+}
+.latest-commit:hover { border-color: var(--accent); }
+.commit-hash {
+ color: var(--accent);
+ font-family: var(--mono);
+ font-size: .78rem;
+ font-weight: 600;
+ user-select: all;
+}
+.commit-msg {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-weight: 500;
+ color: var(--fg);
+}
+.commit-meta {
+ color: var(--fg-muted);
+ font-size: .78rem;
+ white-space: nowrap;
+}
+
+@media (max-width: 640px) {
+ .latest-commit {
+ grid-template-columns: 1fr;
+ gap: 0.5rem;
+ text-align: center;
+ }
+ .latest-commit .commit-meta {
+ display: block;
+ margin-top: .25rem;
+ }
+}
diff --git a/static/js/structured.js b/static/js/structured.js
new file mode 100644
index 0000000..6a28d5c
--- /dev/null
+++ b/static/js/structured.js
@@ -0,0 +1,273 @@
+/* Structured-file reading aids for the blob view: fold blocks, search keys
+ and values, filter the file down to what matched.
+
+ Everything here is progressive enhancement. The server renders a plain
+ numbered table with structure hung off data attributes (see
+ internal/modules/structured.go); this file builds the toolbar and the fold
+ controls at runtime, so a page loaded without JS is exactly the table it
+ has always been rather than a dead search box. */
+(function () {
+ var src = document.querySelector('.source.structured');
+ if (!src) return;
+ var rows = Array.prototype.slice.call(src.querySelectorAll('tbody > tr'));
+ if (!rows.length) return;
+
+ // One record per line. Text is read once from textContent -- never
+ // innerHTML, which would match highlight markup as if it were content.
+ // The alias links and anchor-use badges are chrome the server added, not
+ // file content -- searching "uses" must not match every anchor.
+ function cellText(cell) {
+ if (!cell) return '';
+ var s = '';
+ for (var i = 0; i < cell.childNodes.length; i++) {
+ var c = cell.childNodes[i];
+ if (c.nodeType === 1 && (c.className === 'aref' || c.className === 'anchor-uses')) continue;
+ s += c.textContent;
+ }
+ return s;
+ }
+
+ var R = rows.map(function (tr) {
+ var cell = tr.querySelector('.lc');
+ var text = cellText(cell);
+ var key = tr.dataset.key || '';
+ var val = text;
+ if (key) {
+ var at = text.indexOf(key);
+ var colon = text.indexOf(':', at < 0 ? 0 : at + key.length);
+ if (colon >= 0) val = text.slice(colon + 1);
+ }
+ return {
+ tr: tr, cell: cell,
+ n: +tr.dataset.n,
+ depth: +tr.dataset.depth || 0,
+ foldTo: +tr.dataset.foldTo || 0,
+ key: key.toLowerCase(),
+ text: text.toLowerCase(),
+ blank: text.trim() === '',
+ val: val.trim().toLowerCase(),
+ match: false
+ };
+ });
+ var byLine = {};
+ R.forEach(function (r) { byLine[r.n] = r; });
+
+ var collapsed = {}; // opener line number -> true
+ var scope = 'all'; // all | keys | values
+ var filtering = false;
+ var matches = [];
+ var cursor = -1;
+
+ /* ---- fold controls ------------------------------------------------ */
+
+ // Minified or tab-indented files have no indentation to fold on. They get
+ // search, but no gutter reserved for chevrons that will never appear and
+ // no collapse-all that would do nothing.
+ var foldable = R.some(function (r) { return r.foldTo > 0; });
+ if (foldable) src.classList.add('foldable');
+
+ R.forEach(function (r) {
+ if (!r.foldTo || !r.cell) return;
+ var b = document.createElement('button');
+ b.className = 'fold';
+ b.type = 'button';
+ b.setAttribute('aria-expanded', 'true');
+ b.title = 'Collapse lines ' + (r.n + 1) + '–' + r.foldTo;
+ b.addEventListener('click', function () {
+ if (collapsed[r.n]) delete collapsed[r.n]; else collapsed[r.n] = true;
+ render();
+ });
+ r.tr.querySelector('.ln').appendChild(b);
+ // On the cell, not the row: attr() in ::after only reads the attributes
+ // of the element the pseudo-element belongs to.
+ r.cell.dataset.foldNote = '⋯ ' + (r.foldTo - r.n) + ' lines';
+ });
+
+ function foldAll(on) {
+ collapsed = {};
+ if (on) R.forEach(function (r) { if (r.foldTo) collapsed[r.n] = true; });
+ render();
+ }
+
+ // A match hidden inside a collapsed block reads as "no results", so open
+ // every block enclosing it before rendering.
+ function expose(n) {
+ for (var o in collapsed) {
+ var r = byLine[o];
+ if (r && r.n < n && n <= r.foldTo) delete collapsed[o];
+ }
+ }
+
+ /* ---- search ------------------------------------------------------- */
+
+ function hay(r) {
+ return scope === 'keys' ? r.key : scope === 'values' ? r.val : r.text;
+ }
+
+ var lastQ = '';
+ function search(q) {
+ q = lastQ = q.trim().toLowerCase();
+ matches = [];
+ R.forEach(function (r) {
+ r.match = q !== '' && hay(r).indexOf(q) >= 0;
+ if (r.match) matches.push(r);
+ });
+ matches.forEach(function (r) { expose(r.n); });
+ cursor = matches.length ? 0 : -1;
+ render();
+ }
+
+ // In filter mode a matching line keeps the ancestors that give it its path
+ // and the block it owns -- a bare list of hits out of context is worse
+ // than the file.
+ function keepSet() {
+ var keep = {}, stack = [];
+ R.forEach(function (r) {
+ // A blank line carries no indentation, so it is not a level -- letting
+ // one truncate the stack would strip the parents off every match
+ // below a blank line inside a nested block.
+ if (r.blank) return;
+ stack.length = Math.min(stack.length, r.depth);
+ stack[r.depth] = r;
+ if (!r.match) return;
+ stack.forEach(function (a) { if (a) keep[a.n] = true; });
+ for (var i = r.n; i <= r.foldTo; i++) keep[i] = true;
+ });
+ return keep;
+ }
+
+ /* ---- render ------------------------------------------------------- */
+
+ function render() {
+ if (filtering && !matches.length) {
+ filtering = false;
+ filterBtn.setAttribute('aria-pressed', 'false');
+ }
+ var keep = filtering ? keepSet() : null;
+ var hideUntil = 0;
+ R.forEach(function (r) {
+ var hidden = r.n <= hideUntil || (keep !== null && !keep[r.n]);
+ if (collapsed[r.n]) hideUntil = Math.max(hideUntil, r.foldTo);
+ r.tr.classList.toggle('is-hidden', hidden);
+ r.tr.classList.toggle('is-collapsed', !!collapsed[r.n]);
+ r.tr.classList.toggle('is-match', r.match);
+ r.tr.classList.remove('is-current');
+ var b = r.tr.querySelector('.fold');
+ if (b) b.setAttribute('aria-expanded', collapsed[r.n] ? 'false' : 'true');
+ });
+ if (cursor >= 0 && matches[cursor]) matches[cursor].tr.classList.add('is-current');
+ count.textContent = matches.length
+ ? (cursor + 1) + ' / ' + matches.length
+ : (input.value.trim() ? 'no matches' : '');
+ filterBtn.disabled = !matches.length;
+ }
+
+ function step(d) {
+ if (!matches.length) return;
+ cursor = (cursor + d + matches.length) % matches.length;
+ render();
+ matches[cursor].tr.scrollIntoView({ block: 'center' });
+ }
+
+ /* ---- toolbar ------------------------------------------------------ */
+
+ var bar = document.createElement('div');
+ bar.className = 'sbar';
+
+ var input = document.createElement('input');
+ input.type = 'search';
+ input.className = 'sbar-q';
+ input.placeholder = 'Search keys and values… (/)';
+ input.setAttribute('aria-label', 'Search this file');
+
+ var scopes = document.createElement('div');
+ scopes.className = 'sbar-scope';
+ ['all', 'keys', 'values'].forEach(function (s) {
+ var b = document.createElement('button');
+ b.type = 'button';
+ b.textContent = s;
+ b.setAttribute('aria-pressed', String(s === scope));
+ b.addEventListener('click', function () {
+ scope = s;
+ Array.prototype.forEach.call(scopes.children, function (c) {
+ c.setAttribute('aria-pressed', String(c === b));
+ });
+ search(input.value);
+ });
+ scopes.appendChild(b);
+ });
+
+ var count = document.createElement('span');
+ count.className = 'sbar-count';
+
+ function chip(label, title, fn) {
+ var b = document.createElement('button');
+ b.type = 'button';
+ b.className = 'sbar-btn';
+ b.textContent = label;
+ b.title = title;
+ b.addEventListener('click', fn);
+ return b;
+ }
+
+ var prev = chip('↑', 'Previous match (Shift+Enter)', function () { step(-1); });
+ var next = chip('↓', 'Next match (Enter)', function () { step(1); });
+
+ var filterBtn = chip('filter', 'Show only matching lines and their parents', function () {
+ filtering = !filtering;
+ filterBtn.setAttribute('aria-pressed', String(filtering));
+ render();
+ });
+ filterBtn.setAttribute('aria-pressed', 'false');
+ filterBtn.disabled = true;
+
+ var allCollapsed = false;
+ var foldBtn = chip('collapse all', 'Fold every block', function () {
+ allCollapsed = !allCollapsed;
+ foldBtn.textContent = allCollapsed ? 'expand all' : 'collapse all';
+ foldAll(allCollapsed);
+ });
+
+ bar.appendChild(input);
+ bar.appendChild(scopes);
+ bar.appendChild(count);
+ bar.appendChild(prev);
+ bar.appendChild(next);
+ bar.appendChild(filterBtn);
+ if (foldable) bar.appendChild(foldBtn);
+ src.parentNode.insertBefore(bar, src);
+
+ var timer;
+ input.addEventListener('input', function () {
+ clearTimeout(timer);
+ timer = setTimeout(function () { search(input.value); }, 90);
+ });
+ input.addEventListener('keydown', function (e) {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ clearTimeout(timer);
+ // Enter on a query the debounce hasn't run yet searches; Enter on the
+ // same query walks the results.
+ if (input.value.trim().toLowerCase() !== lastQ) search(input.value);
+ else step(e.shiftKey ? -1 : 1);
+ }
+ else if (e.key === 'Escape') { input.value = ''; search(''); input.blur(); }
+ });
+ document.addEventListener('keydown', function (e) {
+ if (e.key !== '/' || e.target === input || /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName)) return;
+ e.preventDefault();
+ input.focus();
+ input.select();
+ });
+
+ // Deep links (#L42, and the alias jump links) must survive folding.
+ window.addEventListener('hashchange', function () {
+ var m = /^#L(\d+)$/.exec(location.hash);
+ if (!m) return;
+ expose(+m[1]);
+ if (filtering) { filtering = false; filterBtn.setAttribute('aria-pressed', 'false'); }
+ render();
+ });
+
+ render();
+})();
diff --git a/static/style.css b/static/style.css
deleted file mode 100644
index 9772671..0000000
--- a/static/style.css
+++ /dev/null
@@ -1,348 +0,0 @@
-/* gsg — monospace-first UI. Every value on these pages is an identifier,
- hash, path or count, so the interface type is the same face as the code;
- the sans face appears only inside rendered README prose. Palette is a cool
- slate ramp with one indigo accent and a six-colour lane ramp that the
- commit graph and its branch chips share. */
-
-:root {
- --bg: #FAFAFC;
- --surface: #FFFFFF;
- --line: #E3E5EE;
- --line-soft: #EDEEF5;
- --fg: #14161D;
- --fg-soft: #4A5063;
- --dim: #858BA0;
- --accent: #5B4BE0;
- --accent-bg: #EEEBFE;
- --add: #1E874B;
- --add-bg: #E9F6EE;
- --del: #C4314B;
- --del-bg: #FCECEF;
-
- --lane-0: #5B4BE0;
- --lane-1: #109C8D;
- --lane-2: #C97A0E;
- --lane-3: #D2447A;
- --lane-4: #2A7CD6;
- --lane-5: #6C9B1E;
-
- --mono: ui-monospace, "SFMono-Regular", "JetBrains Mono", "Cascadia Mono",
- Menlo, Consolas, "Liberation Mono", monospace;
- --sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
-
- --r: 6px;
- --pad: clamp(1rem, 4vw, 2rem);
-}
-
-@media (prefers-color-scheme: dark) {
- :root {
- --bg: #0E1016;
- --surface: #151823;
- --line: #242838;
- --line-soft: #1C2030;
- --fg: #E4E7F0;
- --fg-soft: #A8AEC2;
- --dim: #6E7590;
- --accent: #9C8BFF;
- --accent-bg: #211D3D;
- --add: #4BC585;
- --add-bg: #12251A;
- --del: #FF7A90;
- --del-bg: #2A1419;
-
- --lane-0: #9C8BFF;
- --lane-1: #34C6B4;
- --lane-2: #E5A544;
- --lane-3: #F2678E;
- --lane-4: #58A6F0;
- --lane-5: #9BD45F;
- }
-}
-
-*, *::before, *::after { box-sizing: border-box; }
-
-html { -webkit-text-size-adjust: 100%; }
-
-body {
- margin: 0;
- background: var(--bg);
- color: var(--fg);
- font-family: var(--mono);
- font-size: 13.5px;
- line-height: 1.6;
- font-variant-ligatures: none;
- -webkit-font-smoothing: antialiased;
-}
-
-.wrap { max-width: 74rem; margin: 0 auto; padding-inline: var(--pad); }
-
-a { color: var(--accent); text-decoration: none; }
-a:hover { text-decoration: underline; text-underline-offset: 2px; }
-:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 2px; }
-.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
-
-/* ---------------------------------------------------------------- topbar */
-
-.topbar {
- position: sticky; top: 0; z-index: 10;
- background: color-mix(in srgb, var(--bg) 88%, transparent);
- backdrop-filter: blur(10px);
- border-bottom: 1px solid var(--line);
-}
-.bar {
- display: flex; align-items: center; gap: .65rem;
- height: 3.1rem; flex-wrap: wrap;
-}
-.brand { color: var(--fg); font-weight: 600; letter-spacing: -.01em; }
-.brand:hover { color: var(--accent); text-decoration: none; }
-.slash { color: var(--dim); }
-.repo { color: var(--fg); font-weight: 600; }
-
-.tabs { display: flex; gap: .15rem; margin-left: .6rem; }
-.tabs a {
- color: var(--fg-soft); padding: .2rem .55rem; border-radius: var(--r);
- font-size: .8125rem; letter-spacing: .02em;
-}
-.tabs a:hover { background: var(--line-soft); color: var(--fg); text-decoration: none; }
-
-.refpick { margin-left: auto; }
-.refpick select {
- font: inherit; font-size: .8125rem;
- color: var(--fg-soft); background: var(--surface);
- border: 1px solid var(--line); border-radius: var(--r);
- padding: .2rem 1.4rem .2rem .5rem; cursor: pointer;
- appearance: none;
- background-image: linear-gradient(45deg, transparent 50%, var(--dim) 50%),
- linear-gradient(135deg, var(--dim) 50%, transparent 50%);
- background-position: right .62rem center, right .42rem center;
- background-size: 4px 4px, 4px 4px;
- background-repeat: no-repeat;
-}
-.refpick select:hover { border-color: var(--accent); color: var(--fg); }
-
-/* ------------------------------------------------------------- page head */
-
-main.wrap { padding-block: 2.25rem 5rem; }
-
-.page-head { margin-bottom: 1.6rem; }
-.page-head h1 {
- margin: 0; font-size: 1.375rem; font-weight: 600; letter-spacing: -.02em;
- line-height: 1.3;
-}
-.page-head h1.subject { font-weight: 500; }
-.sub { margin: .3rem 0 0; color: var(--dim); font-size: .8125rem; }
-.sub code { color: var(--fg-soft); }
-.dots { color: var(--dim); padding: 0 .3rem; }
-
-h2 {
- margin: 2.5rem 0 .7rem;
- font-size: .75rem; font-weight: 600;
- text-transform: uppercase; letter-spacing: .1em;
- color: var(--dim);
- display: flex; align-items: baseline; gap: .75rem;
-}
-h2 .more { font-size: .6875rem; letter-spacing: .06em; margin-left: auto; }
-section:first-of-type h2 { margin-top: 1.75rem; }
-
-.crumbs { display: flex; flex-wrap: wrap; gap: .3rem; align-items: baseline;
- font-size: 1.0625rem; font-weight: 500; }
-.crumbs .here { color: var(--fg); }
-
-/* ------------------------------------------------------------------ facts */
-
-.facts {
- display: grid; grid-template-columns: max-content 1fr;
- gap: .1rem 1.5rem; margin: 0;
- padding: .85rem 1rem;
- background: var(--surface);
- border: 1px solid var(--line); border-radius: var(--r);
-}
-.facts dt { color: var(--dim); font-size: .75rem; text-transform: uppercase; letter-spacing: .08em; }
-.facts dd { margin: 0; color: var(--fg-soft); }
-.facts dd code { color: var(--fg); }
-.full-sha { word-break: break-all; }
-.clone { user-select: all; }
-
-/* ----------------------------------------------------------- latest commit */
-
-.latest {
- display: grid;
- grid-template-columns: max-content 1fr max-content;
- align-items: baseline; gap: .85rem;
- margin-top: .9rem; padding: .6rem .85rem;
- background: var(--surface);
- border: 1px solid var(--line); border-radius: var(--r);
- color: var(--fg);
-}
-.latest:hover { border-color: var(--accent); text-decoration: none; }
-.latest-sha { color: var(--accent); font-size: .8125rem; }
-.latest-subject { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-.latest-meta { color: var(--dim); font-size: .75rem; white-space: nowrap; }
-
-.readme { margin-top: 1.75rem; }
-
-/* ---------------------------------------------------------------- tables */
-
-.listing {
- width: 100%; border-collapse: collapse;
- background: var(--surface);
- border: 1px solid var(--line); border-radius: var(--r);
- overflow: hidden;
-}
-.listing td {
- padding: .42rem .75rem;
- border-top: 1px solid var(--line-soft);
- vertical-align: baseline;
-}
-.listing tr:first-child td { border-top: 0; }
-.listing tr:hover td { background: var(--line-soft); }
-.listing .name { width: 100%; }
-.listing .name a { color: var(--fg); }
-.listing .name a:hover { color: var(--accent); }
-.listing .desc, .listing .who { color: var(--dim); white-space: nowrap; }
-.listing .when, .listing .num, .listing .churn, .listing .act {
- color: var(--dim); white-space: nowrap; text-align: right; font-size: .8125rem;
-}
-.listing .sha a { color: var(--accent); }
-.listing .icon { padding-right: 0; width: 1.4rem; }
-.glyph { color: var(--dim); font-size: .75rem; }
-.glyph.dir { color: var(--accent); }
-.muted { color: var(--dim); }
-.empty { color: var(--dim); text-align: center; padding: 1.6rem !important; }
-
-.ghost {
- color: var(--dim); font-size: .75rem;
- border: 1px solid var(--line); border-radius: 4px;
- padding: .05rem .38rem;
-}
-.ghost:hover { color: var(--accent); border-color: var(--accent); text-decoration: none; }
-
-.churn .add { color: var(--add); }
-.churn .del { color: var(--del); margin-left: .5rem; }
-
-.chips { display: flex; flex-wrap: wrap; gap: .4rem; list-style: none; margin: 0; padding: 0; }
-.chip {
- font-size: .75rem; padding: .1rem .45rem;
- border: 1px solid var(--line); border-radius: 4px;
- color: var(--fg-soft); background: var(--surface);
-}
-.chip b { color: var(--dim); font-weight: 400; }
-.chip-branch { color: var(--accent); background: var(--accent-bg); border-color: transparent; margin-right: .35rem; }
-.chip-tag { color: var(--lane-2); border-color: currentColor; margin-right: .35rem; }
-
-/* ----------------------------------------------------------------- graph */
-/* The signature: lane geometry comes from the module, colour from here. */
-
-table.graph { width: 100%; border-collapse: collapse; }
-table.graph td { padding: 0 .75rem; height: 30px; white-space: nowrap; vertical-align: middle; }
-table.graph tr:hover { background: var(--line-soft); }
-table.graph .rail { padding: 0; width: 1px; }
-.rail-svg { display: block; }
-table.graph .msg { width: 100%; white-space: normal; }
-table.graph .msg a { color: var(--fg); }
-table.graph .msg a:hover { color: var(--accent); }
-table.graph .who, table.graph .when { color: var(--dim); font-size: .8125rem; text-align: right; }
-
-/* ------------------------------------------------------------ source/diff */
-
-.source, .patch {
- margin-top: 1rem;
- background: var(--surface);
- border: 1px solid var(--line); border-radius: var(--r);
- overflow-x: auto;
-}
-.source table { border-collapse: collapse; width: 100%; }
-.source td { padding: 0; vertical-align: top; }
-.source .ln {
- width: 1%; padding: 0 .9rem 0 .8rem; text-align: right;
- color: var(--dim); user-select: none;
- position: sticky; left: 0; background: var(--surface);
- border-right: 1px solid var(--line-soft);
-}
-.source .ln a { color: inherit; }
-.source .lc { padding-left: .9rem; white-space: pre; font-size: .8125rem; line-height: 1.55; }
-.source tr:target .lc, .source tr:target .ln { background: var(--accent-bg); }
-
-/* Diffs mark the gutter rather than flooding the row: the signal stays
- readable when a hunk is mostly additions. */
-.patch { font-size: .8125rem; line-height: 1.55; }
-.pl { white-space: pre; padding: 0 .9rem 0 .65rem; border-left: 3px solid transparent; }
-.pl.meta { color: var(--dim); }
-.pl.hunk { color: var(--accent); background: var(--accent-bg); border-left-color: var(--accent); }
-.pl.add { color: var(--add); background: var(--add-bg); border-left-color: var(--add); }
-.pl.del { color: var(--del); background: var(--del-bg); border-left-color: var(--del); }
-
-.message {
- margin: 1rem 0 0; padding: .85rem 1rem;
- background: var(--surface); border: 1px solid var(--line); border-radius: var(--r);
- white-space: pre-wrap; color: var(--fg-soft); font-size: .8125rem;
-}
-.notice {
- padding: .6rem .85rem; border-radius: var(--r);
- background: var(--accent-bg); color: var(--fg-soft); font-size: .8125rem;
-}
-
-/* ----------------------------------------------------------------- prose */
-/* The only place the sans face appears. */
-
-.prose-wrap { margin-top: 2.5rem; }
-.prose {
- font-family: var(--sans); font-size: .9375rem; line-height: 1.7;
- color: var(--fg-soft);
- padding: 1.25rem 1.5rem;
- background: var(--surface);
- border: 1px solid var(--line); border-radius: var(--r);
-}
-.prose h1, .prose h2, .prose h3 {
- font-family: var(--sans); color: var(--fg);
- text-transform: none; letter-spacing: -.01em; display: block;
-}
-.prose h1 { font-size: 1.25rem; margin: 1.5rem 0 .5rem; }
-.prose h2 { font-size: 1.0625rem; margin: 1.5rem 0 .5rem; }
-.prose :first-child { margin-top: 0; }
-.prose h3 { font-size: .9375rem; margin: 1.25rem 0 .4rem; }
-.prose p, .prose ul, .prose ol, .prose blockquote, .prose table { margin: 0 0 1rem; }
-.prose ul, .prose ol { padding-left: 1.35rem; }
-.prose li { margin-bottom: .2rem; }
-.prose img { max-width: 100%; height: auto; border-radius: 4px; }
-.prose hr { border: 0; border-top: 1px solid var(--line); margin: 1.75rem 0; }
-.prose blockquote {
- padding: .1rem 0 .1rem 1rem; border-left: 2px solid var(--line);
- color: var(--dim);
-}
-.prose table { border-collapse: collapse; font-size: .875rem; }
-.prose th, .prose td { padding: .35rem .8rem; border: 1px solid var(--line); text-align: left; }
-.prose th { background: var(--bg); font-weight: 600; color: var(--fg); }
-.prose code, .prose pre { font-family: var(--mono); font-size: .8125rem; }
-.prose :not(pre) > code {
- padding: .1rem .3rem; background: var(--bg);
- border: 1px solid var(--line-soft); border-radius: 3px;
-}
-.prose pre { padding: .8rem; background: var(--bg); border: 1px solid var(--line-soft);
- border-radius: 4px; overflow-x: auto; line-height: 1.5; }
-.prose pre code { padding: 0; background: none; border: 0; }
-
-/* ---------------------------------------------------------------- footer */
-
-footer {
- padding-block: 1.25rem; margin-top: 3rem;
- border-top: 1px solid var(--line);
- color: var(--dim); font-size: .75rem;
- display: flex; gap: .5rem;
-}
-footer .sep { color: var(--line); }
-
-/* ----------------------------------------------------------- small screens */
-
-@media (max-width: 46rem) {
- .listing .who, .listing .desc, table.graph .who { display: none; }
- .latest { grid-template-columns: max-content 1fr; }
- .latest-meta { grid-column: 1 / -1; }
- .bar { height: auto; padding-block: .6rem; }
- .refpick { margin-left: 0; width: 100%; }
- .refpick select { width: 100%; }
-}
-
-@media (prefers-reduced-motion: reduce) {
- *, *::before, *::after { animation: none !important; transition: none !important; }
-}
diff --git a/templates/layouts/base.html b/templates/layouts/base.html
index 3819316..6f5c0f2 100644
--- a/templates/layouts/base.html
+++ b/templates/layouts/base.html
@@ -4,42 +4,55 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ block "title" . }}{{ with .Info.Title }}{{ . }} &middot; {{ end }}{{ .Site.Name }}{{ end }}</title>
-<link rel="stylesheet" href="/static/style.css">
+<link rel="stylesheet" href="/static/css/base.css">
+{{ block "styles" . }}{{ end }}
</head>
<body>
-{{ template "topbar" . }}
+{{ template "nav" . }}
<main class="wrap">{{ block "main" . }}{{ end }}</main>
<footer class="wrap">
- <span>{{ .Site.Name }}</span>
- <span class="sep">/</span>
- <span>served from bare repositories</span>
+ <div class="footer-left">
+ <span class="logo" style="width:24px;height:24px;font-size:0.9rem;">G</span>
+ <span>{{ .Site.Name }}</span>
+ </div>
+ <div class="footer-right">
+ <!--<span>served from bare repositories</span>-->
+ <span style="color:var(--line);margin:0 .5rem;">&bull;</span>
+ <span>{{ .Site.Name }} v1.0</span>
+ </div>
</footer>
+{{ block "scripts" . }}{{ end }}
</body>
</html>{{ end }}
-{{ define "topbar" }}
-<header class="topbar">
- <div class="wrap bar">
- <a class="brand" href="/">{{ .Site.Name }}</a>
+{{ define "nav" }}
+<nav class="nav">
+ <div class="wrap nav-inner">
+ <div class="nav-start">
+ <a class="brand" href="/">
+ <span class="logo">G</span>
+ <span>{{ .Site.Name }}</span>
+ </a>
+ {{ with .Info.Slug }}
+ <a class="repo-name nav-repo-name" href="/{{ . }}/">{{ $.Info.Title }}</a>
+ {{ end }}
+ </div>
{{ with .Info.Slug }}
- <span class="slash">/</span>
- <a class="repo" href="/{{ . }}/">{{ $.Info.Title }}</a>
<nav class="tabs">
- <a href="/{{ . }}/tree/{{ $.Ref }}">files</a>
- <a href="/{{ . }}/log/{{ $.Ref }}">log</a>
- <a href="/{{ . }}/graph/">graph</a>
- <a href="/{{ . }}/refs/">refs</a>
+ {{ range $.Nav }}<a class="tab{{ if .Active }} active{{ end }}" href="{{ .Href }}">{{ .Label }}</a>{{ end }}
</nav>
- {{ with modOr "refs" }}
- <label class="refpick">
- <span class="sr">Ref</span>
- <select onchange="location.href=this.value">
- {{ range .Branches }}<option value="/{{ $.Info.Slug }}/tree/{{ .Name }}"{{ if eq .Name $.Ref }} selected{{ end }}>{{ .Name }}</option>{{ end }}
- {{ range .Tags }}<option value="/{{ $.Info.Slug }}/tree/{{ .Name }}"{{ if eq .Name $.Ref }} selected{{ end }}>{{ .Name }}</option>{{ end }}
- </select>
- </label>
- {{ end }}
+ <div class="nav-end">
+ {{ with modOr "refs" }}
+ <label class="refpicker">
+ <span class="sr">Ref</span>
+ <select onchange="location.href=this.value">
+ {{ range .Branches }}<option value="/{{ $.Info.Slug }}/tree/{{ .Name }}"{{ if eq .Name $.Ref }} selected{{ end }}>{{ .Name }}</option>{{ end }}
+ {{ range .Tags }}<option value="/{{ $.Info.Slug }}/tree/{{ .Name }}"{{ if eq .Name $.Ref }} selected{{ end }}>{{ .Name }}</option>{{ end }}
+ </select>
+ </label>
+ {{ end }}
+ </div>
{{ end }}
</div>
-</header>
+</nav>
{{ end }}
diff --git a/templates/layouts/partials.html b/templates/layouts/partials.html
index 127b49c..457f5a7 100644
--- a/templates/layouts/partials.html
+++ b/templates/layouts/partials.html
@@ -1,61 +1,76 @@
{{/* {{ template "tree-table" (dict "Base" "/slug" "Ref" ref "Entries" entries) }} */}}
{{ define "tree-table" }}
-<table class="listing tree">
+<div class="table-wrap">
+<table class="table">
+ <thead>
+ <tr><th>Name</th><th>Type</th><th class="text-right">Size</th></tr>
+ </thead>
<tbody>
{{ $ := . }}{{ range .Entries }}
<tr>
- <td class="icon">{{ if .IsDir }}<span class="glyph dir">▸</span>{{ else }}<span class="glyph file">·</span>{{ end }}</td>
- <td class="name">
- {{ if .IsDir }}<a class="dir" href="{{ $.Base }}/tree/{{ $.Ref }}/{{ .Path }}">{{ .Name }}</a>
+ <td>
+ {{ if .IsDir }}<a href="{{ $.Base }}/tree/{{ $.Ref }}/{{ .Path }}">{{ .Name }}</a>
{{ else }}<a href="{{ $.Base }}/blob/{{ $.Ref }}/{{ .Path }}">{{ .Name }}</a>{{ end }}
</td>
- <td class="num">{{ if .IsDir }}<span class="muted">—</span>{{ else }}{{ bytes .Size }}{{ end }}</td>
- <td class="act">{{ if not .IsDir }}<a class="ghost" href="{{ $.Base }}/raw/{{ $.Ref }}/{{ .Path }}">raw</a>{{ end }}</td>
+ <td class="text-sm">{{ if .IsDir }}<span class="chip chip-branch">dir</span>{{ else if .IsSubmodule }}<span class="chip chip-tag">submodule</span>{{ else }}<span class="chip chip-tag">file</span>{{ end }}</td>
+ <td class="text-right text-sm text-muted">{{ if .IsDir }}&mdash;{{ else }}{{ bytes .Size }}{{ end }}</td>
</tr>
{{ else }}
- <tr><td class="empty" colspan="4">This directory is empty.</td></tr>
+ <tr><td class="text-center text-muted" colspan="3">This directory is empty.</td></tr>
{{ end }}
</tbody>
</table>
+</div>
{{ end }}
+{{/* {{ template "commit-table" (dict "Base" "/slug" "Commits" commits) }} */}}
{{ define "commit-table" }}
-<table class="listing log">
+<div class="table-wrap">
+<table class="table">
+ <thead>
+ <tr><th>Hash</th><th>Subject</th><th>Author</th><th class="text-right">Date</th></tr>
+ </thead>
<tbody>
{{ $ := . }}{{ range .Commits }}
<tr>
- <td class="sha"><a href="{{ $.Base }}/commit/{{ .SHA }}">{{ .Short }}</a></td>
- <td class="name"><a class="subject" href="{{ $.Base }}/commit/{{ .SHA }}">{{ trunc 78 .Subject }}</a></td>
- <td class="who">{{ .Author }}</td>
- <td class="when"><time datetime="{{ rfc3339 .When }}">{{ date .When }}</time></td>
+ <td class="font-mono text-sm"><a href="{{ $.Base }}/commit/{{ .SHA }}">{{ .Short }}</a></td>
+ <td><a href="{{ $.Base }}/commit/{{ .SHA }}">{{ trunc 78 .Subject }}</a></td>
+ <td class="text-sm">{{ .Author }}</td>
+ <td class="text-right text-sm text-muted"><time datetime="{{ rfc3339 .When }}">{{ date .When }}</time></td>
</tr>
{{ else }}
- <tr><td class="empty" colspan="4">No commits on this ref yet.</td></tr>
+ <tr><td class="text-center text-muted" colspan="4">No commits on this ref yet.</td></tr>
{{ end }}
</tbody>
</table>
+</div>
{{ end }}
{{/* {{ template "diffstat" (dict "Base" "/slug" "Ref" sha "Diff" d) }} */}}
{{ define "diffstat" }}
{{ $ := . }}
{{ with .Diff.Stats }}
-<table class="listing stat">
+<div class="table-wrap">
+<table class="table">
+ <thead>
+ <tr><th>File</th><th>Changes</th><th></th></tr>
+ </thead>
<tbody>
{{ range . }}
<tr>
- <td class="name"><a href="{{ $.Base }}/blob/{{ $.Ref }}/{{ .Path }}">{{ .Path }}</a></td>
- <td class="churn">
- {{ if eq .Status "B" }}<span class="muted">binary</span>
- {{ else }}<span class="add">+{{ .Added }}</span><span class="del">−{{ .Deleted }}</span>{{ end }}
+ <td><a href="{{ $.Base }}/blob/{{ $.Ref }}/{{ .Path }}">{{ .Path }}</a></td>
+ <td class="text-sm">
+ {{ if eq .Status "B" }}<span class="text-muted">binary</span>
+ {{ else }}<span style="color:var(--add);">+{{ .Added }}</span> <span style="color:var(--del);">&minus;{{ .Deleted }}</span>{{ end }}
</td>
- <td class="act"><a class="ghost" href="{{ $.Base }}/raw/{{ $.Ref }}/{{ .Path }}">raw</a></td>
+ <td class="text-right"><a class="chip" href="{{ $.Base }}/raw/{{ $.Ref }}/{{ .Path }}">raw</a></td>
</tr>
{{ end }}
</tbody>
</table>
+</div>
{{ else }}
-<p class="empty">No files changed.</p>
+<p class="text-muted">No files changed.</p>
{{ end }}
-{{ if .Diff.Truncated }}<p class="notice">This diff exceeds the size limit and is shown in part. Fetch the file with <code>raw</code> to see all of it.</p>{{ end }}
+{{ if .Diff.Truncated }}<div class="notice">This diff exceeds the size limit and is shown in part. Fetch the file with <code>raw</code> to see all of it.</div>{{ end }}
{{ end }}
diff --git a/templates/views/blob.html b/templates/views/blob.html
index a7e87ab..f1e82e9 100644
--- a/templates/views/blob.html
+++ b/templates/views/blob.html
@@ -1,21 +1,58 @@
{{ define "blob.html" }}{{ template "base" . }}{{ end }}
+{{ define "styles" }}<link rel="stylesheet" href="/static/css/blob.css">{{ end }}
{{ define "main" }}
-{{ $b := mod "blob" }}{{ $slug := print "/" .Info.Slug }}
-<header class="page-head">
- <nav class="crumbs">
- <a href="{{ $slug }}/tree/{{ .Ref }}">{{ .Info.Title }}</a>
- <span class="slash">/</span><span class="here">{{ $b.Path }}</span>
- </nav>
- <p class="sub">
- <code>{{ .Ref }}</code> &middot; {{ bytes64 $b.Size }}{{ if not $b.Binary }} &middot; {{ len $b.Lines }} lines{{ end }}
- &middot; <a class="ghost" href="{{ $slug }}/raw/{{ .Ref }}/{{ $b.Path }}">raw</a>
- </p>
-</header>
-{{ if $b.Binary }}
- <p class="notice">Binary file. Fetch it with <code>raw</code>.</p>
+{{ $slug := print "/" .Info.Slug }}
+{{ $b := mod "blob" }}
+
+ <header class="hero">
+ <div class="hero-inner">
+ <h1 class="page-title">{{ $b.Path }}</h1>
+ <p class="page-subtitle">
+ <code style="color:var(--accent);">{{ .Ref }}</code>
+ {{ if not $b.Submodule }}
+ <span class="text-muted">&middot; {{ bytes64 $b.Size }}{{ if not $b.Binary }} &middot; {{ len $b.Lines }} lines{{ end }}</span>
+ <a class="chip" style="margin-left:.5rem;" href="{{ $slug }}/raw/{{ .Ref }}/{{ $b.Path }}">raw</a>
+ {{ end }}
+ </p>
+ </div>
+ </header>
+
+{{ if $b.Submodule }}
+ <div class="notice">
+ This is a submodule, pinned at
+ <code>{{ if $b.Submodule.Remote }}{{ $b.Submodule.Remote }}:{{ end }}{{ $b.Submodule.SHA }}</code>.
+ </div>
+{{ else if $b.Binary }}
+ <div class="notice">This is a binary file. Fetch it with <a href="{{ $slug }}/raw/{{ .Ref }}/{{ $b.Path }}">raw</a>.</div>
{{ else }}
-<div class="source"><table><tbody>
-{{ range $b.Lines }}<tr id="L{{ .N }}"><td class="ln"><a href="#L{{ .N }}">{{ .N }}</a></td><td class="lc">{{ .Text }}</td></tr>
-{{ end }}</tbody></table></div>
+ {{ if $b.Oversize }}
+ <div class="notice">
+ This {{ if eq $b.Lang "json" }}JSON{{ else }}YAML{{ end }} file is {{ bytes64 $b.Size }},
+ over the {{ bytes64 $b.StructuredLimit }} limit for parsing. It is shown as plain numbered lines.
+ <a href="{{ $slug }}/raw/{{ .Ref }}/{{ $b.Path }}">Fetch the raw file</a> to work with it locally.
+ </div>
+ {{ end }}
+ {{ if $b.ParseErr }}
+ <div class="notice notice-warn">
+ Invalid {{ if eq $b.Lang "json" }}JSON{{ else }}YAML{{ end }}
+ {{ if $b.ParseErr.Line }}&mdash; <a href="#L{{ $b.ParseErr.Line }}">line {{ $b.ParseErr.Line }}</a>{{ end }}:
+ <code>{{ $b.ParseErr.Msg }}</code>
+ </div>
+ {{ end }}
+ <div class="source{{ if $b.Structured }} structured{{ end }}" data-lang="{{ $b.Lang }}">
+ <table><tbody>
+ {{ range $b.Lines }}
+ <tr id="L{{ .N }}" data-n="{{ .N }}"
+ {{- if .FoldTo }} data-fold-to="{{ .FoldTo }}"{{ end }}
+ {{- if .Depth }} data-depth="{{ .Depth }}"{{ end }}
+ {{- with .Key }} data-key="{{ . }}"{{ end }}>
+ <td class="ln"><a href="#L{{ .N }}">{{ .N }}</a></td>
+ <td class="lc">{{ .Text }}{{ with .Anchor }}{{ if .Uses }}<span class="anchor-uses">{{ .Uses }} use{{ if ne .Uses 1 }}s{{ end }}</span>{{ end }}{{ end }}{{ with .Ref }}<a class="aref" href="#L{{ .Line }}" title="&amp;{{ .Name }} &mdash; line {{ .Line }}{{ with .Preview }}&#10;&#10;{{ . }}{{ end }}">&rarr;&nbsp;{{ .Line }}</a>{{ end }}</td>
+ </tr>
+ {{ end }}
+ </tbody></table>
+ </div>
{{ end }}
{{ end }}
+
+{{ define "scripts" }}{{ if (mod "blob").Structured }}<script src="/static/js/structured.js" defer></script>{{ end }}{{ end }}
diff --git a/templates/views/commit.html b/templates/views/commit.html
index 8a8a5ea..f2562fc 100644
--- a/templates/views/commit.html
+++ b/templates/views/commit.html
@@ -1,20 +1,42 @@
{{ define "commit.html" }}{{ template "base" . }}{{ end }}
+{{ define "styles" }}
+<link rel="stylesheet" href="/static/css/diff.css">
+<link rel="stylesheet" href="/static/css/readme.css">
+{{ end }}
{{ define "main" }}
-{{ $c := mod "commit" }}{{ $d := mod "diff" }}{{ $slug := print "/" .Info.Slug }}
-<header class="page-head">
- <h1 class="subject">{{ $c.Subject }}</h1>
- <p class="sub">{{ $c.Author }} committed <time datetime="{{ rfc3339 $c.When }}">{{ date $c.When }}</time></p>
-</header>
-<dl class="facts">
- <dt>commit</dt><dd><code class="full-sha">{{ $c.SHA }}</code></dd>
- {{ with $c.Parents }}<dt>parent{{ if gt (len .) 1 }}s{{ end }}</dt><dd>
- {{ range . }}<a href="{{ $slug }}/commit/{{ . }}"><code>{{ trunc 12 . }}</code></a>
- <a class="ghost" href="{{ $slug }}/compare/{{ . }}..{{ $c.SHA }}">diff</a>{{ end }}
- </dd>{{ end }}
-</dl>
-{{ with $c.Body }}<pre class="message">{{ . }}</pre>{{ end }}
+{{ $slug := print "/" .Info.Slug }}
+{{ $c := mod "commit" }}
+{{ $d := mod "diff" }}
+
+ <header class="hero">
+ <div class="hero-inner">
+ <h1 class="page-title">{{ $c.Subject }}</h1>
+ <p class="page-subtitle">
+ <code style="color:var(--accent);">{{ trunc 12 $c.SHA }}</code>
+ <span class="text-muted">&middot; {{ $c.Author }} &middot; <time datetime="{{ rfc3339 $c.When }}">{{ date $c.When }}</time></span>
+ </p>
+ </div>
+ </header>
+
+{{ with $c.Body }}
+ <div class="readme"><pre style="white-space:pre-wrap;margin:0;">{{ . }}</pre></div>
+{{ end }}
+
+{{ with $c.Parents }}
+ <div class="chips" style="margin-bottom:1rem;">
+ {{ range . }}
+ <a class="chip" href="{{ $slug }}/commit/{{ . }}">parent {{ trunc 12 . }}</a>
+ <a class="chip" href="{{ $slug }}/compare/{{ . }}..{{ $c.SHA }}">diff</a>
+ {{ end }}
+ </div>
+{{ end }}
+
+<article class="card">
+ <header class="page-head">
+ <h2 class="page-subtitle">Changed files</h2>
+ </header>
+ {{ template "diffstat" (dict "Base" $slug "Ref" $c.SHA "Diff" $d) }}
+</article>
-<h2>Changed files</h2>
-{{ template "diffstat" (dict "Base" $slug "Ref" $c.SHA "Diff" $d) }}
-{{ with $d.Patch }}{{ patch . }}{{ end }}
+{{ with $d.Patch }}<div class="diff">{{ patch . }}</div>{{ end }}
{{ end }}
diff --git a/templates/views/compare.html b/templates/views/compare.html
index 87409db..8bdc698 100644
--- a/templates/views/compare.html
+++ b/templates/views/compare.html
@@ -1,28 +1,51 @@
{{ define "compare.html" }}{{ template "base" . }}{{ end }}
+{{ define "styles" }}<link rel="stylesheet" href="/static/css/diff.css">{{ end }}
{{ define "main" }}
+{{ $slug := print "/" .Info.Slug }}
{{ $c := mod "compare" }}
-<header class="page-head">
- <h1>Compare</h1>
- <p class="sub">
- <code>{{ $c.Base }}</code>
- <span class="dots">{{ if $c.ThreeDot }}&hellip;{{ else }}&#8229;{{ end }}</span>
- <code>{{ $c.Head }}</code>
- </p>
-</header>
-<dl class="facts">
- <dt>base</dt><dd><a href="{{ print "/" .Info.Slug }}/commit/{{ $c.BaseSHA }}"><code>{{ trunc 12 $c.BaseSHA }}</code></a></dd>
- <dt>head</dt><dd><a href="{{ print "/" .Info.Slug }}/commit/{{ $c.HeadSHA }}"><code>{{ trunc 12 $c.HeadSHA }}</code></a></dd>
- {{ with $c.MergeBase }}<dt>merge base</dt><dd><code>{{ trunc 12 . }}</code></dd>{{ end }}
- <dt>commits</dt><dd>{{ len $c.Commits }}</dd>
-</dl>
+ <header class="hero">
+ <div class="hero-inner">
+ <h1 class="page-title">Compare</h1>
+ <p class="page-subtitle">
+ <code style="color:var(--accent);">{{ $c.Base }}</code>
+ {{ if $c.ThreeDot }}&hellip;{{ else }}..{{ end }}
+ <code style="color:var(--accent);">{{ $c.Head }}</code>
+ <span class="text-muted">&middot; {{ len $c.Commits }} commits</span>
+ </p>
+ </div>
+ </header>
-{{ template "diffstat" (dict "Base" (print "/" .Info.Slug) "Ref" $c.HeadSHA "Diff" $c.Diff) }}
+<div class="facts-bar">
+ <div class="fact">
+ <span class="fact-label">base</span>
+ <span class="fact-value"><a href="{{ $slug }}/commit/{{ $c.BaseSHA }}"><code>{{ trunc 12 $c.BaseSHA }}</code></a></span>
+ </div>
+ <div class="fact">
+ <span class="fact-label">head</span>
+ <span class="fact-value"><a href="{{ $slug }}/commit/{{ $c.HeadSHA }}"><code>{{ trunc 12 $c.HeadSHA }}</code></a></span>
+ </div>
+ {{ with $c.MergeBase }}
+ <div class="fact">
+ <span class="fact-label">merge base</span>
+ <span class="fact-value"><code>{{ trunc 12 . }}</code></span>
+ </div>
+ {{ end }}
+</div>
+
+<article class="card">
+ <header class="page-head">
+ <h2 class="page-subtitle">Changed files</h2>
+ </header>
+ {{ template "diffstat" (dict "Base" $slug "Ref" $c.HeadSHA "Diff" $c.Diff) }}
+</article>
{{ with $c.Commits }}
-<h2>Commits</h2>
-{{ template "commit-table" (dict "Base" (print "/" $.Info.Slug) "Commits" .) }}
+ <article class="card">
+ <header class="page-head"><h2 class="page-subtitle">Commits</h2></header>
+ {{ template "commit-table" (dict "Base" $slug "Commits" .) }}
+ </article>
{{ end }}
-{{ with $c.Diff.Patch }}<h2>Patch</h2>{{ patch . }}{{ end }}
+{{ with $c.Diff.Patch }}<div class="diff">{{ patch . }}</div>{{ end }}
{{ end }}
diff --git a/templates/views/graph.html b/templates/views/graph.html
index dfbf27c..57deca2 100644
--- a/templates/views/graph.html
+++ b/templates/views/graph.html
@@ -1,26 +1,53 @@
{{ define "graph.html" }}{{ template "base" . }}{{ end }}
+{{ define "styles" }}<link rel="stylesheet" href="/static/css/graph.css">{{ end }}
{{ define "main" }}
+{{ $slug := print "/" .Info.Slug }}
+{{/* "150" here must match core.GraphPageSize -- buildCtx uses that
+ constant to snap incoming ?ofs= values onto real page boundaries. */}}
{{ $g := mod "graph" "150" }}
-<header class="page-head">
- <h1>Branch graph</h1>
- <p class="sub">{{ len $g.Rows }} commits across all refs &middot; {{ $g.Lanes }} lanes</p>
-</header>
-<table class="graph">
- <tbody>
- {{ range $g.Rows }}
- <tr>
- <td class="rail">{{ .Rail }}</td>
- <td class="msg">
- {{ range .Refs }}<span class="chip chip-{{ if eq .Kind "tag" }}tag{{ else }}branch{{ end }}">{{ .Name }}</span>{{ end }}
- <a href="{{ print "/" $.Info.Slug }}/commit/{{ .Commit.SHA }}">{{ trunc 76 .Commit.Subject }}</a>
- </td>
- <td class="who">{{ .Commit.Author }}</td>
- <td class="when"><time datetime="{{ rfc3339 .Commit.When }}">{{ date .Commit.When }}</time></td>
- </tr>
+ <header class="hero">
+ <div class="hero-inner">
+ <h1 class="page-title">Commit Graph</h1>
+ <p class="page-subtitle">
+ <span class="text-muted">{{ len $g.Rows }} commits across all refs &middot; {{ $g.Lanes }} lanes</span>
+ </p>
+ </div>
+ </header>
+
+{{ with $g.Rows }}
+<div style="overflow-x:auto;">
+ <table class="graph-table">
+ <tbody>
+ {{ range . }}
+ <tr>
+ <td class="graph-rail">{{ .Rail }}</td>
+ <td class="graph-msg">
+ {{ range .Refs }}<span class="chip chip-{{ if eq .Kind "tag" }}tag{{ else }}branch{{ end }}">{{ .Name }}</span>{{ end }}
+ <a href="{{ $slug }}/commit/{{ .Commit.SHA }}">{{ trunc 88 .Commit.Subject }}</a>
+ </td>
+ <td class="graph-who text-xs text-muted">{{ .Commit.Author }}</td>
+ <td class="graph-when text-xs text-muted"><time datetime="{{ rfc3339 .Commit.When }}">{{ date .Commit.When }}</time></td>
+ </tr>
+ {{ end }}
+ </tbody>
+ </table>
+</div>
+
+{{ else }}
+ {{ if $g.HasPrev }}
+ <div class="notice" style="text-align:center;"><span class="text-muted">No commits at this offset.</span></div>
{{ else }}
- <tr><td class="empty">No commits yet.</td></tr>
+ <div class="card" style="padding:2rem;text-align:center;">
+ <p class="muted">No commits yet. This is a fresh repository.</p>
+ </div>
{{ end }}
- </tbody>
-</table>
+{{ end }}
+
+{{ if or $g.HasPrev $g.HasNext }}
+ <nav class="pager" style="display:flex;justify-content:space-between;margin-top:1rem;">
+ <span>{{ if $g.HasPrev }}<a href="?ofs={{ $g.PrevOfs }}">&larr; Newer</a>{{ end }}</span>
+ <span>{{ if $g.HasNext }}<a href="?ofs={{ $g.NextOfs }}">Older &rarr;</a>{{ end }}</span>
+ </nav>
+{{ end }}
{{ end }}
diff --git a/templates/views/index.html b/templates/views/index.html
index d3378bf..fafbfa4 100644
--- a/templates/views/index.html
+++ b/templates/views/index.html
@@ -1,26 +1,40 @@
{{ define "index.html" }}{{ template "base" . }}{{ end }}
+{{ define "styles" }}<link rel="stylesheet" href="/static/css/repo-list.css">{{ end }}
{{ define "main" }}
{{ $secs := mod "sections" }}
+
<header class="page-head">
- <h1>{{ .Site.Name }}</h1>
- <p class="sub">{{ len (mod "repos") }} repositories{{ if gt (len $secs) 1 }} in {{ len $secs }} sections{{ end }}</p>
+ <h1 class="page-title">{{ .Site.Name }}</h1>
+ <p class="page-subtitle">{{ len (mod "repos") }} repositories{{ if gt (len $secs) 1 }} in {{ len $secs }} sections{{ end }}</p>
</header>
{{ range $secs }}
{{/* An unnamed section means gsg.section is unset everywhere: render flat. */}}
- {{ with .Name }}<h2 id="{{ slug . }}">{{ . }}</h2>{{ end }}
- <table class="listing repos">
+ {{ with .Name }}<h2 id="{{ slug . }}" class="page-subtitle">{{ . }}</h2>{{ end }}
+ <div class="table-wrap">
+<table class="table">
+ <thead>
+ <tr>
+ <th>Repository</th>
+ <th>Description</th>
+ <th class="text-right">Last Updated</th>
+ </tr>
+ </thead>
<tbody>
{{ range .Repos }}
<tr>
- <td class="name"><a href="/{{ .Slug }}/">{{ .Title }}</a></td>
- <td class="desc">{{ with .Description }}{{ . }}{{ else }}<span class="muted">No description set</span>{{ end }}</td>
- <td class="when">{{ with .LastCommit }}<time datetime="{{ rfc3339 . }}">{{ date . }}</time>{{ else }}<span class="muted">empty</span>{{ end }}</td>
+ <td class="repo-name">
+ <a href="/{{ .Slug }}/">{{ .Title }}</a>
+ {{ with .Owner }}<span class="repo-owner">{{ . }}</span>{{ end }}
+ </td>
+ <td class="repo-desc">{{ with .Description }}{{ . }}{{ else }}<span class="muted">No description set</span>{{ end }}</td>
+ <td class="repo-meta">{{ with .LastCommit }}<time datetime="{{ rfc3339 . }}">{{ date . }}</time>{{ else }}<span class="muted">empty</span>{{ end }}</td>
</tr>
{{ else }}
- <tr><td class="empty">No repositories yet. Create a bare repo under the configured root.</td></tr>
+ <tr><td colspan="3" class="text-center text-muted" style="padding: 2rem;">No repositories yet. Create a bare repo under the configured root.</td></tr>
{{ end }}
</tbody>
</table>
+</div>
{{ end }}
-{{ end }}
+{{ end }}
\ No newline at end of file
diff --git a/templates/views/log.html b/templates/views/log.html
index 92be263..d277823 100644
--- a/templates/views/log.html
+++ b/templates/views/log.html
@@ -1,8 +1,69 @@
{{ define "log.html" }}{{ template "base" . }}{{ end }}
{{ define "main" }}
-<header class="page-head">
- <h1>Log</h1>
- <p class="sub"><code>{{ .Ref }}</code></p>
-</header>
-{{ template "commit-table" (dict "Base" (print "/" .Info.Slug) "Commits" (mod "log" "200")) }}
+{{ $slug := print "/" .Info.Slug }}
+{{ $verify := .Info.GPGKeyring }}
+{{ $m := mod "meta" }}
+{{/* "20" here must match core.LogPageSize -- buildCtx uses that constant
+ to snap incoming ?ofs= values onto real page boundaries. */}}
+{{ $page := mod "log" "20" }}
+
+ <header class="hero">
+ <div class="hero-inner">
+ <h1 class="page-title">Commit History</h1>
+ <p class="page-subtitle">
+ Showing <span style="color:var(--accent);font-weight:600;">{{ len $page.Commits }}</span> commits
+ </p>
+ </div>
+ </header>
+
+{{/* `with` on the slice, not index 0 -- an empty repo has no commits. */}}
+{{ with $page.Commits }}
+ <div class="table-wrap">
+<table class="table">
+ <thead>
+ <tr>
+ <th>Hash</th>
+ <th>Subject</th>
+ <th>Author</th>
+ {{ if $verify }}<th>Signature</th>{{ end }}
+ <th class="text-right">Date</th>
+ </tr>
+ </thead>
+ <tbody>
+ {{ range . }}
+ <tr>
+ <td class="font-mono text-sm"><a href="{{ $slug }}/commit/{{ .SHA }}">{{ .Short }}</a></td>
+ <td><a href="{{ $slug }}/commit/{{ .SHA }}">{{ .Subject }}</a></td>
+ <td class="text-sm">{{ .Author }}</td>
+ {{ if $verify }}
+ <td class="text-sm">
+ {{ if .Verified }}<span class="chip chip-ok" title="{{ .Signer }} &middot; {{ .KeyID }}">verified</span>
+ {{ else if .Unchecked }}<span class="chip" title="key {{ .KeyID }} not in keyring">unknown key</span>
+ {{ else if .Signed }}<span class="chip chip-bad" title="{{ .KeyID }}">{{ .SigLabel }}</span>
+ {{ else }}<span class="text-muted">&mdash;</span>{{ end }}
+ </td>
+ {{ end }}
+ <td class="text-right text-sm text-muted"><time datetime="{{ rfc3339 .When }}">{{ date .When }}</time></td>
+ </tr>
+ {{ end }}
+ </tbody>
+ </table>
+</div>
+
+{{ else }}
+ {{ if $page.HasPrev }}
+ <div class="notice" style="text-align:center;"><span class="text-muted">No commits at this offset.</span></div>
+ {{ else }}
+ <div class="card" style="padding:2rem;text-align:center;">
+ <p class="muted">No commits yet. This is a fresh repository.</p>
+ </div>
+ {{ end }}
{{ end }}
+
+{{ if or $page.HasPrev $page.HasNext }}
+ <nav class="pager" style="display:flex;justify-content:space-between;margin-top:1rem;">
+ <span>{{ if $page.HasPrev }}<a href="?ofs={{ $page.PrevOfs }}">&larr; Newer</a>{{ end }}</span>
+ <span>{{ if $page.HasNext }}<a href="?ofs={{ $page.NextOfs }}">Older &rarr;</a>{{ end }}</span>
+ </nav>
+{{ end }}
+{{ end }}
\ No newline at end of file
diff --git a/templates/views/refs.html b/templates/views/refs.html
index 6c8671d..128948c 100644
--- a/templates/views/refs.html
+++ b/templates/views/refs.html
@@ -1,34 +1,60 @@
{{ define "refs.html" }}{{ template "base" . }}{{ end }}
{{ define "main" }}
-{{ $r := mod "refs" }}{{ $slug := print "/" .Info.Slug }}
-<header class="page-head">
- <h1>Refs</h1>
- <p class="sub">{{ len $r.Branches }} branches &middot; {{ len $r.Tags }} tags</p>
-</header>
+{{ $slug := print "/" .Info.Slug }}
+{{ $r := mod "refs" }}
+
+ <header class="hero">
+ <div class="hero-inner">
+ <h1 class="page-title">References</h1>
+ <p class="page-subtitle">
+ <span class="text-muted">{{ len $r.Branches }} branches &middot; {{ len $r.Tags }} tags</span>
+ </p>
+ </div>
+ </header>
+
<section>
- <h2>Branches</h2>
- <table class="listing refs"><tbody>
- {{ range $r.Branches }}
- <tr>
- <td class="name"><a href="{{ $slug }}/tree/{{ .Name }}">{{ .Name }}</a></td>
- <td class="desc">{{ trunc 64 .Title }}</td>
- <td class="when"><time datetime="{{ rfc3339 .When }}">{{ date .When }}</time></td>
- <td class="act"><a class="ghost" href="{{ $slug }}/compare/{{ $.Ref }}...{{ .Name }}">compare</a></td>
- </tr>
- {{ else }}<tr><td class="empty" colspan="4">No branches.</td></tr>{{ end }}
- </tbody></table>
+ <h2 class="page-subtitle">Branches</h2>
+ <div class="table-wrap">
+<table class="table">
+ <thead>
+ <tr><th>Name</th><th>Subject</th><th class="text-right">Updated</th><th></th></tr>
+ </thead>
+ <tbody>
+ {{ range $r.Branches }}
+ <tr>
+ <td><a class="chip chip-branch" href="{{ $slug }}/tree/{{ .Name }}">{{ .Name }}</a></td>
+ <td class="text-sm text-muted">{{ trunc 64 .Title }}</td>
+ <td class="text-right text-sm text-muted"><time datetime="{{ rfc3339 .When }}">{{ date .When }}</time></td>
+ <td class="text-right"><a class="chip" href="{{ $slug }}/compare/{{ $.Ref }}...{{ .Name }}">compare</a></td>
+ </tr>
+ {{ else }}
+ <tr><td class="text-center text-muted" colspan="4">No branches.</td></tr>
+ {{ end }}
+ </tbody>
+ </table>
+</div>
</section>
-<section>
- <h2>Tags</h2>
- <table class="listing refs"><tbody>
- {{ range $r.Tags }}
- <tr>
- <td class="name"><a href="{{ $slug }}/tree/{{ .Name }}">{{ .Name }}</a></td>
- <td class="desc">{{ trunc 64 .Title }}</td>
- <td class="when"><time datetime="{{ rfc3339 .When }}">{{ date .When }}</time></td>
- <td class="act"><a class="ghost" href="{{ $slug }}/compare/{{ $.Ref }}...{{ .Name }}">compare</a></td>
- </tr>
- {{ else }}<tr><td class="empty" colspan="4">No tags.</td></tr>{{ end }}
- </tbody></table>
+
+<section style="margin-top:1.5rem;">
+ <h2 class="page-subtitle">Tags</h2>
+ <div class="table-wrap">
+<table class="table">
+ <thead>
+ <tr><th>Name</th><th>Subject</th><th class="text-right">Created</th><th></th></tr>
+ </thead>
+ <tbody>
+ {{ range $r.Tags }}
+ <tr>
+ <td><a class="chip chip-tag" href="{{ $slug }}/tree/{{ .Name }}">{{ .Name }}</a></td>
+ <td class="text-sm text-muted">{{ trunc 64 .Title }}</td>
+ <td class="text-right text-sm text-muted"><time datetime="{{ rfc3339 .When }}">{{ date .When }}</time></td>
+ <td class="text-right"><a class="chip" href="{{ $slug }}/compare/{{ $.Ref }}...{{ .Name }}">compare</a></td>
+ </tr>
+ {{ else }}
+ <tr><td class="text-center text-muted" colspan="4">No tags.</td></tr>
+ {{ end }}
+ </tbody>
+ </table>
+</div>
</section>
{{ end }}
diff --git a/templates/views/repo.html b/templates/views/repo.html
deleted file mode 100644
index cc4a4a1..0000000
--- a/templates/views/repo.html
+++ /dev/null
@@ -1,41 +0,0 @@
-{{ define "repo.html" }}{{ template "base" . }}{{ end }}
-{{ define "main" }}
-{{ $slug := print "/" .Info.Slug }}
-{{ $m := mod "meta" }}
-
-<header class="page-head">
- <h1>{{ $m.Title }}</h1>
- {{ with $m.Description }}<p class="sub">{{ . }}</p>{{ end }}
-</header>
-
-<dl class="facts">
- <dt>branch</dt><dd><a href="{{ $slug }}/tree/{{ $m.DefaultRef }}"><code>{{ $m.DefaultRef }}</code></a></dd>
- <dt>updated</dt><dd>{{ with $m.LastCommit }}<time datetime="{{ rfc3339 . }}">{{ date . }}</time>{{ else }}<span class="muted">never</span>{{ end }}</dd>
- {{ with $m.Section }}<dt>section</dt><dd><a href="/#{{ slug . }}">{{ . }}</a></dd>{{ end }}
- {{ with $m.Clone }}<dt>clone</dt><dd><code class="clone">{{ . }}</code></dd>{{ end }}
- {{ with $m.Owner }}<dt>owner</dt><dd>{{ . }}</dd>{{ end }}
-</dl>
-
-{{/* `with` on the slice, not index 0 -- an empty repo has no commits and
- indexing would abort the render. */}}
-{{ with mod "log" "1" }}{{ with index . 0 }}
-<a class="latest" href="{{ $slug }}/commit/{{ .SHA }}">
- <span class="latest-sha">{{ .Short }}</span>
- <span class="latest-subject">{{ trunc 88 .Subject }}</span>
- <span class="latest-meta">{{ .Author }} &middot; <time datetime="{{ rfc3339 .When }}">{{ date .When }}</time></span>
-</a>
-{{ end }}{{ end }}
-
-{{ with modOr "readme" }}
- <div class="prose readme">{{ .HTML }}</div>
-{{ else }}
- <p class="notice">No README on <code>{{ $.Ref }}</code>. Browse the <a href="{{ $slug }}/tree/{{ $.Ref }}">files</a> instead.</p>
-{{ end }}
-
-{{/* Everything else moved to its own page. Modules are lazy, so the ones
- this view no longer calls cost nothing -- to put authors back, this is
- the entire change:
- {{ with mod "authors" }}
- <ul class="chips">{{ range . }}<li class="chip">{{ .Name }} <b>{{ .Commits }}</b></li>{{ end }}</ul>
- {{ end }} */}}
-{{ end }}
diff --git a/templates/views/tree.html b/templates/views/tree.html
index 840ed10..c50b83f 100644
--- a/templates/views/tree.html
+++ b/templates/views/tree.html
@@ -1,15 +1,90 @@
{{ define "tree.html" }}{{ template "base" . }}{{ end }}
+{{ define "styles" }}
+<link rel="stylesheet" href="/static/css/repo.css">
+<link rel="stylesheet" href="/static/css/readme.css">
+{{ end }}
{{ define "main" }}
-{{ $t := mod "tree" }}{{ $slug := print "/" .Info.Slug }}
-<header class="page-head">
- <nav class="crumbs">
- <a href="{{ $slug }}/tree/{{ .Ref }}">{{ .Info.Title }}</a>
- {{ range $t.Crumbs }}<span class="slash">/</span><a href="{{ $slug }}/tree/{{ $.Ref }}/{{ .Path }}">{{ .Name }}</a>{{ end }}
- </nav>
- <p class="sub"><code>{{ .Ref }}</code> &middot; {{ len $t.Entries }} entries</p>
+{{ $slug := print "/" .Info.Slug }}
+{{ $root := eq .Path "" }}
+
+{{ if $root }}
+{{ $m := mod "meta" }}
+<header class="hero">
+ <div class="hero-inner">
+ <h1 class="page-title">{{ $m.Title }}</h1>
+ {{ with $m.Description }}<p class="page-subtitle">{{ . }}</p>{{ end }}
+ </div>
</header>
-{{ template "tree-table" (dict "Base" $slug "Ref" .Ref "Entries" $t.Entries) }}
+
+<div class="facts-bar">
+ <div class="fact">
+ <span class="fact-label">default branch</span>
+ <span class="fact-value"><a href="{{ $slug }}/tree/{{ $m.DefaultRef }}">{{ $m.DefaultRef }}</a></span>
+ </div>
+ <div class="fact">
+ <span class="fact-label">updated</span>
+ <span class="fact-value">{{ with $m.LastCommit }}<time datetime="{{ rfc3339 . }}">{{ date . }}</time>{{ else }}<span class="muted">never</span>{{ end }}</span>
+ </div>
+ {{ with $m.Section }}<div class="fact">
+ <span class="fact-label">section</span>
+ <span class="fact-value"><a href="/#{{ slug . }}">{{ . }}</a></span>
+ </div>{{ end }}
+ {{ with $m.Clone }}<div class="fact">
+ <span class="fact-label">clone</span>
+ <span class="fact-value"><code>{{ . }}</code></span>
+ </div>{{ end }}
+ {{ with $m.Owner }}<div class="fact">
+ <span class="fact-label">owner</span>
+ <span class="fact-value">{{ . }}</span>
+ </div>{{ end }}
+</div>
+
+{{/* `with` on .Commits, not index 0 -- an empty repo has no commits and
+ indexing would abort the render. */}}
+{{ with (mod "log" "1").Commits }}{{ with index . 0 }}
+<a class="latest-commit" href="{{ $slug }}/commit/{{ .SHA }}">
+ <span class="commit-hash">{{ .Short }}</span>
+ <span class="commit-msg">{{ trunc 88 .Subject }}</span>
+ <span class="commit-meta">{{ .Author }} &middot; <time datetime="{{ rfc3339 .When }}">{{ date .When }}</time></span>
+</a>
+{{ end }}{{ end }}
+{{ end }}
+
+{{/* An empty repo (unborn HEAD) has no commit to list a tree at -- mod
+ "tree" would 404 on it, where this page used to render fine. Only call
+ it once there's a real commit to resolve against. */}}
+{{ if .Commit }}
+{{ $tree := mod "tree" }}
+{{ if $root }}
+ <p class="text-muted">
+ <code style="color:var(--accent);">{{ .Ref }}</code>
+ &middot; {{ len $tree.Entries }} entries
+ </p>
+{{ else }}
+ <header class="hero">
+ <div class="hero-inner">
+ <h1 class="page-title">Files</h1>
+ <p class="page-subtitle">
+ <code style="color:var(--accent);">{{ .Ref }}</code>
+ <span class="text-muted">&middot; {{ len $tree.Entries }} entries{{ with $tree.Path }} in <code>{{ . }}</code>{{ end }}</span>
+ </p>
+ </div>
+ </header>
+{{ end }}
+
+{{ template "tree-table" (dict "Base" $slug "Ref" .Ref "Entries" $tree.Entries) }}
+{{ end }}
+
+{{ if $root }}
{{ with modOr "readme" }}
-<section class="prose-wrap"><div class="prose">{{ .HTML }}</div></section>
+ <div class="readme">{{ .HTML }}</div>
+{{ end }}
{{ end }}
+
+{{/* Everything else moved to its own page. Modules are lazy, so the ones
+ this view no longer calls cost nothing -- to put authors back, this is
+ the entire change:
+ {{ with mod "authors" }}
+ <ul class="chips">{{ range . }}<li class="chip">{{ .Name }} <b>{{ .Commits }}</b></li>{{ end }}</ul>
+ {{ end }} */}}
{{ end }}