gunk-dev/the-valley

git.go

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