Migration This is my new public git source viewer. Source available. Please contact with concerns/bugs. Contact me

internal/gitx/git.go

d640ddbb8ad06f0e54d9c6e33c347acf247818e6 · 24.4 KB · 813 lines raw

1 // Package gitx is the only place that knows how git works.
2 // Everything above it sees plain Go values. Swap this for go-git or
3 // git2go later without touching a single module or template.
4 package gitx
5
6 import (
7 "bytes"
8 "context"
9 "errors"
10 "fmt"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "regexp"
15 "runtime"
16 "strconv"
17 "strings"
18 "sync"
19 "time"
20 )
21
22 // Separators. exec() argv cannot contain NUL bytes, so the FORMAT strings
23 // use git's own hex escapes and git emits the real bytes; we split on those.
24 // (for-each-ref spells them %00, git-log spells them %x00.)
25 const (
26 sepF = "\x00" // field separator, as it appears in git's OUTPUT
27 sepR = "\x1e" // record separator, as it appears in git's OUTPUT
28
29 escF = "%00" // field separator, as written in a for-each-ref format
30 escLogF = "%x00" // field separator, as written in a git-log format
31 escLogR = "%x1e" // record separator, as written in a git-log format
32 )
33
34 // Repo is immutable once returned to a caller. Every request takes a
35 // shallow copy of the long-lived Repo (WithContext) while the watcher may
36 // concurrently be reconfiguring it, so nothing may write to a published
37 // Repo's fields: a change is a new Repo (WithKeyring, WithoutKeyring) that
38 // the caller publishes in its place.
39 type Repo struct {
40 Dir string // path to the git dir (bare repo, or <worktree>/.git)
41 Slug string // url-safe short name, derived from the directory
42
43 ctx context.Context
44 maxBytes int64
45
46 // kr, when non-nil, is the isolated GNUPGHOME imported from the
47 // operator's gsg.gpgkeyring. Its presence is also the signal to
48 // Log/LogAll to ask git for signature status at all. Shared, read-only,
49 // by every copy of the Repo that was built from it.
50 kr *keyring
51
52 // memo caches HeadRef/Refs for the lifetime of one request. It is a
53 // pointer, allocated fresh by WithContext, rather than a plain field:
54 // Repo is copied by value (see WithContext), so a mutex or map field
55 // here directly would either trip go vet's copylocks check or -- worse
56 // -- share its map header with the copy, leaking one request's cache
57 // into the long-lived Repo every Handle keeps between requests. nil on
58 // that long-lived Repo and in any Repo not built via WithContext (e.g.
59 // tests): HeadRef/Refs just skip the cache in that case.
60 memo *repoMemo
61 }
62
63 type repoMemo struct {
64 mu sync.Mutex
65 empty *bool
66 headRef *string
67 haveRefs bool
68 refs []Ref
69 refsErr error
70 }
71
72 // WithContext returns a view of the repo bound to a request context and an
73 // output cap. Serving means every git invocation is attacker-influenced
74 // work: without a deadline, one `git log` on a huge repo pins a core, and
75 // without a cap one diff of a 200MB blob eats the heap.
76 func (r *Repo) WithContext(ctx context.Context, maxBytes int64) *Repo {
77 c := *r
78 c.ctx = ctx
79 c.maxBytes = maxBytes
80 c.memo = &repoMemo{}
81 return &c
82 }
83
84 // Empty reports whether the repository has no commits (unborn HEAD). This
85 // is a normal state for a freshly created bare repo, not an error -- Log
86 // and Tree return nothing rather than failing, so a view still renders.
87 //
88 // Evaluated on demand and memoized per request (like HeadRef), never
89 // latched at Open: core/watch.go opens a repo as soon as its directory
90 // appears under root -- gitolite and `git init --bare` both create it
91 // before the first push -- and keeps that *Repo for the life of the
92 // process. A value captured at Open left a new repo showing no commits
93 // after it was pushed to, until a restart re-opened it. Pushes don't touch
94 // config or description, so the watcher never sees them; this has to be a
95 // read of current state, not something the watcher refreshes.
96 func (r *Repo) Empty() bool {
97 if r.memo != nil {
98 r.memo.mu.Lock()
99 cached := r.memo.empty
100 r.memo.mu.Unlock()
101 if cached != nil {
102 return *cached
103 }
104 }
105
106 empty := r.headUnborn()
107
108 if r.memo != nil {
109 r.memo.mu.Lock()
110 r.memo.empty = &empty
111 r.memo.mu.Unlock()
112 }
113 return empty
114 }
115
116 // headUnborn is true only when git positively reports that HEAD does not
117 // resolve: `rev-parse --verify --quiet` exits 1. Any other failure -- the
118 // request deadline, git missing -- is not evidence the repo is empty, and
119 // treating it as such would turn a timeout into a silently blank page
120 // instead of an error.
121 func (r *Repo) headUnborn() bool {
122 _, err := r.run("rev-parse", "--verify", "--quiet", "HEAD")
123 var exitErr *exec.ExitError
124 return errors.As(err, &exitErr) && exitErr.ExitCode() == 1
125 }
126
127 func Open(dir string) (*Repo, error) {
128 gitDir := dir
129 if st, err := os.Stat(filepath.Join(dir, ".git")); err == nil && st.IsDir() {
130 gitDir = filepath.Join(dir, ".git")
131 }
132 r := &Repo{
133 Dir: gitDir,
134 Slug: strings.TrimSuffix(filepath.Base(strings.TrimSuffix(dir, "/")), ".git"),
135 }
136 if _, err := r.run("rev-parse", "--git-dir"); err != nil {
137 return nil, fmt.Errorf("open %s: %w", dir, err)
138 }
139 return r, nil
140 }
141
142 // ErrTruncated is returned alongside partial output that hit maxBytes.
143 var ErrTruncated = fmt.Errorf("output truncated")
144
145 func (r *Repo) run(args ...string) ([]byte, error) {
146 ctx := r.ctx
147 if ctx == nil {
148 ctx = context.Background()
149 }
150 // safe.directory=* bypasses git's dubious-ownership check (CVE-2022-24765).
151 // gsg runs against operator-chosen repo roots, commonly bind-mounted into
152 // a container where the mount ends up owned by a different uid than the
153 // process -- a trust boundary git can't see, since HOME=/nonexistent
154 // below means there's no config file left to set this in from outside.
155 full := append([]string{"--git-dir", r.Dir, "-c", "safe.directory=*"}, args...)
156 cmd := exec.CommandContext(ctx, "git", full...)
157 // Refuse to inherit anything that alters git's behaviour.
158 cmd.Env = []string{"GIT_CONFIG_NOSYSTEM=1", "HOME=/nonexistent", "GIT_TERMINAL_PROMPT=0", "PATH=" + os.Getenv("PATH")}
159 kr := r.kr
160 if kr != nil {
161 // git shells out to gpg to check %G?; gpg picks this up from its
162 // own environment, which it inherits from git's.
163 cmd.Env = append(cmd.Env, "GNUPGHOME="+kr.home)
164 }
165
166 var out, errb bytes.Buffer
167 cmd.Stdout, cmd.Stderr = &out, &errb
168 err := cmd.Run()
169 // The homedir is removed by kr's finalizer once kr is unreachable. Past
170 // building Env, nothing above reads kr, so without this the GC could
171 // decide it is dead and delete the directory while gpg is reading it.
172 runtime.KeepAlive(kr)
173
174 if r.maxBytes > 0 && int64(out.Len()) > r.maxBytes {
175 return out.Bytes()[:r.maxBytes], ErrTruncated
176 }
177 if err != nil {
178 if ctx.Err() != nil {
179 return nil, fmt.Errorf("git %s: %w", args[0], ctx.Err())
180 }
181 return nil, fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
182 }
183 return out.Bytes(), nil
184 }
185
186 // ------------------------------------------------------------------ config
187
188 // Config reads a key from the repository's own config file, the way cgit
189 // does with enable-git-config. A missing key is empty, not an error.
190 func (r *Repo) Config(key string) string {
191 out, err := r.run("config", "--get", key)
192 if err != nil {
193 return "" // exit 1 == key absent
194 }
195 return strings.TrimSpace(string(out))
196 }
197
198 // ConfigFirst returns the first key that has a value, for fallback chains
199 // such as gsg.description -> gitweb.description.
200 func (r *Repo) ConfigFirst(keys ...string) string {
201 for _, k := range keys {
202 if v := r.Config(k); v != "" {
203 return v
204 }
205 }
206 return ""
207 }
208
209 // -------------------------------------------------------------------- gpg
210
211 // keyring is an imported, isolated GNUPGHOME. Immutable after
212 // importKeyring returns.
213 //
214 // Its directory is deleted by a finalizer when the keyring becomes
215 // unreachable, not when the watcher swaps in a replacement: a request that
216 // looked its Handle up just before the swap is still holding a copy of the
217 // old Repo and may be mid-`git log` with gpg reading this directory.
218 // Deleting it eagerly (as an earlier version did) made that request's
219 // signatures come back as "signature not checked", and that result was
220 // then cached in the module LRU under the old keyring's key. Reachability
221 // is exactly "no Repo that could still run gpg against it", so it is the
222 // right lifetime.
223 type keyring struct {
224 home string // GNUPGHOME
225 path string // the gsg.gpgkeyring value it was imported from
226 }
227
228 // importKeyring imports the armored keys at path into a fresh homedir.
229 // Without this, %G? signature checks would fall back to the host's default
230 // keyring -- whatever happens to be trusted there, not what this repo's
231 // operator vetted.
232 //
233 // The homedir is created directly under /tmp rather than os.TempDir():
234 // gpg-agent's control socket is a Unix domain socket, capped at ~104
235 // bytes, and a long TMPDIR (macOS's is typically 50+ characters) pushes
236 // the full path over that limit and breaks key generation/import in a way
237 // that just prints "no agent running" with no useful exit code to catch.
238 func importKeyring(path string) (*keyring, error) {
239 dir, err := os.MkdirTemp("/tmp", "gsg-gpg-")
240 if err != nil {
241 return nil, fmt.Errorf("gpg keyring: %w", err)
242 }
243 if err := os.Chmod(dir, 0700); err != nil {
244 os.RemoveAll(dir)
245 return nil, fmt.Errorf("gpg keyring: %w", err)
246 }
247 cmd := exec.Command("gpg", "--batch", "--quiet", "--import", path)
248 cmd.Env = []string{"GNUPGHOME=" + dir, "HOME=/nonexistent", "PATH=" + os.Getenv("PATH")}
249 var errb bytes.Buffer
250 cmd.Stderr = &errb
251 if err := cmd.Run(); err != nil {
252 os.RemoveAll(dir)
253 return nil, fmt.Errorf("gpg keyring: import %s: %w: %s", path, err, strings.TrimSpace(errb.String()))
254 }
255 kr := &keyring{home: dir, path: path}
256 runtime.SetFinalizer(kr, func(k *keyring) { os.RemoveAll(k.home) })
257 return kr, nil
258 }
259
260 // WithKeyring returns a copy of r whose git invocations (via GNUPGHOME, see
261 // run) see only the keys imported from path. r itself is not modified. On
262 // error the caller still has r, so a bad reconfigure leaves the
263 // previously-working keyring in effect rather than breaking it.
264 func (r *Repo) WithKeyring(path string) (*Repo, error) {
265 kr, err := importKeyring(path)
266 if err != nil {
267 return nil, err
268 }
269 c := *r
270 c.kr = kr
271 return &c, nil
272 }
273
274 // WithoutKeyring returns a copy of r that does not verify signatures. r
275 // itself is not modified; its homedir, if any, goes away once nothing
276 // references it.
277 func (r *Repo) WithoutKeyring() *Repo {
278 c := *r
279 c.kr = nil
280 return &c
281 }
282
283 // KeyringPath is the gsg.gpgkeyring value imported into this Repo, or "" if
284 // it has no keyring. Callers use this to detect when the configured keyring
285 // has changed, on any call -- the first or the hundredth -- without needing
286 // to track that separately.
287 func (r *Repo) KeyringPath() string {
288 if r.kr == nil {
289 return ""
290 }
291 return r.kr.path
292 }
293
294 const placeholderDesc = "Unnamed repository; edit this file 'description' to name the repository."
295
296 // DescriptionFile reads the legacy `description` file, ignoring git's placeholder.
297 func (r *Repo) DescriptionFile() string {
298 b, err := os.ReadFile(filepath.Join(r.Dir, "description"))
299 if err != nil {
300 return ""
301 }
302 s := strings.TrimSpace(string(b))
303 if s == placeholderDesc {
304 return ""
305 }
306 return s
307 }
308
309 // -------------------------------------------------------------------- refs
310
311 type Ref struct {
312 Name string
313 Kind string // "branch" | "tag"
314 Target string // commit sha
315 When time.Time
316 Title string
317 }
318
319 func (r *Repo) Refs() ([]Ref, error) {
320 if r.memo != nil {
321 r.memo.mu.Lock()
322 if r.memo.haveRefs {
323 refs, err := r.memo.refs, r.memo.refsErr
324 r.memo.mu.Unlock()
325 return refs, err
326 }
327 r.memo.mu.Unlock()
328 }
329
330 refs, err := r.refs()
331
332 if r.memo != nil {
333 r.memo.mu.Lock()
334 r.memo.refs, r.memo.refsErr, r.memo.haveRefs = refs, err, true
335 r.memo.mu.Unlock()
336 }
337 return refs, err
338 }
339
340 func (r *Repo) refs() ([]Ref, error) {
341 const f = "%(refname:short)" + escF + "%(objectname)" + escF +
342 "%(creatordate:iso-strict)" + escF + "%(subject)" + escF + "%(refname)"
343 out, err := r.run("for-each-ref", "--format="+f, "refs/heads", "refs/tags")
344 if err != nil {
345 return nil, err
346 }
347 var refs []Ref
348 for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") {
349 if line == "" {
350 continue
351 }
352 p := strings.Split(line, sepF)
353 if len(p) < 5 {
354 continue
355 }
356 kind := "branch"
357 if strings.HasPrefix(p[4], "refs/tags/") {
358 kind = "tag"
359 }
360 t, _ := time.Parse(time.RFC3339, p[2])
361 refs = append(refs, Ref{Name: p[0], Kind: kind, Target: p[1], When: t, Title: p[3]})
362 }
363 return refs, nil
364 }
365
366 var shaRE = regexp.MustCompile(`^[0-9a-fA-F]{7,40}$`)
367
368 // Resolve turns user-supplied ref text into a commit SHA.
369 //
370 // SECURITY: the input is never handed to `git rev-parse`. rev-parse accepts
371 // an expression language (`:/regex` searches history, `@{...}` reads the
372 // reflog) and git subcommands treat a leading `-` as an option. So input is
373 // either a hex SHA that must already exist, or an exact match against the
374 // repo's own ref list. Everything else is rejected.
375 func (r *Repo) Resolve(ref string) (string, error) {
376 if ref == "" || ref == "HEAD" {
377 ref = r.HeadRef()
378 }
379 if strings.ContainsAny(ref, "\x00\n") || strings.HasPrefix(ref, "-") {
380 return "", fmt.Errorf("invalid ref %q", ref)
381 }
382 if shaRE.MatchString(ref) {
383 out, err := r.run("rev-parse", "--verify", "--quiet", ref+"^{commit}")
384 if err != nil {
385 return "", fmt.Errorf("unknown commit %q", ref)
386 }
387 return strings.TrimSpace(string(out)), nil
388 }
389 refs, err := r.Refs()
390 if err != nil {
391 return "", err
392 }
393 for _, x := range refs {
394 if x.Name == ref {
395 out, err := r.run("rev-parse", "--verify", x.Target+"^{commit}")
396 if err != nil {
397 return "", err
398 }
399 return strings.TrimSpace(string(out)), nil
400 }
401 }
402 return "", fmt.Errorf("unknown ref %q", ref)
403 }
404
405 // SplitRefPath separates "feature/x/src/main.go" into ref "feature/x" and
406 // path "src/main.go" by matching the LONGEST prefix that is a real ref.
407 // Branch names contain slashes, so a naive split at the first "/" is wrong;
408 // cgit dodges this with ?h= query params, GitHub resolves against the ref
409 // list. This does the latter.
410 func (r *Repo) SplitRefPath(rest string) (ref, path string) {
411 rest = strings.Trim(rest, "/")
412 if rest == "" {
413 return r.HeadRef(), ""
414 }
415 names := map[string]bool{}
416 if refs, err := r.Refs(); err == nil {
417 for _, x := range refs {
418 names[x.Name] = true
419 }
420 }
421 segs := strings.Split(rest, "/")
422 for i := len(segs); i > 0; i-- {
423 cand := strings.Join(segs[:i], "/")
424 if names[cand] || shaRE.MatchString(cand) {
425 return cand, strings.Join(segs[i:], "/")
426 }
427 }
428 // No ref matched: treat the whole thing as a path at HEAD.
429 return r.HeadRef(), rest
430 }
431
432 // HeadRef resolves the repo's default branch, rather than guessing main/master.
433 func (r *Repo) HeadRef() string {
434 if r.memo != nil {
435 r.memo.mu.Lock()
436 cached := r.memo.headRef
437 r.memo.mu.Unlock()
438 if cached != nil {
439 return *cached
440 }
441 }
442
443 head := r.headRef()
444
445 if r.memo != nil {
446 r.memo.mu.Lock()
447 r.memo.headRef = &head
448 r.memo.mu.Unlock()
449 }
450 return head
451 }
452
453 func (r *Repo) headRef() string {
454 out, err := r.run("symbolic-ref", "--short", "HEAD")
455 if err != nil {
456 return "HEAD"
457 }
458 return strings.TrimSpace(string(out))
459 }
460
461 // ----------------------------------------------------------------- commits
462
463 type Commit struct {
464 SHA string
465 Short string
466 Author string
467 Email string
468 When time.Time
469 Subject string
470 Body string
471 Parents []string
472
473 // Signature is only populated when the caller asked for it (Log, when
474 // the repo has a keyring -- see Repo.WithKeyring). SigStatus is git's
475 // raw %G? code: G/U good, B bad, X/Y expired, R revoked, E unchecked,
476 // N unsigned or "" when signature checks weren't requested at all.
477 SigStatus string
478 Signer string
479 KeyID string
480 }
481
482 // Verified reports a good signature from a key in the repo's configured
483 // keyring. A bare gpg homedir has no ownertrust database, so a genuinely
484 // valid signature from a freshly-imported key comes back "U" (valid, trust
485 // unknown), not "G" -- trust here comes from the key being in the
486 // operator's keyring file, not from GPG's own web-of-trust bookkeeping.
487 func (c Commit) Verified() bool { return c.SigStatus == "G" || c.SigStatus == "U" }
488
489 // Signed reports whether the commit carries a signature at all, good or
490 // not -- lets a template tell "bad signature" apart from "no signature".
491 func (c Commit) Signed() bool { return c.SigStatus != "" && c.SigStatus != "N" }
492
493 // Unchecked reports a signature git could not evaluate against the
494 // keyring at all -- almost always because the signing key just isn't in
495 // it. That is not evidence of tampering the way B/X/Y/R are, so it should
496 // read as "we don't know", not as a failure.
497 func (c Commit) Unchecked() bool { return c.SigStatus == "E" }
498
499 // SigLabel is a short human-readable rendering of SigStatus, for the log
500 // view's badge.
501 func (c Commit) SigLabel() string {
502 switch c.SigStatus {
503 case "G", "U":
504 return "verified"
505 case "B":
506 return "bad signature"
507 case "X":
508 return "expired signature"
509 case "Y":
510 return "expired key"
511 case "R":
512 return "revoked key"
513 case "E":
514 return "signature not checked"
515 default:
516 return "unsigned"
517 }
518 }
519
520 // Log walks history from rev in ONE git process. n <= 0 means unbounded.
521 // Never call this once per commit; fork overhead dominates at scale.
522 // When verify is true, each commit also carries its signature status --
523 // only pass true for small, bounded logs: git forks gpg once per signed
524 // commit to check it.
525 func (r *Repo) Log(rev string, n, skip int, verify bool) ([]Commit, error) {
526 if r.Empty() {
527 return nil, nil
528 }
529 verify = verify && r.kr != nil // no keyring configured: nothing to check against
530 fields := []string{"%H", "%an", "%ae", "%aI", "%P", "%s"}
531 if verify {
532 fields = append(fields, "%G?", "%GS", "%GK")
533 }
534 fields = append(fields, "%b")
535 format := strings.Join(fields, escLogF)
536 args := []string{"log", "--format=" + escLogR + format}
537 if n > 0 {
538 args = append(args, "-n", strconv.Itoa(n))
539 }
540 if skip > 0 {
541 args = append(args, "--skip", strconv.Itoa(skip))
542 }
543 args = append(args, rev)
544 out, err := r.run(args...)
545 return r.parseLog(out, err, verify)
546 }
547
548 func (r *Repo) parseLog(out []byte, err error, verify bool) ([]Commit, error) {
549 if err != nil {
550 return nil, err
551 }
552 nfields := 7
553 if verify {
554 nfields = 10
555 }
556 var commits []Commit
557 for _, rec := range strings.Split(string(out), sepR) {
558 rec = strings.TrimRight(rec, "\n")
559 if rec == "" {
560 continue
561 }
562 p := strings.SplitN(rec, sepF, nfields)
563 if len(p) < nfields {
564 continue
565 }
566 t, _ := time.Parse(time.RFC3339, p[3])
567 c := Commit{
568 SHA: p[0], Author: p[1], Email: p[2], When: t,
569 Subject: p[5],
570 }
571 if verify {
572 c.SigStatus, c.Signer, c.KeyID, c.Body = p[6], p[7], p[8], strings.TrimSpace(p[9])
573 } else {
574 c.Body = strings.TrimSpace(p[6])
575 }
576 if len(c.SHA) >= 8 {
577 c.Short = c.SHA[:8]
578 }
579 if p[4] != "" {
580 c.Parents = strings.Fields(p[4])
581 }
582 commits = append(commits, c)
583 }
584 return commits, nil
585 }
586
587 // MergeBase returns the common ancestor of two resolved commits.
588 func (r *Repo) MergeBase(a, b string) (string, error) {
589 out, err := r.run("merge-base", a, b)
590 if err != nil {
591 return "", err
592 }
593 return strings.TrimSpace(string(out)), nil
594 }
595
596 // IsAncestor reports whether a is an ancestor of b (true, in particular,
597 // when a == b).
598 func (r *Repo) IsAncestor(a, b string) (bool, error) {
599 _, err := r.run("merge-base", "--is-ancestor", a, b)
600 if err == nil {
601 return true, nil
602 }
603 var exitErr *exec.ExitError
604 if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 {
605 return false, nil
606 }
607 return false, err
608 }
609
610 // LogAll walks every ref in topological order. This is the input to the
611 // branch graph: --topo-order guarantees a child always precedes its
612 // parents, which the lane assignment depends on.
613 func (r *Repo) LogAll(n int) ([]Commit, error) {
614 if r.Empty() {
615 return nil, nil
616 }
617 format := strings.Join([]string{"%H", "%an", "%ae", "%aI", "%P", "%s", "%b"}, escLogF)
618 // Never request signature status here: this walks every ref unbounded
619 // for the graph view, and git forks gpg per signed commit -- fine at
620 // Log's n=20, not fine here.
621 out, err := r.run("log", "--all", "--topo-order", "--date-order",
622 "-n", strconv.Itoa(n), "--format="+escLogR+format)
623 return r.parseLog(out, err, false)
624 }
625
626 // ------------------------------------------------------------------- trees
627
628 type Entry struct {
629 Mode string
630 Type string // "blob" | "tree" | "commit" (submodule)
631 SHA string
632 Size int64
633 Name string // basename
634 Path string // full path from repo root
635 }
636
637 func (e Entry) IsDir() bool { return e.Type == "tree" }
638 func (e Entry) IsSubmodule() bool { return e.Type == "commit" }
639
640 // Tree lists one directory level at rev.
641 func (r *Repo) Tree(rev, path string) ([]Entry, error) {
642 if r.Empty() {
643 return nil, nil
644 }
645 spec := rev + ":"
646 if path != "" && path != "." {
647 spec = rev + ":" + path
648 }
649 out, err := r.run("ls-tree", "-z", "--long", spec)
650 if err != nil {
651 return nil, err
652 }
653 var entries []Entry
654 for _, rec := range strings.Split(string(out), "\x00") {
655 if rec == "" {
656 continue
657 }
658 head, name, ok := strings.Cut(rec, "\t")
659 if !ok {
660 continue
661 }
662 f := strings.Fields(head)
663 if len(f) < 3 {
664 continue
665 }
666 e := Entry{Mode: f[0], Type: f[1], SHA: f[2], Name: name}
667 if len(f) > 3 {
668 e.Size, _ = strconv.ParseInt(f[3], 10, 64)
669 }
670 e.Path = strings.TrimPrefix(path+"/"+name, "/")
671 entries = append(entries, e)
672 }
673 return entries, nil
674 }
675
676 // Stat looks up a single path's own tree entry (its mode/type/sha as
677 // recorded by its parent tree), regardless of depth. Unlike Blob, this
678 // works for gitlinks (submodules), since it never tries to read object
679 // contents.
680 func (r *Repo) Stat(rev, path string) (Entry, bool, error) {
681 out, err := r.run("ls-tree", "-z", "--long", rev, "--", path)
682 if err != nil {
683 return Entry{}, false, err
684 }
685 rec := strings.TrimSuffix(string(out), "\x00")
686 if rec == "" {
687 return Entry{}, false, nil
688 }
689 head, name, ok := strings.Cut(rec, "\t")
690 if !ok {
691 return Entry{}, false, nil
692 }
693 f := strings.Fields(head)
694 if len(f) < 3 {
695 return Entry{}, false, nil
696 }
697 e := Entry{Mode: f[0], Type: f[1], SHA: f[2], Name: filepath.Base(name), Path: name}
698 if len(f) > 3 {
699 e.Size, _ = strconv.ParseInt(f[3], 10, 64)
700 }
701 return e, true, nil
702 }
703
704 // SubmoduleURL looks up the remote configured for a submodule path in
705 // .gitmodules at rev. Best-effort: a missing or unparsable file just means
706 // no URL is shown alongside the pinned commit.
707 func (r *Repo) SubmoduleURL(rev, path string) string {
708 raw, err := r.Blob(rev, ".gitmodules")
709 if err != nil {
710 return ""
711 }
712 var inSection, sectionMatches bool
713 for _, line := range strings.Split(string(raw), "\n") {
714 line = strings.TrimSpace(line)
715 if strings.HasPrefix(line, "[submodule") {
716 inSection = true
717 sectionMatches = false
718 continue
719 }
720 if !inSection {
721 continue
722 }
723 key, val, ok := strings.Cut(line, "=")
724 if !ok {
725 continue
726 }
727 key, val = strings.TrimSpace(key), strings.TrimSpace(val)
728 switch key {
729 case "path":
730 sectionMatches = val == path
731 case "url":
732 if sectionMatches {
733 return val
734 }
735 }
736 }
737 return ""
738 }
739
740 // ------------------------------------------------------------------ diffs
741
742 type FileStat struct {
743 Added, Deleted int
744 Path, OldPath string
745 Status string
746 }
747
748 type Diff struct {
749 Stats []FileStat
750 Patch string
751 Truncated bool
752 }
753
754 // DiffRange returns the patch between two resolved commits.
755 // Callers MUST pass SHAs from Resolve, never raw user input.
756 func (r *Repo) DiffRange(base, head string, threeDot bool) (Diff, error) {
757 sep := ".."
758 if threeDot {
759 sep = "..."
760 }
761 return r.diff("diff", "-p", "--no-color", "--no-ext-diff", "-M", "--numstat", base+sep+head)
762 }
763
764 // DiffCommit returns the patch for a single commit. --root makes the first
765 // commit diff against the empty tree instead of erroring.
766 func (r *Repo) DiffCommit(sha string) (Diff, error) {
767 return r.diff("diff-tree", "-p", "--root", "--no-color", "--no-ext-diff",
768 "-M", "--numstat", "--format=", sha)
769 }
770
771 func (r *Repo) diff(args ...string) (Diff, error) {
772 var d Diff
773 raw, err := r.run(args...)
774 if err == ErrTruncated {
775 d.Truncated = true
776 } else if err != nil {
777 return d, err
778 }
779 body := string(raw)
780 // numstat block comes first, then the patch; they are separated by the
781 // first line starting with "diff --git".
782 if i := strings.Index(body, "diff --git"); i >= 0 {
783 d.Stats = parseNumstat(body[:i])
784 d.Patch = body[i:]
785 } else {
786 d.Stats = parseNumstat(body)
787 }
788 return d, nil
789 }
790
791 func parseNumstat(s string) []FileStat {
792 var out []FileStat
793 for _, line := range strings.Split(s, "\n") {
794 f := strings.Split(strings.TrimSpace(line), "\t")
795 if len(f) < 3 {
796 continue
797 }
798 fs := FileStat{Path: f[2], Status: "M"}
799 if f[0] == "-" {
800 fs.Status = "B" // binary
801 } else {
802 fs.Added, _ = strconv.Atoi(f[0])
803 fs.Deleted, _ = strconv.Atoi(f[1])
804 }
805 out = append(out, fs)
806 }
807 return out
808 }
809
810 // Blob returns file contents at rev.
811 func (r *Repo) Blob(rev, path string) ([]byte, error) {
812 return r.run("cat-file", "blob", rev+":"+path)
813 }