// Package gitx is the only place that knows how git works. // Everything above it sees plain Go values. Swap this for go-git or // git2go later without touching a single module or template. package gitx import ( "bytes" "context" "fmt" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" "sync" "time" ) // Separators. exec() argv cannot contain NUL bytes, so the FORMAT strings // use git's own hex escapes and git emits the real bytes; we split on those. // (for-each-ref spells them %00, git-log spells them %x00.) const ( sepF = "\x00" // field separator, as it appears in git's OUTPUT sepR = "\x1e" // record separator, as it appears in git's OUTPUT escF = "%00" // field separator, as written in a for-each-ref format escLogF = "%x00" // field separator, as written in a git-log format escLogR = "%x1e" // record separator, as written in a git-log format ) type Repo struct { Dir string // path to the git dir (bare repo, or /.git) Slug string // url-safe short name, derived from the directory empty bool // no commits yet (unborn HEAD) 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 // output cap. Serving means every git invocation is attacker-influenced // work: without a deadline, one `git log` on a huge repo pins a core, and // without a cap one diff of a 200MB blob eats the heap. func (r *Repo) WithContext(ctx context.Context, maxBytes int64) *Repo { c := *r c.ctx = ctx c.maxBytes = maxBytes c.memo = &repoMemo{} return &c } // Empty reports whether the repository has no commits. This is a normal // state for a freshly created bare repo, not an error -- Log and Tree // return nothing rather than failing, so a view still renders. func (r *Repo) Empty() bool { return r.empty } func Open(dir string) (*Repo, error) { gitDir := dir if st, err := os.Stat(filepath.Join(dir, ".git")); err == nil && st.IsDir() { gitDir = filepath.Join(dir, ".git") } r := &Repo{ Dir: gitDir, Slug: strings.TrimSuffix(filepath.Base(strings.TrimSuffix(dir, "/")), ".git"), } if _, err := r.run("rev-parse", "--git-dir"); err != nil { return nil, fmt.Errorf("open %s: %w", dir, err) } _, err := r.run("rev-parse", "--verify", "--quiet", "HEAD") r.empty = err != nil return r, nil } // ErrTruncated is returned alongside partial output that hit maxBytes. var ErrTruncated = fmt.Errorf("output truncated") func (r *Repo) run(args ...string) ([]byte, error) { ctx := r.ctx if ctx == nil { ctx = context.Background() } full := append([]string{"--git-dir", r.Dir}, args...) 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 err := cmd.Run() if r.maxBytes > 0 && int64(out.Len()) > r.maxBytes { return out.Bytes()[:r.maxBytes], ErrTruncated } if err != nil { if ctx.Err() != nil { return nil, fmt.Errorf("git %s: %w", args[0], ctx.Err()) } return nil, fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String())) } return out.Bytes(), nil } // ------------------------------------------------------------------ config // Config reads a key from the repository's own config file, the way cgit // does with enable-git-config. A missing key is empty, not an error. func (r *Repo) Config(key string) string { out, err := r.run("config", "--get", key) if err != nil { return "" // exit 1 == key absent } return strings.TrimSpace(string(out)) } // ConfigFirst returns the first key that has a value, for fallback chains // such as gsg.description -> gitweb.description. func (r *Repo) ConfigFirst(keys ...string) string { for _, k := range keys { if v := r.Config(k); v != "" { return v } } 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. func (r *Repo) DescriptionFile() string { b, err := os.ReadFile(filepath.Join(r.Dir, "description")) if err != nil { return "" } s := strings.TrimSpace(string(b)) if s == placeholderDesc { return "" } return s } // -------------------------------------------------------------------- refs type Ref struct { Name string Kind string // "branch" | "tag" Target string // commit sha When time.Time Title string } 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") if err != nil { return nil, err } var refs []Ref for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") { if line == "" { continue } p := strings.Split(line, sepF) if len(p) < 5 { continue } kind := "branch" if strings.HasPrefix(p[4], "refs/tags/") { kind = "tag" } t, _ := time.Parse(time.RFC3339, p[2]) refs = append(refs, Ref{Name: p[0], Kind: kind, Target: p[1], When: t, Title: p[3]}) } return refs, nil } var shaRE = regexp.MustCompile(`^[0-9a-fA-F]{7,40}$`) // Resolve turns user-supplied ref text into a commit SHA. // // SECURITY: the input is never handed to `git rev-parse`. rev-parse accepts // an expression language (`:/regex` searches history, `@{...}` reads the // reflog) and git subcommands treat a leading `-` as an option. So input is // either a hex SHA that must already exist, or an exact match against the // repo's own ref list. Everything else is rejected. func (r *Repo) Resolve(ref string) (string, error) { if ref == "" || ref == "HEAD" { ref = r.HeadRef() } if strings.ContainsAny(ref, "\x00\n") || strings.HasPrefix(ref, "-") { return "", fmt.Errorf("invalid ref %q", ref) } if shaRE.MatchString(ref) { out, err := r.run("rev-parse", "--verify", "--quiet", ref+"^{commit}") if err != nil { return "", fmt.Errorf("unknown commit %q", ref) } return strings.TrimSpace(string(out)), nil } refs, err := r.Refs() if err != nil { return "", err } for _, x := range refs { if x.Name == ref { out, err := r.run("rev-parse", "--verify", x.Target+"^{commit}") if err != nil { return "", err } return strings.TrimSpace(string(out)), nil } } return "", fmt.Errorf("unknown ref %q", ref) } // SplitRefPath separates "feature/x/src/main.go" into ref "feature/x" and // path "src/main.go" by matching the LONGEST prefix that is a real ref. // Branch names contain slashes, so a naive split at the first "/" is wrong; // cgit dodges this with ?h= query params, GitHub resolves against the ref // list. This does the latter. func (r *Repo) SplitRefPath(rest string) (ref, path string) { rest = strings.Trim(rest, "/") if rest == "" { return r.HeadRef(), "" } names := map[string]bool{} if refs, err := r.Refs(); err == nil { for _, x := range refs { names[x.Name] = true } } segs := strings.Split(rest, "/") for i := len(segs); i > 0; i-- { cand := strings.Join(segs[:i], "/") if names[cand] || shaRE.MatchString(cand) { return cand, strings.Join(segs[i:], "/") } } // No ref matched: treat the whole thing as a path at HEAD. return r.HeadRef(), rest } // 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" } return strings.TrimSpace(string(out)) } // ----------------------------------------------------------------- commits type Commit struct { SHA string Short string Author string Email string When time.Time 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. // 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 } 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) out, err := r.run(args...) return r.parseLog(out, err, verify) } 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, 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], } 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] } if p[4] != "" { c.Parents = strings.Fields(p[4]) } commits = append(commits, c) } return commits, nil } // MergeBase returns the common ancestor of two resolved commits. func (r *Repo) MergeBase(a, b string) (string, error) { out, err := r.run("merge-base", a, b) if err != nil { return "", err } return strings.TrimSpace(string(out)), nil } // LogAll walks every ref in topological order. This is the input to the // branch graph: --topo-order guarantees a child always precedes its // parents, which the lane assignment depends on. func (r *Repo) LogAll(n int) ([]Commit, error) { if r.empty { return nil, nil } format := strings.Join([]string{"%H", "%an", "%ae", "%aI", "%P", "%s", "%b"}, escLogF) // 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 type Entry struct { Mode string Type string // "blob" | "tree" | "commit" (submodule) SHA string Size int64 Name string // basename Path string // full path from repo root } 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) { if r.empty { return nil, nil } spec := rev + ":" if path != "" && path != "." { spec = rev + ":" + path } out, err := r.run("ls-tree", "-z", "--long", spec) if err != nil { return nil, err } var entries []Entry for _, rec := range strings.Split(string(out), "\x00") { if rec == "" { continue } head, name, ok := strings.Cut(rec, "\t") if !ok { continue } f := strings.Fields(head) if len(f) < 3 { continue } e := Entry{Mode: f[0], Type: f[1], SHA: f[2], Name: name} if len(f) > 3 { e.Size, _ = strconv.ParseInt(f[3], 10, 64) } e.Path = strings.TrimPrefix(path+"/"+name, "/") entries = append(entries, e) } 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 { Added, Deleted int Path, OldPath string Status string } type Diff struct { Stats []FileStat Patch string Truncated bool } // DiffRange returns the patch between two resolved commits. // Callers MUST pass SHAs from Resolve, never raw user input. func (r *Repo) DiffRange(base, head string, threeDot bool) (Diff, error) { sep := ".." if threeDot { sep = "..." } return r.diff("diff", "-p", "--no-color", "--no-ext-diff", "-M", "--numstat", base+sep+head) } // DiffCommit returns the patch for a single commit. --root makes the first // commit diff against the empty tree instead of erroring. func (r *Repo) DiffCommit(sha string) (Diff, error) { return r.diff("diff-tree", "-p", "--root", "--no-color", "--no-ext-diff", "-M", "--numstat", "--format=", sha) } func (r *Repo) diff(args ...string) (Diff, error) { var d Diff raw, err := r.run(args...) if err == ErrTruncated { d.Truncated = true } else if err != nil { return d, err } body := string(raw) // numstat block comes first, then the patch; they are separated by the // first line starting with "diff --git". if i := strings.Index(body, "diff --git"); i >= 0 { d.Stats = parseNumstat(body[:i]) d.Patch = body[i:] } else { d.Stats = parseNumstat(body) } return d, nil } func parseNumstat(s string) []FileStat { var out []FileStat for _, line := range strings.Split(s, "\n") { f := strings.Split(strings.TrimSpace(line), "\t") if len(f) < 3 { continue } fs := FileStat{Path: f[2], Status: "M"} if f[0] == "-" { fs.Status = "B" // binary } else { fs.Added, _ = strconv.Atoi(f[0]) fs.Deleted, _ = strconv.Atoi(f[1]) } out = append(out, fs) } return out } // Blob returns file contents at rev. func (r *Repo) Blob(rev, path string) ([]byte, error) { return r.run("cat-file", "blob", rev+":"+path) }