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