internal/gitutil/gitutil.go

32a5f76e5b270097b63a5bba9a43557cf50ad63d
gitbay/internal/gitutil/gitutil.go history · blame · raw

326 lines · 12337 bytes

  1// Package gitutil wraps the system git binary. All repository access goes
  2// through git subprocesses; there is no in-process git implementation.
  3package gitutil
  4
  5import (
  6	"context"
  7	"fmt"
  8	"io"
  9	"io/fs"
 10	"os"
 11	"os/exec"
 12	"path/filepath"
 13	"strings"
 14
 15	"gitbay.org/gitbay/internal/toolpath"
 16)
 17
 18// InitBare creates a bare repository with the shared hooks directory wired
 19// via core.hooksPath.
 20func InitBare(path, defaultBranch, hooksPath string) error {
 21	if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
 22		return err
 23	}
 24	cmd := exec.Command(toolpath.Look("git"), "init", "--bare", "--initial-branch="+defaultBranch, path)
 25	if out, err := cmd.CombinedOutput(); err != nil {
 26		return fmt.Errorf("git init: %v\n%s", err, out)
 27	}
 28	cmd = exec.Command(toolpath.Look("git"), "-C", path, "config", "core.hooksPath", hooksPath)
 29	if out, err := cmd.CombinedOutput(); err != nil {
 30		return fmt.Errorf("git config core.hooksPath: %v\n%s", err, out)
 31	}
 32	return nil
 33}
 34
 35// Transport streams one git transport service (upload-pack, receive-pack,
 36// upload-archive). extraEnv entries are appended to the process environment;
 37// hooks read the GITBAY_* variables from it. maxPack caps incoming pack
 38// bytes on receive-pack (0 = unlimited). Closing cancel kills the service
 39// and everything it started; a push killed before its pre-receive hook
 40// answers updates no refs. A nil cancel never fires.
 41func Transport(service, repoPath string, stdin io.Reader, stdout, errW io.Writer, extraEnv []string, maxPack int64, cancel <-chan struct{}) error {
 42	var args []string
 43	switch service {
 44	case "git-upload-pack", "git-receive-pack", "git-upload-archive":
 45		if service == "git-receive-pack" && maxPack > 0 {
 46			args = []string{"-c", fmt.Sprintf("receive.maxInputSize=%d", maxPack)}
 47		}
 48		args = append(args, strings.TrimPrefix(service, "git-"), repoPath)
 49	default:
 50		return fmt.Errorf("unknown service %q", service)
 51	}
 52	cmd := exec.Command(toolpath.Look("git"), args...)
 53	cmd.Env = append(os.Environ(), extraEnv...)
 54	cmd.Stdin = stdin
 55	cmd.Stdout = stdout
 56	cmd.Stderr = errW
 57	ownProcessGroup(cmd)
 58	if err := cmd.Start(); err != nil {
 59		return err
 60	}
 61	finished := make(chan struct{})
 62	go func() {
 63		select {
 64		case <-cancel:
 65			killTree(cmd)
 66		case <-finished:
 67		}
 68	}()
 69	err := cmd.Wait()
 70	close(finished)
 71	return err
 72}
 73
 74// IsAncestor reports whether old is an ancestor of new in the repository at
 75// dir. It must run with the caller's environment intact so that quarantined
 76// objects during pre-receive remain visible.
 77func IsAncestor(dir, old, new string) (bool, error) {
 78	cmd := exec.Command(toolpath.Look("git"), "-C", dir, "merge-base", "--is-ancestor", old, new)
 79	err := cmd.Run()
 80	if err == nil {
 81		return true, nil
 82	}
 83	if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 1 {
 84		return false, nil
 85	}
 86	return false, err
 87}
 88
 89// Reachable reports whether sha is reachable from some ref in the
 90// repository at dir — the condition a clone must find true to have any
 91// chance of checking it out. That includes refs outside refs/heads and
 92// refs/tags: a merge request head fetched from a fork lives at
 93// refs/merge-requests/<n>/head, and is exactly as fetchable as a branch
 94// tip, so it must count as reachable too — a first pass of this function
 95// restricted the check to branches and tags and read every fork MR's
 96// queued build as unreachable, cancelling it. false comes from two
 97// shapes, and Reachable does not need to tell them apart: the object is
 98// already gone (pruned), or it is still in the object store but nothing
 99// points at it any more (a force-push moved the branch, gc has not run
