gunk-dev/the-valley

git.go

sourcecaaa5bee5e11main's published tip history
45.3 KiB
1package git
2
3import (
4 "bytes"
5 "context"
6 "fmt"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "slices"
11 "strconv"
12 "strings"
13 "sync"
14 "time"
15)
16
17// Timeout constants for git operations.
18const (
19 // networkTimeout is for git commands that talk to a remote (fetch, push, clone).
20 networkTimeout = 2 * time.Minute
21 // localTimeout is for git commands that operate on local data (worktree, branch, rev-parse).
22 localTimeout = 30 * time.Second
23 // verifyTimeout bounds best-effort remote checks at finalize.
24 verifyTimeout = 20 * time.Second
25)
26
27// RepoRoot returns the top-level directory of the git repository.
28func RepoRoot() (string, error) {
29 return runGit(context.Background(), "", "rev-parse", "--show-toplevel")
30}
31
32// CommonDir returns the absolute path to the git common directory.
33// This works from worktrees too (returns the main repo's .git dir).
34func CommonDir(ctx context.Context) (string, error) {
35 d, err := runGit(ctx, "", "rev-parse", "--git-common-dir")
36 if err != nil {
37 return "", err
38 }
39 // --git-common-dir can return a relative path in the main worktree
40 abs, err := filepath.Abs(d)
41 if err != nil {
42 return "", fmt.Errorf("resolving common dir: %w", err)
43 }
44 return abs, nil
45}
46
47// FetchAll fetches all branches and tags from origin, pruning deleted remote branches.
48func FetchAll(ctx context.Context, repoDir string) error {
49 _, err := runGitNetwork(ctx, repoDir, "fetch", "origin", "--prune", "--tags", "--quiet")
50 return err
51}
52
53// FetchBranch fetches a branch from origin.
54func FetchBranch(ctx context.Context, repoDir, branch string) error {
55 _, err := runGitNetwork(ctx, repoDir, "fetch", "origin", branch, "--quiet")
56 return err
57}
58
59// FetchRemoteBranch updates origin's branch, as repoDir tracks it in
60// refs/remotes/origin, to what origin holds now.
61func FetchRemoteBranch(ctx context.Context, repoDir, branch string) error {
62 _, err := runGitNetwork(ctx, repoDir, "fetch", "--quiet", "origin", "+refs/heads/"+branch+":refs/remotes/origin/"+branch)
63 return err
64}
65
66// FetchDataRef updates the local data ref from origin. It is best-effort:
67// callers should ignore the error (there may be no remote, the ref may not
68// exist remotely, or the local ref may already be current). When the local
69// ref is missing and the remote has it, the ref is created locally.
70func FetchDataRef(ctx context.Context, repoDir, dataRef string) error {
71 _, err := runGitNetwork(ctx, repoDir, "fetch", "origin", dataRef+":"+dataRef, "--quiet")
72 return err
73}
74
75// ReadDataRefFile returns the raw bytes of a file stored in the data ref tree.
76// treePath is the path within the ref's tree (e.g. "sessions/<run-id>.jsonl").
77// It returns an error if the ref or path does not exist. Output is not trimmed,
78// so JSONL content (including trailing newlines) is preserved verbatim.
79func ReadDataRefFile(ctx context.Context, repoDir, dataRef, treePath string) ([]byte, error) {
80 ctx, cancel := ensureTimeout(ctx, localTimeout)
81 defer cancel()
82
83 cmd := exec.CommandContext(ctx, "git", "cat-file", "blob", dataRef+":"+treePath)
84 if repoDir != "" {
85 cmd.Dir = repoDir
86 }
87 var stdout, stderr bytes.Buffer
88 cmd.Stdout = &stdout
89 cmd.Stderr = &stderr
90 if err := cmd.Run(); err != nil {
91 if ctx.Err() == context.DeadlineExceeded {
92 return nil, fmt.Errorf("git cat-file timed out after %s", localTimeout)
93 }
94 return nil, fmt.Errorf("reading %s from %s: %w: %s", treePath, dataRef, err, stderr.String())
95 }
96 return stdout.Bytes(), nil
97}
98
99// WorktreeAdd creates a new worktree at path on a new branch based on startPoint.
100// It refuses when path already exists. If the branch is already checked out
101// in a stale worktree, it prunes and retries once; it never removes a
102// worktree whose directory exists.
103func WorktreeAdd(ctx context.Context, repoDir, path, branch, startPoint string) error {
104 if err := checkPathFree(path); err != nil {
105 return err
106 }
107 _, err := runGit(ctx, repoDir, "worktree", "add", path, "-b", branch, startPoint, "--quiet")
108 if err == nil {
109 return nil
110 }
111 return retryAfterPrune(ctx, repoDir, branch, err, func() error {
112 // Use -B on retry: after pruning a stale worktree the branch ref remains,
113 // so -b (create new) would fail with "branch already exists".
114 _, e := runGit(ctx, repoDir, "worktree", "add", path, "-B", branch, startPoint, "--quiet")
115 return e
116 })
117}
118
119// WorktreeRemove removes a worktree. repoDir is the main repo directory.
120func WorktreeRemove(ctx context.Context, repoDir, path string) error {
121 _, err := runGit(ctx, repoDir, "worktree", "remove", "--force", path)
122 return err
123}
124
125// WorktreeAddTrack creates a worktree at path tracking an existing remote
126// branch. It uses -B to force-create/reset the local branch to match
127// origin/<branch>. It refuses when path already exists.
128//
129// It never removes a worktree to make way. When the branch is checked out
130// in another worktree whose directory is gone, it prunes that entry; when
131// that directory exists, it refuses with a *WorktreeInUseError, saying what
132// work there origin lacks. Git knows a worktree only by its path, so no
133// check of which worktree that is could keep a removal from taking one
134// recreated at the same path since.
135//
136// Unless discard is set, it refuses with a *LocalWorkError when the local
137// branch has commits that aren't on origin/<branch>; with discard, the
138// reset drops them. A local branch that only points at what origin has is
139// reset freely.
140func WorktreeAddTrack(ctx context.Context, repoDir, path, branch string, discard bool) error {
141 if err := checkPathFree(path); err != nil {
142 return err
143 }
144 if wt := worktreePathForBranch(ctx, repoDir, branch); wt != "" {
145 if _, err := os.Stat(wt); err == nil {
146 work, err := localWork(ctx, repoDir, wt, branch)
147 if err != nil {
148 return err
149 }
150 return &WorktreeInUseError{Branch: branch, Path: wt, Work: work}
151 }
152 if err := WorktreePrune(ctx, repoDir); err != nil {
153 return fmt.Errorf("pruning stale worktrees: %w", err)
154 }
155 }
156 if !discard {
157 work, err := localWork(ctx, repoDir, "", branch)
158 if err != nil {
159 return err
160 }
161 if work != "" {
162 return &LocalWorkError{Branch: branch, Work: work}
163 }
164 }
165 _, err := runGit(ctx, repoDir, "worktree", "add", "-B", branch, path, "origin/"+branch, "--quiet")
166 return err
167}
168
169// WorktreeInUseError is WorktreeAddTrack's refusal while the worktree at
170// Path, whose directory exists, has Branch checked out.
171type WorktreeInUseError struct {
172 Branch string
173 Path string
174 Work string // what it holds that origin lacks, e.g. "uncommitted changes"; "" for nothing
175}
176
177func (e *WorktreeInUseError) Error() string {
178 if e.Work == "" {
179 return fmt.Sprintf("branch %q is checked out in worktree %s", e.Branch, e.Path)
180 }
181 return fmt.Sprintf("branch %q is checked out in worktree %s, which has %s", e.Branch, e.Path, e.Work)
182}
183
184// BranchWorktree returns the path of the worktree that has branch checked
185// out in repoDir, or "" when none does.
186func BranchWorktree(ctx context.Context, repoDir, branch string) string {
187 return worktreePathForBranch(ctx, repoDir, branch)
188}
189
190// checkPathFree refuses a new worktree's path that already holds anything.
191func checkPathFree(path string) error {
192 if _, err := os.Lstat(path); err == nil {
193 return fmt.Errorf("worktree path %s already exists", path)
194 } else if !os.IsNotExist(err) {
195 return fmt.Errorf("checking worktree path %s: %w", path, err)
196 }
197 return nil
198}
199
200// LocalWorkError is WorktreeAddTrack's refusal to discard commits that
201// origin lacks on the local Branch, which no worktree has checked out.
202type LocalWorkError struct {
203 Branch string
204 Work string // what origin lacks, e.g. "1 commit(s) not on origin/<branch>"
205}
206
207func (e *LocalWorkError) Error() string {
208 return fmt.Sprintf("local branch %q has %s", e.Branch, e.Work)
209}
210
211// localWork is what branch holds that origin/<branch> lacks: uncommitted
212// changes in wt, the worktree that has it checked out ("" for none), or
213// else local commits that aren't on origin/<branch>. "" for nothing.
214func localWork(ctx context.Context, repoDir, wt, branch string) (string, error) {
215 if wt != "" {
216 dirty, err := hasUncommittedChanges(ctx, wt)
217 if err != nil {
218 return "", fmt.Errorf("checking %s for uncommitted changes: %w", wt, err)
219 }
220 if dirty {
221 return "uncommitted changes", nil
222 }
223 }
224 local, remote := "refs/heads/"+branch, "refs/remotes/origin/"+branch
225 if !RefExists(ctx, repoDir, local) || !RefExists(ctx, repoDir, remote) {
226 return "", nil
227 }
228 n, err := revListCount(ctx, repoDir, remote+".."+local)
229 if err != nil {
230 return "", fmt.Errorf("checking branch %q for commits not on origin: %w", branch, err)
231 }
232 if n > 0 {
233 return fmt.Sprintf("%d commit(s) not on origin/%s", n, branch), nil
234 }
235 return "", nil
236}
237
238// hasUncommittedChanges reports whether the worktree at dir has staged,
239// modified or untracked files.
240func hasUncommittedChanges(ctx context.Context, dir string) (bool, error) {
241 out, err := runGit(ctx, dir, "status", "--porcelain", "--untracked-files=all")
242 if err != nil {
243 return false, err
244 }
245 return strings.TrimSpace(out) != "", nil
246}
247
248// WorktreePrune removes stale worktree tracking information.
249func WorktreePrune(ctx context.Context, repoDir string) error {
250 _, err := runGit(ctx, repoDir, "worktree", "prune")
251 return err
252}
253
254// worktreePathForBranch returns the worktree path that has the given branch
255// checked out, or "" if not found.
256func worktreePathForBranch(ctx context.Context, repoDir, branch string) string {
257 out, err := runGit(ctx, repoDir, "worktree", "list", "--porcelain")
258 if err != nil {
259 return ""
260 }
261 var currentPath string
262 for _, line := range strings.Split(out, "\n") {
263 line = strings.TrimSpace(line)
264 if strings.HasPrefix(line, "worktree ") {
265 currentPath = strings.TrimPrefix(line, "worktree ")
266 }
267 if strings.HasPrefix(line, "branch ") {
268 ref := strings.TrimPrefix(line, "branch ")
269 // branch ref looks like "refs/heads/<branch>"
270 if ref == "refs/heads/"+branch {
271 return currentPath
272 }
273 }
274 }
275 return ""
276}
277
278// retryAfterPrune handles "already used by worktree" errors. If the conflicting
279// worktree is stale (path no longer exists on disk), it prunes and retries.
280// If the worktree directory still exists, it returns a clear error and
281// leaves it alone.
282func retryAfterPrune(ctx context.Context, repoDir, branch string, origErr error, retry func() error) error {
283 // Check whether this branch is recorded in any worktree.
284 wtPath := worktreePathForBranch(ctx, repoDir, branch)
285 if wtPath == "" {
286 // Branch is not in any worktree — nothing to prune; return the original error.
287 return origErr
288 }
289
290 if _, err := os.Stat(wtPath); err == nil {
291 return fmt.Errorf("branch %q is already checked out in active worktree %q; remove it first with: git worktree remove %s", branch, wtPath, wtPath)
292 }
293
294 // Worktree directory is gone — prune stale entries and retry.
295 if err := WorktreePrune(ctx, repoDir); err != nil {
296 return fmt.Errorf("pruning stale worktrees: %w (original error: %v)", err, origErr)
297 }
298 return retry()
299}
300
301// CheckBranchName reports whether name can be used verbatim as a new branch
302// name, by git check-ref-format --branch. A name git would expand, such as
303// @{-1}, is rejected too.
304func CheckBranchName(ctx context.Context, name string) error {
305 out, err := runGit(ctx, "", "check-ref-format", "--branch", name)
306 if err != nil {
307 return fmt.Errorf("%q is not a valid branch name", name)
308 }
309 if out != name {
310 return fmt.Errorf("%q is not a valid branch name (git reads it as %q)", name, out)
311 }
312 return nil
313}
314
315// RefExists reports whether ref resolves to an object in repoDir.
316func RefExists(ctx context.Context, repoDir, ref string) bool {
317 _, err := runGit(ctx, repoDir, "rev-parse", "--verify", "--quiet", ref)
318 return err == nil
319}
320
321// RefCommit returns the commit ref resolves to in repoDir, or "" when it
322// resolves to none.
323func RefCommit(ctx context.Context, repoDir, ref string) string {
324 sha, err := runGit(ctx, repoDir, "rev-parse", "--verify", "--quiet", ref+"^{commit}")
325 if err != nil {
326 return ""
327 }
328 return sha
329}
330
331// IsAncestor reports whether commit a is b or one of its ancestors in
332// repoDir; false when either is unknown there.
333func IsAncestor(ctx context.Context, repoDir, a, b string) bool {
334 _, err := runGit(ctx, repoDir, "merge-base", "--is-ancestor", a, b)
335 return err == nil
336}
337
338// BranchDelete deletes a local branch.
339func BranchDelete(ctx context.Context, repoDir, branch string) error {
340 _, err := runGit(ctx, repoDir, "branch", "-D", branch)
341 return err
342}
343
344// IsClean reports whether the working tree at repoDir has no uncommitted changes.
345// Returns true only when git status --porcelain produces empty output.
346func IsClean(ctx context.Context, repoDir string) (bool, error) {
347 out, err := runGit(ctx, repoDir, "status", "--porcelain")
348 if err != nil {
349 return false, err
350 }
351 return out == "", nil
352}
353
354// CurrentBranch returns the short name of the currently checked-out branch,
355// or "" if the repo is in a detached HEAD state. Any other failure (not a git
356// repo, missing HEAD, etc.) is returned as an error rather than silently
357// treated as "no branch".
358func CurrentBranch(ctx context.Context, repoDir string) (string, error) {
359 ctx, cancel := ensureTimeout(ctx, localTimeout)
360 defer cancel()
361
362 cmd := exec.CommandContext(ctx, "git", "symbolic-ref", "--quiet", "--short", "HEAD")
363 cmd.Dir = repoDir
364 var stdout, stderr bytes.Buffer
365 cmd.Stdout = &stdout
366 cmd.Stderr = &stderr
367 err := cmd.Run()
368 if err == nil {
369 return strings.TrimSpace(stdout.String()), nil
370 }
371 if ctx.Err() == context.DeadlineExceeded {
372 return "", fmt.Errorf("git symbolic-ref timed out after %s", localTimeout)
373 }
374 // With --quiet, symbolic-ref exits with code 1 ONLY when HEAD is not a
375 // symbolic ref (i.e., detached HEAD). Other failures (e.g., not a git
376 // repo → "fatal:" exit 128) still need to bubble up.
377 if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 1 && stderr.Len() == 0 {
378 return "", nil
379 }
380 return "", fmt.Errorf("git symbolic-ref: %w: %s", err, stderr.String())
381}
382
383// HasUpstream reports whether the current branch at repoDir has a tracking
384// upstream. Missing upstream (a normal state) is reported as (false, nil);
385// other failures — not a git repo, bad path, I/O errors — return an error.
386func HasUpstream(ctx context.Context, repoDir string) (bool, error) {
387 ctx, cancel := ensureTimeout(ctx, localTimeout)
388 defer cancel()
389
390 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}")
391 cmd.Dir = repoDir
392 var stdout, stderr bytes.Buffer
393 cmd.Stdout = &stdout
394 cmd.Stderr = &stderr
395 err := cmd.Run()
396 if err == nil {
397 return strings.TrimSpace(stdout.String()) != "", nil
398 }
399 if ctx.Err() == context.DeadlineExceeded {
400 return false, fmt.Errorf("git rev-parse timed out after %s", localTimeout)
401 }
402 // Git reports missing upstream with specific stderr text and exit 128.
403 // Distinguish that from fatal errors like "not a git repository".
404 se := stderr.String()
405 if isNoUpstreamErr(se) {
406 return false, nil
407 }
408 return false, fmt.Errorf("git rev-parse: %w: %s", err, se)
409}
410
411// isNoUpstreamErr returns true if stderr matches the messages git emits when
412// a branch has no configured upstream. Covers both `@{u}` phrasings seen in
413// modern git.
414func isNoUpstreamErr(stderr string) bool {
415 s := strings.ToLower(stderr)
416 return strings.Contains(s, "no upstream configured") ||
417 strings.Contains(s, "does not point to a branch") ||
418 strings.Contains(s, "head does not point")
419}
420
421// MergeFastForward runs `git merge --ff-only @{u}` in repoDir. Fails if the
422// current branch has diverged from upstream, has no upstream, or the working
423// tree isn't clean. Does NOT touch the tree on failure.
424func MergeFastForward(ctx context.Context, repoDir string) error {
425 _, err := runGit(ctx, repoDir, "merge", "--ff-only", "--quiet", "@{u}")
426 return err
427}
428
429// CommitsBehindUpstream returns how many commits the current branch is behind
430// its upstream. Returns 0 if already up-to-date. Assumes an upstream exists;
431// callers should check HasUpstream first.
432func CommitsBehindUpstream(ctx context.Context, repoDir string) (int, error) {
433 out, err := runGit(ctx, repoDir, "rev-list", "--count", "HEAD..@{u}")
434 if err != nil {
435 return 0, err
436 }
437 n, err := strconv.Atoi(strings.TrimSpace(out))
438 if err != nil {
439 return 0, fmt.Errorf("parsing rev-list --count output %q: %w", out, err)
440 }
441 return n, nil
442}
443
444// CommitsAhead returns the number of commits on ref not reachable from base.
445func CommitsAhead(ctx context.Context, repoDir, base, ref string) (int, error) {
446 return revListCount(ctx, repoDir, base+".."+ref)
447}
448
449// BranchPushed reports whether origin's branch tip equals the local tip. It
450// asks the remote (ls-remote), not cached origin/* refs; an error means
451// unverified.
452func BranchPushed(ctx context.Context, repoDir, branch string) (bool, error) {
453 local, err := runGit(ctx, repoDir, "rev-parse", "--verify", "refs/heads/"+branch)
454 if err != nil {
455 return false, err
456 }
457 remote, err := RemoteBranchSHA(ctx, repoDir, branch)
458 if err != nil {
459 return false, err
460 }
461 return remote == local, nil
462}
463
464// RemoteBranchSHA returns origin's tip of branch, or "" when origin has no
465// such branch. It asks the remote (ls-remote), not cached origin/* refs.
466func RemoteBranchSHA(ctx context.Context, repoDir, branch string) (string, error) {
467 ctx, cancel := context.WithTimeout(ctx, verifyTimeout)
468 defer cancel()
469 out, err := runGitNetwork(ctx, repoDir, "ls-remote", "--heads", "origin", "refs/heads/"+branch)
470 if err != nil {
471 return "", err
472 }
473 sha, _, _ := strings.Cut(out, "\t")
474 return sha, nil
475}
476
477func revListCount(ctx context.Context, repoDir string, args ...string) (int, error) {
478 out, err := runGit(ctx, repoDir, append([]string{"rev-list", "--count"}, args...)...)
479 if err != nil {
480 return 0, err
481 }
482 n, err := strconv.Atoi(strings.TrimSpace(out))
483 if err != nil {
484 return 0, fmt.Errorf("parsing rev-list --count output %q: %w", out, err)
485 }
486 return n, nil
487}
488
489// EnsureDataRef ensures the custom data ref exists. Creates it with an empty
490// initial commit if it doesn't. Uses git plumbing so nothing in the working
491// tree is touched.
492func EnsureDataRef(ctx context.Context, repoDir, dataRef string) error {
493 _, err := runGit(ctx, repoDir, "rev-parse", "--verify", dataRef)
494 if err == nil {
495 return nil // already exists
496 }
497
498 // Create empty tree
499 emptyTree, err := runGit(ctx, repoDir, "hash-object", "-t", "tree", "/dev/null")
500 if err != nil {
501 return fmt.Errorf("creating empty tree: %w", err)
502 }
503
504 // Create initial commit
505 initCommit, err := runGitStdin(ctx, repoDir, "Initialize klaus run data", "commit-tree", emptyTree)
506 if err != nil {
507 return fmt.Errorf("creating initial commit: %w", err)
508 }
509
510 // Create the ref only if it is still missing: a writer that created it
511 // meanwhile may already have added a run's commit to it.
512 if _, err := runGit(ctx, repoDir, "update-ref", dataRef, initCommit, ""); err != nil {
513 if _, verr := runGit(ctx, repoDir, "rev-parse", "--verify", dataRef); verr == nil {
514 return nil
515 }
516 return err
517 }
518 return nil
519}
520
521// dataRefAttempts bounds how often SyncToDataRef rebuilds its commit on a
522// data ref that another writer moved meanwhile.
523const dataRefAttempts = 5
524
525// beforeDataRefUpdate runs in SyncToDataRef after it builds its commit and
526// before it moves the ref, so a test can interleave another writer there.
527var beforeDataRefUpdate = func() {}
528
529// SetBeforeDataRefUpdate sets the function SyncToDataRef runs between
530// building its commit and moving the data ref (for testing), and returns a
531// function that restores the previous one.
532func SetBeforeDataRefUpdate(fn func()) (restore func()) {
533 prev := beforeDataRefUpdate
534 beforeDataRefUpdate = fn
535 return func() { beforeDataRefUpdate = prev }
536}
537
538// SyncToDataRef commits files to the data ref using a temporary index and
539// returns the commit it wrote. files is a map of path-in-tree ->
540// local-file-path. It moves the ref only from the tip it built on, so two
541// writers in one clone both land: when the ref moved meanwhile, it rebuilds
542// its commit on the new tip, up to dataRefAttempts times.
543func SyncToDataRef(ctx context.Context, repoDir, dataRef, commitMsg string, files map[string]string) (string, error) {
544 if err := EnsureDataRef(ctx, repoDir, dataRef); err != nil {
545 return "", err
546 }
547
548 blobs := make(map[string]string, len(files))
549 for treePath, localPath := range files {
550 blob, err := runGit(ctx, repoDir, "hash-object", "-w", localPath)
551 if err != nil {
552 return "", fmt.Errorf("hashing %s: %w", localPath, err)
553 }
554 blobs[treePath] = blob
555 }
556
557 tmpIndex, err := os.CreateTemp("", "klaus-index-*")
558 if err != nil {
559 return "", fmt.Errorf("creating temp index: %w", err)
560 }
561 tmpIndexPath := tmpIndex.Name()
562 tmpIndex.Close()
563 defer os.Remove(tmpIndexPath)
564 index := map[string]string{"GIT_INDEX_FILE": tmpIndexPath}
565
566 for range dataRefAttempts {
567 parentCommit, err := runGit(ctx, repoDir, "rev-parse", "--verify", dataRef)
568 if err != nil {
569 return "", fmt.Errorf("resolving data ref: %w", err)
570 }
571 // read-tree replaces the whole index, so an earlier attempt leaves nothing behind.
572 if err := runGitEnv(ctx, repoDir, index, "read-tree", parentCommit); err != nil {
573 return "", fmt.Errorf("reading tree: %w", err)
574 }
575 for treePath, blob := range blobs {
576 cacheInfo := fmt.Sprintf("100644,%s,%s", blob, treePath)
577 if err := runGitEnv(ctx, repoDir, index, "update-index", "--add", "--cacheinfo", cacheInfo); err != nil {
578 return "", fmt.Errorf("updating index for %s: %w", treePath, err)
579 }
580 }
581 newTree, err := runGitOutput(ctx, repoDir, index, "write-tree")
582 if err != nil {
583 return "", fmt.Errorf("writing tree: %w", err)
584 }
585 newCommit, err := runGitStdin(ctx, repoDir, commitMsg, "commit-tree", newTree, "-p", parentCommit)
586 if err != nil {
587 return "", fmt.Errorf("creating commit: %w", err)
588 }
589
590 beforeDataRefUpdate()
591 _, err = runGit(ctx, repoDir, "update-ref", dataRef, newCommit, parentCommit)
592 if err == nil {
593 return newCommit, nil
594 }
595 if tip, terr := runGit(ctx, repoDir, "rev-parse", "--verify", dataRef); terr != nil || tip == parentCommit {
596 return "", err // the ref did not move, so building again cannot help
597 }
598 }
599 return "", fmt.Errorf("%s moved during each of %d attempts to add a commit to it", dataRef, dataRefAttempts)
600}
601
602// ghProtocol caches the result of detecting the user's preferred git protocol.
603var (
604 ghProtocolOnce sync.Once
605 ghProtocolSSH bool
606)
607
608// DetectGHProtocol runs "gh config get git_protocol" and returns true if SSH.
609var detectGHProtocol = defaultDetectGHProtocol
610
611// defaultDetectGHProtocol is the real implementation.
612func defaultDetectGHProtocol() bool {
613 out, err := exec.Command("gh", "config", "get", "git_protocol").Output()
614 if err != nil {
615 return false
616 }
617 return strings.TrimSpace(string(out)) == "ssh"
618}
619
620// SetDetectGHProtocol overrides the protocol detection function (for testing).
621func SetDetectGHProtocol(fn func() bool) {
622 detectGHProtocol = fn
623}
624
625// ResetDetectGHProtocol restores the default protocol detection function.
626func ResetDetectGHProtocol() {
627 detectGHProtocol = defaultDetectGHProtocol
628}
629
630// useSSHProtocol returns true if the user has configured gh to use SSH.
631func useSSHProtocol() bool {
632 ghProtocolOnce.Do(func() {
633 ghProtocolSSH = detectGHProtocol()
634 })
635 return ghProtocolSSH
636}
637
638// CloneURL returns the git clone URL for a GitHub repo, respecting the user's
639// configured git protocol (via gh config).
640func CloneURL(owner, repo string) string {
641 if useSSHProtocol() {
642 return fmt.Sprintf("git@github.com:%s/%s.git", owner, repo)
643 }
644 return fmt.Sprintf("https://github.com/%s/%s.git", owner, repo)
645}
646
647// githubURLPrefixes are the URL forms that name a repository on github.com.
648var githubURLPrefixes = []string{
649 "https://github.com/",
650 "http://github.com/",
651 "git@github.com:",
652 "ssh://git@github.com/",
653}
654
655// cutGitHubPrefix strips a github.com URL prefix from ref, reporting whether
656// it had one.
657func cutGitHubPrefix(ref string) (string, bool) {
658 for _, p := range githubURLPrefixes {
659 if rest, ok := strings.CutPrefix(ref, p); ok {
660 return rest, true
661 }
662 }
663 return ref, false
664}
665
666// CleanGitHubRef strips GitHub URL prefixes, .git suffix, and trailing slashes
667// from a repo reference, returning the bare "owner/repo" or short name form.
668func CleanGitHubRef(ref string) string {
669 ref = strings.TrimSuffix(ref, ".git")
670 ref, _ = cutGitHubPrefix(ref)
671 return strings.TrimRight(ref, "/")
672}
673
674// IsGitHubRemote reports whether remote, a git remote URL, names an owner/repo
675// on github.com (https, scp-style ssh, or ssh:// form). A bare "owner/repo"
676// reference is not a remote URL and reports false.
677func IsGitHubRemote(remote string) bool {
678 if _, ok := cutGitHubPrefix(remote); !ok {
679 return false
680 }
681 _, _, err := SplitRepoRef(remote)
682 return err == nil
683}
684
685// ParseRepoRef parses a GitHub repo reference into owner, repo name, and clone URL.
686// Accepts: "owner/repo", "https://github.com/owner/repo[.git]", "git@github.com:owner/repo[.git]",
687// "ssh://git@github.com/owner/repo[.git]"
688func ParseRepoRef(ref string) (owner, repo, cloneURL string, err error) {
689 owner, repo, err = SplitRepoRef(ref)
690 if err != nil {
691 return "", "", "", err
692 }
693 return owner, repo, CloneURL(owner, repo), nil
694}
695
696// SplitRepoRef is ParseRepoRef without the clone URL, which may shell out to gh.
697func SplitRepoRef(ref string) (owner, repo string, err error) {
698 ref = CleanGitHubRef(ref)
699 parts := strings.SplitN(ref, "/", 3)
700 if len(parts) < 2 || parts[0] == "" || parts[1] == "" {
701 return "", "", fmt.Errorf("invalid repo reference %q: expected owner/repo", ref)
702 }
703
704 owner = parts[0]
705 repo = parts[1]
706 if strings.Contains(owner, "..") || strings.Contains(repo, "..") {
707 return "", "", fmt.Errorf("invalid repo reference %q: path traversal not allowed", ref)
708 }
709 return owner, repo, nil
710}
711
712// EnsureClone clones a repo to destDir if it doesn't already exist.
713// If it already exists, fetches the latest from origin.
714func EnsureClone(ctx context.Context, cloneURL, destDir string) error {
715 if _, err := os.Stat(filepath.Join(destDir, ".git")); err == nil {
716 _, fetchErr := runGitNetwork(ctx, destDir, "fetch", "origin", "--prune", "--tags", "--quiet")
717 return fetchErr
718 }
719
720 if err := os.MkdirAll(filepath.Dir(destDir), 0o755); err != nil {
721 return fmt.Errorf("creating parent dir: %w", err)
722 }
723 _, err := runGitNetwork(ctx, "", "clone", cloneURL, destDir, "--quiet")
724 return err
725}
726
727// PushDataRef pushes the data ref's tip to origin and returns the commit it
728// pushed. It names the tip by its hash, so the caller knows which history
729// origin took even when the ref moves during the push. A failed push returns
730// a *PushError.
731func PushDataRef(ctx context.Context, repoDir, dataRef string) (string, error) {
732 tip := RefCommit(ctx, repoDir, dataRef)
733 if tip == "" {
734 return "", fmt.Errorf("%s resolves to no commit", dataRef)
735 }
736 ctx, cancel := ensureTimeout(ctx, networkTimeout)
737 defer cancel()
738
739 cmd := exec.CommandContext(ctx, "git", "push", "--porcelain", "--quiet", "origin", tip+":"+dataRef)
740 cmd.Dir = repoDir
741 var stdout, stderr bytes.Buffer
742 cmd.Stdout = &stdout
743 cmd.Stderr = &stderr
744 if err := cmd.Run(); err != nil {
745 if ctx.Err() == context.DeadlineExceeded {
746 return "", &PushError{Class: PushNetwork}
747 }
748 return "", ParsePushError(dataRef, stdout.String(), stderr.String())
749 }
750 return tip, nil
751}
752
753// Provenance names the run that makes a worktree's commits and the change
754// they belong to. Its trailers label commits for finding and auditing; they
755// grant nothing.
756type Provenance struct {
757 RunID string // Klaus-Run trailer; empty for none
758 ChangeID string // Change-Id trailer; empty for none
759}
760
761// Trailers returns the provenance trailer lines for the fields that are set,
762// Change-Id first, or "" when neither is.
763func (p Provenance) Trailers() string {
764 var lines []string
765 if p.ChangeID != "" {
766 lines = append(lines, "Change-Id: "+p.ChangeID)
767 }
768 if p.RunID != "" {
769 lines = append(lines, "Klaus-Run: "+p.RunID)
770 }
771 return strings.Join(lines, "\n")
772}
773
774// hookConfigName is the file beside klaus's hooks that holds their data, in
775// git config format: the trailer values, the formatter's command line and the
776// hooks directory they chain to. The scripts read it with git config and never
777// have a value spliced into their code.
778const hookConfigName = "klaus.config"
779
780// commitMsgHookScript is klaus's commit-msg hook. It strips Co-Authored-By
781// trailers referencing Claude or Anthropic and removes AI attribution lines
782// (human co-author lines are kept), adds the provenance trailers named in
783// klaus.config, then runs the commit-msg hook git would otherwise have run.
784// A Change-Id already on the message is kept; a Klaus-Run is added unless
785// that same run is already listed, so an amend by a later run lists both.
786//
787// A message that is empty, or made only of lines starting with #, gets no
788// trailers. Git keeps # lines for git commit -m but strips them from a message
789// written in the editor, and a hook cannot tell which cleanup will apply.
790// Treating such a message as empty keeps an empty editor message aborting the
791// commit; stamping it would turn that abort into a commit of trailers alone.
792const commitMsgHookScript = `#!/bin/sh
793# Installed by klaus: strips Claude/Anthropic attribution, adds provenance
794# trailers, then runs the repository's own commit-msg hook.
795sed -i.bak \
796 -e '/^Co-[Aa]uthored-[Bb]y:.*[Cc]laude/d' \
797 -e '/^Co-[Aa]uthored-[Bb]y:.*[Aa]nthropic/d' \
798 -e '/^[Gg]enerated.*[Cc]laude/d' \
799 -e '/^[Gg]enerated.*[Aa]nthropic/d' \
800 -e '/🤖.*[Cc]laude/d' \
801 "$1"
802rm -f "$1.bak"
803
804conf="$(dirname "$0")/` + hookConfigName + `"
805setting() { git config --file "$conf" --get "klaus.$1"; }
806
807# A message with no text aborts the commit; trailers alone must not save it.
808# A message made only of # lines counts as empty too, since an editor commit
809# strips them. Lines below a verbose commit's scissors line are the diff.
810if sed '/^. -\{24\} >8 -\{24\}$/,$d' "$1" | git stripspace --strip-comments | grep -q .; then
811 change=$(setting changeid)
812 if [ -n "$change" ]; then
813 git interpret-trailers --in-place --no-divider \
814 --if-exists doNothing --trailer "Change-Id: $change" "$1" || exit 1
815 fi
816 run=$(setting run)
817 if [ -n "$run" ]; then
818 git interpret-trailers --in-place --no-divider \
819 --if-exists addIfDifferent --trailer "Klaus-Run: $run" "$1" || exit 1
820 fi
821fi
822
823next=$(setting chaindir)
824if [ -n "$next" ] && [ -x "$next/commit-msg" ]; then
825 exec "$next/commit-msg" "$@"
826fi
827`
828
829// preCommitHookScript is klaus's pre-commit hook. It runs the formatter whose
830// command line klaus.config lists, one argument per klaus.format value, from
831// the worktree root, where git runs hooks. A formatter that fails fails the
832// commit, its output shown. Then it re-stages the paths whose index entries
833// differ from HEAD: the files staged for this commit, since the formatter
834// changes only the working tree. A file that also had changes not staged gets
835// its staged content back, so the commit never takes a change that wasn't
836// staged. Files not staged stay as the formatter left them. Last it runs the
837// pre-commit hook git would otherwise have run.
838const preCommitHookScript = `#!/bin/sh
839# Installed by klaus: formats the files staged for commit with the project's
840# formatter, then runs the repository's own pre-commit hook.
841conf="$(dirname "$0")/` + hookConfigName + `"
842setting() { git config --file "$conf" --get-all "klaus.$1"; }
843
844if [ -n "$(setting format)" ]; then
845 set --
846 while IFS= read -r arg; do set -- "$@" "$arg"; done <<EOF
847$(setting format)
848EOF
849 staged=$(git write-tree) || exit 1
850 unstaged=$(mktemp) || exit 1
851 git diff -z --name-only > "$unstaged" || { rm -f "$unstaged"; exit 1; }
852 if ! "$@"; then
853 rm -f "$unstaged"
854 echo "klaus: the formatter ($*) failed, so the commit was not made" >&2
855 exit 1
856 fi
857 git update-index --again || { rm -f "$unstaged"; exit 1; }
858 if [ -s "$unstaged" ]; then
859 xargs -0 git --literal-pathspecs reset -q "$staged" -- < "$unstaged" || { rm -f "$unstaged"; exit 1; }
860 fi
861 rm -f "$unstaged"
862fi
863
864next=$(setting chaindir)
865if [ -n "$next" ] && [ -x "$next/pre-commit" ]; then
866 exec "$next/pre-commit"
867fi
868`
869
870// InstallHooks installs klaus's commit-msg and pre-commit hooks in the linked
871// worktree at worktreeDir. The commit-msg hook strips Claude/Anthropic
872// attribution and adds prov's trailers (none when prov is zero). The
873// pre-commit hook runs format, a command line run from the worktree root (no
874// formatting when empty), and re-stages the files staged for the commit. Each
875// then runs the hook of its name the repository would otherwise run. It is
876// idempotent.
877//
878// The hooks live in the worktree's own git dir and are enabled with a
879// worktree-scoped core.hooksPath, so other worktrees and the main clone keep
880// their own hooks. That needs extensions.worktreeConfig, which this enables on
881// the repository once. A shared core.hooksPath that points into a worktree's
882// git dir, as earlier klaus versions left behind, is removed.
883func InstallHooks(ctx context.Context, worktreeDir string, prov Provenance, format []string) error {
884 for _, v := range []string{prov.RunID, prov.ChangeID} {
885 if strings.ContainsAny(v, " \t\r\n") {
886 return fmt.Errorf("provenance value %q must be a single token", v)
887 }
888 }
889 for _, arg := range format {
890 if arg == "" || strings.ContainsAny(arg, "\r\n") {
891 return fmt.Errorf("format argument %q must be a single, non-empty line", arg)
892 }
893 }
894 gitDir, err := absGitPath(ctx, worktreeDir, "--git-dir")
895 if err != nil {
896 return fmt.Errorf("finding git dir: %w", err)
897 }
898 commonDir, err := absGitPath(ctx, worktreeDir, "--git-common-dir")
899 if err != nil {
900 return fmt.Errorf("finding common git dir: %w", err)
901 }
902 // In the main worktree the git dir's hooks/ is the repository's own.
903 if samePath(gitDir, commonDir) {
904 return fmt.Errorf("%s is not a linked worktree", worktreeDir)
905 }
906
907 if err := removeLeakedHooksPath(ctx, worktreeDir, commonDir); err != nil {
908 return err
909 }
910 chain := chainedHooksDir(ctx, worktreeDir, commonDir)
911
912 hooksDir := filepath.Join(gitDir, "hooks")
913 if err := os.MkdirAll(hooksDir, 0o755); err != nil {
914 return fmt.Errorf("creating hooks dir: %w", err)
915 }
916 conf := filepath.Join(hooksDir, hookConfigName)
917 if err := os.Remove(conf); err != nil && !os.IsNotExist(err) {
918 return fmt.Errorf("replacing %s: %w", hookConfigName, err)
919 }
920 for _, kv := range [][2]string{{"run", prov.RunID}, {"changeid", prov.ChangeID}, {"chaindir", chain}} {
921 if kv[1] == "" {
922 continue
923 }
924 if _, err := runGit(ctx, worktreeDir, "config", "--file", conf, "klaus."+kv[0], kv[1]); err != nil {
925 return fmt.Errorf("writing %s: %w", hookConfigName, err)
926 }
927 }
928 for _, arg := range format {
929 if _, err := runGit(ctx, worktreeDir, "config", "--file", conf, "--add", "klaus.format", arg); err != nil {
930 return fmt.Errorf("writing %s: %w", hookConfigName, err)
931 }
932 }
933 for name, script := range map[string]string{"commit-msg": commitMsgHookScript, "pre-commit": preCommitHookScript} {
934 if err := os.WriteFile(filepath.Join(hooksDir, name), []byte(script), 0o755); err != nil {
935 return fmt.Errorf("writing %s hook: %w", name, err)
936 }
937 }
938
939 if err := enableWorktreeConfig(ctx, worktreeDir); err != nil {
940 return err
941 }
942 if _, err := runGit(ctx, worktreeDir, "config", "--worktree", "core.hooksPath", hooksDir); err != nil {
943 return fmt.Errorf("setting core.hooksPath: %w", err)
944 }
945 return nil
946}
947
948// absGitPath runs git rev-parse with flag (--git-dir, --git-common-dir) in dir
949// and returns the path it names, made absolute.
950func absGitPath(ctx context.Context, dir, flag string) (string, error) {
951 p, err := runGit(ctx, dir, "rev-parse", flag)
952 if err != nil {
953 return "", err
954 }
955 if !filepath.IsAbs(p) {
956 p = filepath.Join(dir, p)
957 }
958 return filepath.Clean(p), nil
959}
960
961// enableWorktreeConfig turns on extensions.worktreeConfig in the shared
962// repository config, so git config --worktree has a file of its own. Git
963// honours the extension in format-0 repositories too.
964func enableWorktreeConfig(ctx context.Context, dir string) error {
965 enabled := func() bool {
966 v, err := runGit(ctx, dir, "config", "--local", "--type=bool", "--get", "extensions.worktreeConfig")
967 return err == nil && v == "true"
968 }
969 if err := updateSharedConfig(ctx, dir, enabled, "config", "--local", "extensions.worktreeConfig", "true"); err != nil {
970 return fmt.Errorf("enabling extensions.worktreeConfig: %w", err)
971 }
972 return nil
973}
974
975// removeLeakedHooksPath removes a shared core.hooksPath that points inside the
976// common git dir's worktrees/. Earlier klaus versions wrote one there, which
977// made every worktree of the clone run the last-set-up worktree's hooks, and
978// none at all once that worktree was cleaned up. Any other value is the
979// repository's own choice and is kept.
980func removeLeakedHooksPath(ctx context.Context, dir, commonDir string) error {
981 leaked := func() []string {
982 out, err := runGit(ctx, dir, "config", "--local", "--get-all", "core.hooksPath")
983 if err != nil {
984 return nil // unset
985 }
986 var vs []string
987 for _, v := range strings.Split(out, "\n") {
988 if inWorktreesDir(v, commonDir) {
989 vs = append(vs, v)
990 }
991 }
992 return vs
993 }
994 for _, v := range leaked() {
995 gone := func() bool { return !slices.Contains(leaked(), v) }
996 if err := updateSharedConfig(ctx, dir, gone, "config", "--local", "--fixed-value", "--unset-all", "core.hooksPath", v); err != nil {
997 return fmt.Errorf("removing shared core.hooksPath %s: %w", v, err)
998 }
999 }
1000 return nil
1001}
1002
1003// configLockWait bounds how long updateSharedConfig keeps retrying while
1004// another process holds the shared config's lock.
1005var configLockWait = 2 * time.Second
1006
1007// updateSharedConfig runs git with args in dir to change the shared config,
1008// unless done reports the change is already there. git config fails at once
1009// when another process holds config.lock, as a concurrent launch does while
1010// it makes the same change, and that launch may not have renamed its new
1011// config into place yet. So a failed write is retried with a short backoff,
1012// re-checking done after each wait, and fails only once configLockWait has
1013// passed.
1014func updateSharedConfig(ctx context.Context, dir string, done func() bool, args ...string) error {
1015 deadline := time.Now().Add(configLockWait)
1016 wait := 10 * time.Millisecond
1017 for {
1018 if done() {
1019 return nil
1020 }
1021 _, err := runGit(ctx, dir, args...)
1022 if err == nil {
1023 return nil
1024 }
1025 remaining := time.Until(deadline)
1026 if remaining <= 0 {
1027 return err
1028 }
1029 select {
1030 case <-ctx.Done():
1031 return err
1032 case <-time.After(min(wait, remaining)):
1033 }
1034 wait = min(2*wait, 200*time.Millisecond)
1035 }
1036}
1037
1038// chainedHooksDir returns the hooks directory git would use in the worktree
1039// at dir without klaus's: the core.hooksPath set outside the worktree's own
1040// config, else the common git dir's hooks/. It returns "" when that path is
1041// inside a worktree's git dir: another run's klaus hooks.
1042func chainedHooksDir(ctx context.Context, dir, commonDir string) string {
1043 hooksDir := filepath.Join(commonDir, "hooks")
1044 // --show-scope lists values lowest precedence first; the last one wins.
1045 if out, err := runGit(ctx, dir, "config", "--show-scope", "--type=path", "--get-all", "core.hooksPath"); err == nil {
1046 for _, line := range strings.Split(out, "\n") {
1047 scope, v, ok := strings.Cut(line, "\t")
1048 if !ok || scope == "worktree" || scope == "command" {
1049 continue
1050 }
1051 hooksDir = v
1052 }
1053 }
1054 // A relative core.hooksPath is relative to the worktree root, where git
1055 // runs hooks.
1056 if !filepath.IsAbs(hooksDir) {
1057 hooksDir = filepath.Join(dir, hooksDir)
1058 }
1059 if inWorktreesDir(hooksDir, commonDir) {
1060 return ""
1061 }
1062 return hooksDir
1063}
1064
1065// inWorktreesDir reports whether the absolute path p is inside the common git
1066// dir's worktrees/, where linked worktrees keep their git dirs.
1067func inWorktreesDir(p, commonDir string) bool {
1068 if !filepath.IsAbs(p) {
1069 return false
1070 }
1071 roots := []string{commonDir}
1072 if real, err := filepath.EvalSymlinks(commonDir); err == nil {
1073 roots = append(roots, real)
1074 }
1075 for _, root := range roots {
1076 rel, err := filepath.Rel(filepath.Join(root, "worktrees"), p)
1077 if err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
1078 return true
1079 }
1080 }
1081 return false
1082}
1083
1084// samePath reports whether a and b name the same directory.
1085func samePath(a, b string) bool {
1086 if ra, err := filepath.EvalSymlinks(a); err == nil {
1087 a = ra
1088 }
1089 if rb, err := filepath.EvalSymlinks(b); err == nil {
1090 b = rb
1091 }
1092 return filepath.Clean(a) == filepath.Clean(b)
1093}
1094
1095// CommitChangeID returns the Change-Id trailer of commit rev in dir, or ""
1096// when it has none.
1097func CommitChangeID(ctx context.Context, dir, rev string) (string, error) {
1098 out, err := runGit(ctx, dir, "log", "-1", "--format=%(trailers:key=Change-Id,valueonly,separator=%x0A)", rev)
1099 if err != nil {
1100 return "", err
1101 }
1102 first, _, _ := strings.Cut(out, "\n")
1103 return strings.TrimSpace(first), nil
1104}
1105
1106// ensureTimeout returns a context with the given default timeout applied if
1107// the parent context has no deadline set.
1108func ensureTimeout(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
1109 if ctx == nil {
1110 ctx = context.Background()
1111 }
1112 if _, ok := ctx.Deadline(); ok {
1113 return ctx, func() {}
1114 }
1115 return context.WithTimeout(ctx, timeout)
1116}
1117
1118// runGit executes a local git command and returns trimmed stdout.
1119func runGit(ctx context.Context, dir string, args ...string) (string, error) {
1120 ctx, cancel := ensureTimeout(ctx, localTimeout)
1121 defer cancel()
1122
1123 cmd := exec.CommandContext(ctx, "git", args...)
1124 if dir != "" {
1125 cmd.Dir = dir
1126 }
1127 var stdout, stderr bytes.Buffer
1128 cmd.Stdout = &stdout
1129 cmd.Stderr = &stderr
1130 if err := cmd.Run(); err != nil {
1131 if ctx.Err() == context.DeadlineExceeded {
1132 return "", fmt.Errorf("git %s timed out after %s", args[0], localTimeout)
1133 }
1134 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, stderr.String())
1135 }
1136 return strings.TrimSpace(stdout.String()), nil
1137}
1138
1139// runGitNetwork executes a git command that talks to a remote and returns trimmed stdout.
1140func runGitNetwork(ctx context.Context, dir string, args ...string) (string, error) {
1141 ctx, cancel := ensureTimeout(ctx, networkTimeout)
1142 defer cancel()
1143
1144 cmd := exec.CommandContext(ctx, "git", args...)
1145 if dir != "" {
1146 cmd.Dir = dir
1147 }
1148 var stdout, stderr bytes.Buffer
1149 cmd.Stdout = &stdout
1150 cmd.Stderr = &stderr
1151 if err := cmd.Run(); err != nil {
1152 if ctx.Err() == context.DeadlineExceeded {
1153 return "", fmt.Errorf("git %s timed out after %s", args[0], networkTimeout)
1154 }
1155 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, stderr.String())
1156 }
1157 return strings.TrimSpace(stdout.String()), nil
1158}
1159
1160// runGitStdin executes a git command with stdin and returns trimmed stdout.
1161func runGitStdin(ctx context.Context, dir, stdin string, args ...string) (string, error) {
1162 ctx, cancel := ensureTimeout(ctx, localTimeout)
1163 defer cancel()
1164
1165 cmd := exec.CommandContext(ctx, "git", args...)
1166 if dir != "" {
1167 cmd.Dir = dir
1168 }
1169 cmd.Stdin = strings.NewReader(stdin)
1170 var stdout, stderr bytes.Buffer
1171 cmd.Stdout = &stdout
1172 cmd.Stderr = &stderr
1173 if err := cmd.Run(); err != nil {
1174 if ctx.Err() == context.DeadlineExceeded {
1175 return "", fmt.Errorf("git %s timed out after %s", args[0], localTimeout)
1176 }
1177 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, stderr.String())
1178 }
1179 return strings.TrimSpace(stdout.String()), nil
1180}
1181
1182// runGitEnv executes a git command with extra env vars (no stdout capture needed for some).
1183func runGitEnv(ctx context.Context, dir string, env map[string]string, args ...string) error {
1184 ctx, cancel := ensureTimeout(ctx, localTimeout)
1185 defer cancel()
1186
1187 cmd := exec.CommandContext(ctx, "git", args...)
1188 if dir != "" {
1189 cmd.Dir = dir
1190 }
1191 cmd.Env = os.Environ()
1192 for k, v := range env {
1193 cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
1194 }
1195 var stderr bytes.Buffer
1196 cmd.Stderr = &stderr
1197 if err := cmd.Run(); err != nil {
1198 if ctx.Err() == context.DeadlineExceeded {
1199 return fmt.Errorf("git %s timed out after %s", args[0], localTimeout)
1200 }
1201 return fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, stderr.String())
1202 }
1203 return nil
1204}
1205
1206// runGitOutput executes a git command with extra env vars and returns stdout.
1207func runGitOutput(ctx context.Context, dir string, env map[string]string, args ...string) (string, error) {
1208 ctx, cancel := ensureTimeout(ctx, localTimeout)
1209 defer cancel()
1210
1211 cmd := exec.CommandContext(ctx, "git", args...)
1212 if dir != "" {
1213 cmd.Dir = dir
1214 }
1215 cmd.Env = os.Environ()
1216 for k, v := range env {
1217 cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
1218 }
1219 var stdout, stderr bytes.Buffer
1220 cmd.Stdout = &stdout
1221 cmd.Stderr = &stderr
1222 if err := cmd.Run(); err != nil {
1223 if ctx.Err() == context.DeadlineExceeded {
1224 return "", fmt.Errorf("git %s timed out after %s", args[0], localTimeout)
1225 }
1226 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, stderr.String())
1227 }
1228 return strings.TrimSpace(stdout.String()), nil
1229}
1230
1231// LsRemote returns the commit ref points at in the remote repository repo (a
1232// URL or a path), read with git ls-remote, or "" when repo has no such ref.
1233// env is added to git's environment, e.g. to restrict GIT_ALLOW_PROTOCOL.
1234func LsRemote(ctx context.Context, repo, ref string, env ...string) (string, error) {
1235 ctx, cancel := ensureTimeout(ctx, networkTimeout)
1236 defer cancel()
1237 cmd := exec.CommandContext(ctx, "git", "ls-remote", "--", repo, ref)
1238 cmd.Env = append(os.Environ(), env...)
1239 var stdout, stderr bytes.Buffer
1240 cmd.Stdout, cmd.Stderr = &stdout, &stderr
1241 if err := cmd.Run(); err != nil {
1242 if ctx.Err() == context.DeadlineExceeded {
1243 return "", fmt.Errorf("git ls-remote timed out after %s", networkTimeout)
1244 }
1245 return "", fmt.Errorf("git ls-remote: %w: %s", err, strings.TrimSpace(stderr.String()))
1246 }
1247 for _, line := range strings.Split(strings.TrimSpace(stdout.String()), "\n") {
1248 // ls-remote matches patterns by their tail; keep the exact ref.
1249 if sha, name, ok := strings.Cut(line, "\t"); ok && name == ref {
1250 return sha, nil
1251 }
1252 }
1253 return "", nil
1254}
1255
1256// ShowFile returns the content of path at ref, as git show reads it from the
1257// object store, never from a working tree.
1258func ShowFile(ctx context.Context, repoDir, ref, path string) (string, error) {
1259 return runGit(ctx, repoDir, "show", ref+":"+path)
1260}