internal/gitutil/gitutil.go

b44a1e91cd044f2131a51201329bf86eb8577571
gitbay/internal/gitutil/gitutil.go history · blame · raw

179 lines · 5986 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	"os"
 10	"os/exec"
 11	"path/filepath"
 12	"strings"
 13)
 14
 15// InitBare creates a bare repository with the shared hooks directory wired
 16// via core.hooksPath.
 17func InitBare(path, defaultBranch, hooksPath string) error {
 18	if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
 19		return err
 20	}
 21	cmd := exec.Command("git", "init", "--bare", "--initial-branch="+defaultBranch, path)
 22	if out, err := cmd.CombinedOutput(); err != nil {
 23		return fmt.Errorf("git init: %v\n%s", err, out)
 24	}
 25	cmd = exec.Command("git", "-C", path, "config", "core.hooksPath", hooksPath)
 26	if out, err := cmd.CombinedOutput(); err != nil {
 27		return fmt.Errorf("git config core.hooksPath: %v\n%s", err, out)
 28	}
 29	return nil
 30}
 31
 32// Transport streams one git transport service (upload-pack, receive-pack,
 33// upload-archive). extraEnv entries are appended to the process environment;
 34// hooks read the GITBAY_* variables from it. maxPack caps incoming pack
 35// bytes on receive-pack (0 = unlimited).
 36func Transport(service, repoPath string, stdin io.Reader, stdout, errW io.Writer, extraEnv []string, maxPack int64) error {
 37	var args []string
 38	switch service {
 39	case "git-upload-pack", "git-receive-pack", "git-upload-archive":
 40		if service == "git-receive-pack" && maxPack > 0 {
 41			args = []string{"-c", fmt.Sprintf("receive.maxInputSize=%d", maxPack)}
 42		}
 43		args = append(args, strings.TrimPrefix(service, "git-"), repoPath)
 44	default:
 45		return fmt.Errorf("unknown service %q", service)
 46	}
 47	cmd := exec.Command("git", args...)
 48	cmd.Env = append(os.Environ(), extraEnv...)
 49	cmd.Stdin = stdin
 50	cmd.Stdout = stdout
 51	cmd.Stderr = errW
 52	return cmd.Run()
 53}
 54
 55// IsAncestor reports whether old is an ancestor of new in the repository at
 56// dir. It must run with the caller's environment intact so that quarantined
 57// objects during pre-receive remain visible.
 58func IsAncestor(dir, old, new string) (bool, error) {
 59	cmd := exec.Command("git", "-C", dir, "merge-base", "--is-ancestor", old, new)
 60	err := cmd.Run()
 61	if err == nil {
 62		return true, nil
 63	}
 64	if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 1 {
 65		return false, nil
 66	}
 67	return false, err
 68}
 69
 70// ZeroSHA reports whether s is an all-zero object id (SHA-1 or SHA-256).
 71func ZeroSHA(s string) bool {
 72	if len(s) != 40 && len(s) != 64 {
 73		return false
 74	}
 75	for i := 0; i < len(s); i++ {
 76		if s[i] != '0' {
 77			return false
 78		}
 79	}
 80	return true
 81}
 82
 83// RevList returns up to limit commit SHAs reachable from ref, newest first.
 84func RevList(dir, ref string, limit int) ([]string, error) {
 85	cmd := exec.Command("git", "-C", dir, "rev-list", fmt.Sprintf("--max-count=%d", limit), ref)
 86	out, err := cmd.Output()
 87	if err != nil {
 88		return nil, fmt.Errorf("rev-list %s: %w", ref, err)
 89	}
 90	var shas []string
 91	for _, l := range strings.Split(strings.TrimSpace(string(out)), "\n") {
 92		if l != "" {
 93			shas = append(shas, l)
 94		}
 95	}
 96	return shas, nil
 97}
 98
 99// ReadCommit returns the raw commit object bytes.
100func ReadCommit(dir, sha string) ([]byte, error) {
101	cmd := exec.Command("git", "-C", dir, "cat-file", "commit", sha)
102	out, err := cmd.Output()
103	if err != nil {
104		return nil, fmt.Errorf("cat-file commit %s: %w", sha, err)
105	}
106	return out, nil
107}
108
109// FetchMirror pulls all branches, tags, and notes from a foreign URL into
110// the bare repository at dir, forcing updates. Progress streams to errW so
111// an interactive caller can watch. extraEnv carries credentials via
112// GIT_ASKPASS; the URL itself must never contain them.
113func FetchMirror(ctx context.Context, dir, url string, errW io.Writer, extraEnv []string) error {
114	cmd := exec.CommandContext(ctx, "git", "-C", dir, "fetch", "--progress", "--no-write-fetch-head", url,
115		"+refs/heads/*:refs/heads/*",
116		"+refs/tags/*:refs/tags/*",
117		"+refs/notes/*:refs/notes/*")
118	cmd.Env = append(os.Environ(), extraEnv...)
119	cmd.Stderr = errW
120	if err := cmd.Run(); err != nil {
121		return fmt.Errorf("fetch from %s: %w", url, err)
122	}
123	return nil
124}
125
126// RemoteDefaultBranch asks the remote which branch HEAD points at.
127func RemoteDefaultBranch(ctx context.Context, url string, extraEnv []string) (string, error) {
128	cmd := exec.CommandContext(ctx, "git", "ls-remote", "--symref", url, "HEAD")
129	cmd.Env = append(os.Environ(), extraEnv...)
130	out, err := cmd.Output()
131	if err != nil {
132		return "", fmt.Errorf("ls-remote %s: %w", url, err)
133	}
134	// "ref: refs/heads/<branch>\tHEAD"
135	for _, line := range strings.Split(string(out), "\n") {
136		if rest, ok := strings.CutPrefix(line, "ref: refs/heads/"); ok {
137			if branch, _, ok := strings.Cut(rest, "\t"); ok {
138				return branch, nil
139			}
140		}
141	}
142	return "", fmt.Errorf("remote %s did not advertise a default branch", url)
143}
144
145// SetHead points the bare repo's HEAD at a branch.
146func SetHead(dir, branch string) error {
147	cmd := exec.Command("git", "-C", dir, "symbolic-ref", "HEAD", "refs/heads/"+branch)
148	if out, err := cmd.CombinedOutput(); err != nil {
149		return fmt.Errorf("symbolic-ref: %v\n%s", err, out)
150	}
151	return nil
152}
153
154// gitDefaultDescription is the placeholder git init writes; treated as no
155// description at all.
156const gitDefaultDescription = "Unnamed repository; edit this file 'description' to name the repository."
157
158// ReadDescription returns the repo's description from the classic
159// <repo>.git/description file, empty for the git-init placeholder.
160func ReadDescription(dir string) string {
161	raw, err := os.ReadFile(filepath.Join(dir, "description"))
162	if err != nil {
163		return ""
164	}
165	desc := strings.TrimSpace(string(raw))
166	if desc == gitDefaultDescription {
167		return ""
168	}
169	return desc
170}
171
172// WriteDescription sets the description file: first line only, capped.
173func WriteDescription(dir, desc string) error {
174	desc, _, _ = strings.Cut(strings.TrimSpace(desc), "\n")
175	if len(desc) > 256 {
176		desc = desc[:256]
177	}
178	return os.WriteFile(filepath.Join(dir, "description"), []byte(desc+"\n"), 0o644)
179}