100// yet). Either way the answer is the same: no ref reaches it.
101//
102// A non-nil error means the check itself did not run to a clean answer —
103// missing repository, git failing for its own reasons — and false is
104// meaningless in that case. The caller must not read err as "unreachable":
105// that would cancel a build the check never actually looked at.
106func Reachable(dir, sha string) (bool, error) {
107	if _, err := os.Stat(dir); err != nil {
108		return false, fmt.Errorf("reachable %s: %w", sha, err)
109	}
110	// cat-file -e <object>, unpeeled, is git's own existence predicate with
111	// a documented exit code: 1 means the object is not there, the same
112	// contract IsAncestor above already trusts from merge-base
113	// --is-ancestor. Peeling to ^{commit} breaks that contract: a missing
114	// object then exits 128, indistinguishable from "not a git repository"
115	// or a corrupted one — the ambiguous case that must never read as
116	// "unreachable" and cancel a build the check never actually looked at.
117	err := exec.Command(toolpath.Look("git"), "-C", dir, "cat-file", "-e", "--end-of-options", sha).Run()
118	if err != nil {
119		if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 1 {
120			return false, nil
121		}
122		return false, fmt.Errorf("cat-file -e %s: %w", sha, err)
123	}
124	// The object exists; --contains lists every ref whose history includes
125	// it, with no namespace restriction — a branch, a tag, or a
126	// refs/merge-requests/<n>/head are equally "a ref reaches this", and
127	// that is the actual question, not whether it happens to be a branch
128	// or a tag. Empty output with no error is the force-push case: present
129	// in the object store, reachable from nothing.
130	out, err := exec.Command(toolpath.Look("git"), "-C", dir, "for-each-ref",
131		"--count=1", "--format=x", "--contains="+sha).Output()
132	if err != nil {
133		return false, fmt.Errorf("for-each-ref --contains %s: %w", sha, err)
134	}
135	return len(out) > 0, nil
136}
137
138// ZeroSHA reports whether s is an all-zero object id (SHA-1 or SHA-256).
139func ZeroSHA(s string) bool {
140	if len(s) != 40 && len(s) != 64 {
141		return false
142	}
143	for i := 0; i < len(s); i++ {
144		if s[i] != '0' {
145			return false
146		}
147	}
148	return true
149}
150
151// RevList returns up to limit commit SHAs reachable from ref, newest first.
152func RevList(dir, ref string, limit int) ([]string, error) {
153	cmd := exec.Command(toolpath.Look("git"), "-C", dir, "rev-list", fmt.Sprintf("--max-count=%d", limit), "--end-of-options", ref)
154	out, err := cmd.Output()
155	if err != nil {
156		return nil, fmt.Errorf("rev-list %s: %w", ref, err)
157	}
158	var shas []string
159	for _, l := range strings.Split(strings.TrimSpace(string(out)), "\n") {
160		if l != "" {
161			shas = append(shas, l)
162		}
163	}
164	return shas, nil
165}
166
167// RevListPath returns up to limit commit SHAs reachable from ref that
168// touch filePath, newest first. The "--" keeps the path from ever being
169// read as an option or ref.
170func RevListPath(dir, ref, filePath string, limit int) ([]string, error) {
171	cmd := exec.Command(toolpath.Look("git"), "-C", dir, "rev-list",
172		fmt.Sprintf("--max-count=%d", limit), "--end-of-options", ref, "--", filePath)
173	out, err := cmd.Output()
174	if err != nil {
175		return nil, fmt.Errorf("rev-list %s -- %s: %w", ref, filePath, err)
176	}
177	var shas []string
178	for _, l := range strings.Split(strings.TrimSpace(string(out)), "\n") {
179		if l != "" {
180			shas = append(shas, l)
181		}
182	}
183	return shas, nil
184}
185
186// PeelToCommit resolves a ref or object to its commit — annotated tags
187// peel to the commit they point at.
188func PeelToCommit(dir, ref string) (string, error) {
189	out, err := exec.Command(toolpath.Look("git"), "-C", dir, "rev-parse", "--verify", "--end-of-options", ref+"^{commit}").Output()
190	if err != nil {
191		return "", fmt.Errorf("rev-parse %s^{commit}: %w", ref, err)
192	}
193	return strings.TrimSpace(string(out)), nil
194}
195
196// ReadCommit returns the raw commit object bytes.
197func ReadCommit(dir, sha string) ([]byte, error) {
198	cmd := exec.Command(toolpath.Look("git"), "-C", dir, "cat-file", "commit", "--end-of-options", sha)
199	out, err := cmd.Output()
200	if err != nil {
201		return nil, fmt.Errorf("cat-file commit %s: %w", sha, err)
202	}
203	return out, nil
204}
205
206// FetchMirror pulls all branches, tags, and notes from a foreign URL into
207// the bare repository at dir, forcing updates. Progress streams to errW so
208// an interactive caller can watch. extraEnv carries credentials via
209// GIT_ASKPASS; the URL itself must never contain them.
210func FetchMirror(ctx context.Context, dir, url string, errW io.Writer, extraEnv []string) error {
211	cmd := exec.CommandContext(ctx, toolpath.Look("git"), "-C", dir, "fetch", "--progress", "--no-write-fetch-head", url,
212		"+refs/heads/*:refs/heads/*",
213		"+refs/tags/*:refs/tags/*",
214		"+refs/notes/*:refs/notes/*")
215	cmd.Env = append(os.Environ(), extraEnv...)
216	cmd.Stderr = errW
217	if err := cmd.Run(); err != nil {
218		return fmt.Errorf("fetch from %s: %w", url, err)
219	}
220	return nil
221}
222
223// FetchPullHeads pulls a GitHub repository's pull-request heads into
224// refs/gh-pull/*, so an imported pull request has something to diff.
225// GitHub publishes every PR head at refs/pull/<n>/head on the git remote,
226// but a mirror made with the default refspecs does not carry them, which
227// is why an import used to produce merge requests with no head at all.
228//
229// One fetch for every pull request rather than one each: the ref count is
230// the repository's history, and asking a hundred times is a hundred
231// handshakes. extraEnv carries credentials via GIT_ASKPASS; the URL must
232// never contain them.
233func FetchPullHeads(ctx context.Context, dir, url string, errW io.Writer, extraEnv []string) error {
234	cmd := exec.CommandContext(ctx, toolpath.Look("git"), "-C", dir, "fetch", "--no-write-fetch-head", "--no-tags",
235		url, "+refs/pull/*/head:refs/gh-pull/*")
236	cmd.Env = append(os.Environ(), extraEnv...)
237	cmd.Stderr = errW
238	if err := cmd.Run(); err != nil {
239		return fmt.Errorf("fetch pull heads from %s: %w", url, err)
240	}
241	return nil
242}
243
244// RemoteDefaultBranch asks the remote which branch HEAD points at.
245func RemoteDefaultBranch(ctx context.Context, url string, extraEnv []string) (string, error) {
246	cmd := exec.CommandContext(ctx, toolpath.Look("git"), "ls-remote", "--symref", url, "HEAD")
247	cmd.Env = append(os.Environ(), extraEnv...)
248	out, err := cmd.Output()
249	if err != nil {
250		return "", fmt.Errorf("ls-remote %s: %w", url, err)
251	}
252	// "ref: refs/heads/<branch>\tHEAD"
253	for _, line := range strings.Split(string(out), "\n") {
254		if rest, ok := strings.CutPrefix(line, "ref: refs/heads/"); ok {
255			if branch, _, ok := strings.Cut(rest, "\t"); ok {
256				return branch, nil
257			}
258		}
259	}
260	return "", fmt.Errorf("remote %s did not advertise a default branch", url)
261}
262
263// SetHead points the bare repo's HEAD at a branch.
264func SetHead(dir, branch string) error {
265	cmd := exec.Command(toolpath.Look("git"), "-C", dir, "symbolic-ref", "HEAD", "refs/heads/"+branch)
266	if out, err := cmd.CombinedOutput(); err != nil {
267		return fmt.Errorf("symbolic-ref: %v\n%s", err, out)
268	}
269	return nil
270}
271
272// gitDefaultDescription is the placeholder git init writes; treated as no
273// description at all.
274const gitDefaultDescription = "Unnamed repository; edit this file 'description' to name the repository."
275
276// ReadDescription returns the repo's description from the classic
277// <repo>.git/description file, empty for the git-init placeholder.
278func ReadDescription(dir string) string {
279	raw, err := os.ReadFile(filepath.Join(dir, "description"))
280	if err != nil {
281		return ""
282	}
283	desc := strings.TrimSpace(string(raw))
284	if desc == gitDefaultDescription {
285		return ""
286	}
287	return desc
288}
289
290// WriteDescription sets the description file: first line only, capped.
291func WriteDescription(dir, desc string) error {
292	desc, _, _ = strings.Cut(strings.TrimSpace(desc), "\n")
293	if len(desc) > 256 {
294		desc = desc[:256]
295	}
296	return os.WriteFile(filepath.Join(dir, "description"), []byte(desc+"\n"), 0o644)
297}
298
299// DirSize sums file sizes under dir; unreadable entries count as zero.
300func DirSize(dir string) int64 {
301	var total int64
302	filepath.WalkDir(dir, func(_ string, d fs.DirEntry, err error) error {
303		if err != nil || d.IsDir() {
304			return nil
305		}
306		if fi, err := d.Info(); err == nil {
307			total += fi.Size()
308		}
309		return nil
310	})
311	return total
312}
313
314// Every git this package runs prints paths as they are, not quoted with
315// octal escapes the way core.quotepath does by default, so a file called
316// übersicht.txt lists, greps, blames and diffs under its own name.
317// GIT_CONFIG_PARAMETERS reaches every subprocess, hooks included,
318// without touching each call site (#129).
319func init() {
320	const q = "'core.quotepath=off'"
321	if cur := os.Getenv("GIT_CONFIG_PARAMETERS"); cur != "" {
322		os.Setenv("GIT_CONFIG_PARAMETERS", cur+" "+q)
323	} else {
324		os.Setenv("GIT_CONFIG_PARAMETERS", q)
325	}
326}