gunk-dev/the-valley

git.go

source601b054bc28emain's published tip history
43.0 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 // Update ref
511 _, err = runGit(ctx, repoDir, "update-ref", dataRef, initCommit)
512 return err
513}
514
515// SyncToDataRef commits files to the data ref using a temporary index.
516// files is a map of path-in-tree -> local-file-path.
517func SyncToDataRef(ctx context.Context, repoDir, dataRef, commitMsg string, files map[string]string) error {
518 if err := EnsureDataRef(ctx, repoDir, dataRef); err != nil {
519 return err
520 }
521
522 parentCommit, err := runGit(ctx, repoDir, "rev-parse", dataRef)
523 if err != nil {
524 return fmt.Errorf("resolving data ref: %w", err)
525 }
526
527 tmpIndex, err := os.CreateTemp("", "klaus-index-*")
528 if err != nil {
529 return fmt.Errorf("creating temp index: %w", err)
530 }
531 tmpIndexPath := tmpIndex.Name()
532 tmpIndex.Close()
533 defer os.Remove(tmpIndexPath)
534
535 // Read current tree into temp index
536 if err := runGitEnv(ctx, repoDir, map[string]string{"GIT_INDEX_FILE": tmpIndexPath}, "read-tree", dataRef); err != nil {
537 return fmt.Errorf("reading tree: %w", err)
538 }
539
540 // Add each file
541 for treePath, localPath := range files {
542 blob, err := runGit(ctx, repoDir, "hash-object", "-w", localPath)
543 if err != nil {
544 return fmt.Errorf("hashing %s: %w", localPath, err)
545 }
546 cacheInfo := fmt.Sprintf("100644,%s,%s", blob, treePath)
547 if err := runGitEnv(ctx, repoDir, map[string]string{"GIT_INDEX_FILE": tmpIndexPath}, "update-index", "--add", "--cacheinfo", cacheInfo); err != nil {
548 return fmt.Errorf("updating index for %s: %w", treePath, err)
549 }
550 }
551
552 // Write tree
553 newTree, err := runGitOutput(ctx, repoDir, map[string]string{"GIT_INDEX_FILE": tmpIndexPath}, "write-tree")
554 if err != nil {
555 return fmt.Errorf("writing tree: %w", err)
556 }
557
558 // Create commit
559 newCommit, err := runGitStdin(ctx, repoDir, commitMsg, "commit-tree", newTree, "-p", parentCommit)
560 if err != nil {
561 return fmt.Errorf("creating commit: %w", err)
562 }
563
564 // Update ref
565 _, err = runGit(ctx, repoDir, "update-ref", dataRef, newCommit)
566 return err
567}
568
569// ghProtocol caches the result of detecting the user's preferred git protocol.
570var (
571 ghProtocolOnce sync.Once
572 ghProtocolSSH bool
573)
574
575// DetectGHProtocol runs "gh config get git_protocol" and returns true if SSH.
576var detectGHProtocol = defaultDetectGHProtocol
577
578// defaultDetectGHProtocol is the real implementation.
579func defaultDetectGHProtocol() bool {
580 out, err := exec.Command("gh", "config", "get", "git_protocol").Output()
581 if err != nil {
582 return false
583 }
584 return strings.TrimSpace(string(out)) == "ssh"
585}
586
587// SetDetectGHProtocol overrides the protocol detection function (for testing).
588func SetDetectGHProtocol(fn func() bool) {
589 detectGHProtocol = fn
590}
591
592// ResetDetectGHProtocol restores the default protocol detection function.
593func ResetDetectGHProtocol() {
594 detectGHProtocol = defaultDetectGHProtocol
595}
596
597// useSSHProtocol returns true if the user has configured gh to use SSH.
598func useSSHProtocol() bool {
599 ghProtocolOnce.Do(func() {
600 ghProtocolSSH = detectGHProtocol()
601 })
602 return ghProtocolSSH
603}
604
605// CloneURL returns the git clone URL for a GitHub repo, respecting the user's
606// configured git protocol (via gh config).
607func CloneURL(owner, repo string) string {
608 if useSSHProtocol() {
609 return fmt.Sprintf("git@github.com:%s/%s.git", owner, repo)
610 }
611 return fmt.Sprintf("https://github.com/%s/%s.git", owner, repo)
612}
613
614// githubURLPrefixes are the URL forms that name a repository on github.com.
615var githubURLPrefixes = []string{
616 "https://github.com/",
617 "http://github.com/",
618 "git@github.com:",
619 "ssh://git@github.com/",
620}
621
622// cutGitHubPrefix strips a github.com URL prefix from ref, reporting whether
623// it had one.
624func cutGitHubPrefix(ref string) (string, bool) {
625 for _, p := range githubURLPrefixes {
626 if rest, ok := strings.CutPrefix(ref, p); ok {
627 return rest, true
628 }
629 }
630 return ref, false
631}
632
633// CleanGitHubRef strips GitHub URL prefixes, .git suffix, and trailing slashes
634// from a repo reference, returning the bare "owner/repo" or short name form.
635func CleanGitHubRef(ref string) string {
636 ref = strings.TrimSuffix(ref, ".git")
637 ref, _ = cutGitHubPrefix(ref)
638 return strings.TrimRight(ref, "/")
639}
640
641// IsGitHubRemote reports whether remote, a git remote URL, names an owner/repo
642// on github.com (https, scp-style ssh, or ssh:// form). A bare "owner/repo"
643// reference is not a remote URL and reports false.
644func IsGitHubRemote(remote string) bool {
645 if _, ok := cutGitHubPrefix(remote); !ok {
646 return false
647 }
648 _, _, err := SplitRepoRef(remote)
649 return err == nil
650}
651
652// ParseRepoRef parses a GitHub repo reference into owner, repo name, and clone URL.
653// Accepts: "owner/repo", "https://github.com/owner/repo[.git]", "git@github.com:owner/repo[.git]",
654// "ssh://git@github.com/owner/repo[.git]"
655func ParseRepoRef(ref string) (owner, repo, cloneURL string, err error) {
656 owner, repo, err = SplitRepoRef(ref)
657 if err != nil {
658 return "", "", "", err
659 }
660 return owner, repo, CloneURL(owner, repo), nil
661}
662
663// SplitRepoRef is ParseRepoRef without the clone URL, which may shell out to gh.
664func SplitRepoRef(ref string) (owner, repo string, err error) {
665 ref = CleanGitHubRef(ref)
666 parts := strings.SplitN(ref, "/", 3)
667 if len(parts) < 2 || parts[0] == "" || parts[1] == "" {
668 return "", "", fmt.Errorf("invalid repo reference %q: expected owner/repo", ref)
669 }
670
671 owner = parts[0]
672 repo = parts[1]
673 if strings.Contains(owner, "..") || strings.Contains(repo, "..") {
674 return "", "", fmt.Errorf("invalid repo reference %q: path traversal not allowed", ref)
675 }
676 return owner, repo, nil
677}
678
679// EnsureClone clones a repo to destDir if it doesn't already exist.
680// If it already exists, fetches the latest from origin.
681func EnsureClone(ctx context.Context, cloneURL, destDir string) error {
682 if _, err := os.Stat(filepath.Join(destDir, ".git")); err == nil {
683 _, fetchErr := runGitNetwork(ctx, destDir, "fetch", "origin", "--prune", "--tags", "--quiet")
684 return fetchErr
685 }
686
687 if err := os.MkdirAll(filepath.Dir(destDir), 0o755); err != nil {
688 return fmt.Errorf("creating parent dir: %w", err)
689 }
690 _, err := runGitNetwork(ctx, "", "clone", cloneURL, destDir, "--quiet")
691 return err
692}
693
694// PushDataRef pushes the data ref to origin.
695func PushDataRef(ctx context.Context, repoDir, dataRef string) error {
696 refspec := fmt.Sprintf("%s:%s", dataRef, dataRef)
697 _, err := runGitNetwork(ctx, repoDir, "push", "origin", refspec, "--quiet")
698 return err
699}
700
701// Provenance names the run that makes a worktree's commits and the change
702// they belong to. Its trailers label commits for finding and auditing; they
703// grant nothing.
704type Provenance struct {
705 RunID string // Klaus-Run trailer; empty for none
706 ChangeID string // Change-Id trailer; empty for none
707}
708
709// Trailers returns the provenance trailer lines for the fields that are set,
710// Change-Id first, or "" when neither is.
711func (p Provenance) Trailers() string {
712 var lines []string
713 if p.ChangeID != "" {
714 lines = append(lines, "Change-Id: "+p.ChangeID)
715 }
716 if p.RunID != "" {
717 lines = append(lines, "Klaus-Run: "+p.RunID)
718 }
719 return strings.Join(lines, "\n")
720}
721
722// hookConfigName is the file beside klaus's hooks that holds their data, in
723// git config format: the trailer values, the formatter's command line and the
724// hooks directory they chain to. The scripts read it with git config and never
725// have a value spliced into their code.
726const hookConfigName = "klaus.config"
727
728// commitMsgHookScript is klaus's commit-msg hook. It strips Co-Authored-By
729// trailers referencing Claude or Anthropic and removes AI attribution lines
730// (human co-author lines are kept), adds the provenance trailers named in
731// klaus.config, then runs the commit-msg hook git would otherwise have run.
732// A Change-Id already on the message is kept; a Klaus-Run is added unless
733// that same run is already listed, so an amend by a later run lists both.
734//
735// A message that is empty, or made only of lines starting with #, gets no
736// trailers. Git keeps # lines for git commit -m but strips them from a message
737// written in the editor, and a hook cannot tell which cleanup will apply.
738// Treating such a message as empty keeps an empty editor message aborting the
739// commit; stamping it would turn that abort into a commit of trailers alone.
740const commitMsgHookScript = `#!/bin/sh
741# Installed by klaus: strips Claude/Anthropic attribution, adds provenance
742# trailers, then runs the repository's own commit-msg hook.
743sed -i.bak \
744 -e '/^Co-[Aa]uthored-[Bb]y:.*[Cc]laude/d' \
745 -e '/^Co-[Aa]uthored-[Bb]y:.*[Aa]nthropic/d' \
746 -e '/^[Gg]enerated.*[Cc]laude/d' \
747 -e '/^[Gg]enerated.*[Aa]nthropic/d' \
748 -e '/🤖.*[Cc]laude/d' \
749 "$1"
750rm -f "$1.bak"
751
752conf="$(dirname "$0")/` + hookConfigName + `"
753setting() { git config --file "$conf" --get "klaus.$1"; }
754
755# A message with no text aborts the commit; trailers alone must not save it.
756# A message made only of # lines counts as empty too, since an editor commit
757# strips them. Lines below a verbose commit's scissors line are the diff.
758if sed '/^. -\{24\} >8 -\{24\}$/,$d' "$1" | git stripspace --strip-comments | grep -q .; then
759 change=$(setting changeid)
760 if [ -n "$change" ]; then
761 git interpret-trailers --in-place --no-divider \
762 --if-exists doNothing --trailer "Change-Id: $change" "$1" || exit 1
763 fi
764 run=$(setting run)
765 if [ -n "$run" ]; then
766 git interpret-trailers --in-place --no-divider \
767 --if-exists addIfDifferent --trailer "Klaus-Run: $run" "$1" || exit 1
768 fi
769fi
770
771next=$(setting chaindir)
772if [ -n "$next" ] && [ -x "$next/commit-msg" ]; then
773 exec "$next/commit-msg" "$@"
774fi
775`
776
777// preCommitHookScript is klaus's pre-commit hook. It runs the formatter whose
778// command line klaus.config lists, one argument per klaus.format value, from
779// the worktree root, where git runs hooks. A formatter that fails fails the
780// commit, its output shown. Then it re-stages the paths whose index entries
781// differ from HEAD: the files staged for this commit, since the formatter
782// changes only the working tree. A file that also had changes not staged gets
783// its staged content back, so the commit never takes a change that wasn't
784// staged. Files not staged stay as the formatter left them. Last it runs the
785// pre-commit hook git would otherwise have run.
786const preCommitHookScript = `#!/bin/sh
787# Installed by klaus: formats the files staged for commit with the project's
788# formatter, then runs the repository's own pre-commit hook.
789conf="$(dirname "$0")/` + hookConfigName + `"
790setting() { git config --file "$conf" --get-all "klaus.$1"; }
791
792if [ -n "$(setting format)" ]; then
793 set --
794 while IFS= read -r arg; do set -- "$@" "$arg"; done <<EOF
795$(setting format)
796EOF
797 staged=$(git write-tree) || exit 1
798 unstaged=$(mktemp) || exit 1
799 git diff -z --name-only > "$unstaged" || { rm -f "$unstaged"; exit 1; }
800 if ! "$@"; then
801 rm -f "$unstaged"
802 echo "klaus: the formatter ($*) failed, so the commit was not made" >&2
803 exit 1
804 fi
805 git update-index --again || { rm -f "$unstaged"; exit 1; }
806 if [ -s "$unstaged" ]; then
807 xargs -0 git --literal-pathspecs reset -q "$staged" -- < "$unstaged" || { rm -f "$unstaged"; exit 1; }
808 fi
809 rm -f "$unstaged"
810fi
811
812next=$(setting chaindir)
813if [ -n "$next" ] && [ -x "$next/pre-commit" ]; then
814 exec "$next/pre-commit"
815fi
816`
817
818// InstallHooks installs klaus's commit-msg and pre-commit hooks in the linked
819// worktree at worktreeDir. The commit-msg hook strips Claude/Anthropic
820// attribution and adds prov's trailers (none when prov is zero). The
821// pre-commit hook runs format, a command line run from the worktree root (no
822// formatting when empty), and re-stages the files staged for the commit. Each
823// then runs the hook of its name the repository would otherwise run. It is
824// idempotent.
825//
826// The hooks live in the worktree's own git dir and are enabled with a
827// worktree-scoped core.hooksPath, so other worktrees and the main clone keep
828// their own hooks. That needs extensions.worktreeConfig, which this enables on
829// the repository once. A shared core.hooksPath that points into a worktree's
830// git dir, as earlier klaus versions left behind, is removed.
831func InstallHooks(ctx context.Context, worktreeDir string, prov Provenance, format []string) error {
832 for _, v := range []string{prov.RunID, prov.ChangeID} {
833 if strings.ContainsAny(v, " \t\r\n") {
834 return fmt.Errorf("provenance value %q must be a single token", v)
835 }
836 }
837 for _, arg := range format {
838 if arg == "" || strings.ContainsAny(arg, "\r\n") {
839 return fmt.Errorf("format argument %q must be a single, non-empty line", arg)
840 }
841 }
842 gitDir, err := absGitPath(ctx, worktreeDir, "--git-dir")
843 if err != nil {
844 return fmt.Errorf("finding git dir: %w", err)
845 }
846 commonDir, err := absGitPath(ctx, worktreeDir, "--git-common-dir")
847 if err != nil {
848 return fmt.Errorf("finding common git dir: %w", err)
849 }
850 // In the main worktree the git dir's hooks/ is the repository's own.
851 if samePath(gitDir, commonDir) {
852 return fmt.Errorf("%s is not a linked worktree", worktreeDir)
853 }
854
855 if err := removeLeakedHooksPath(ctx, worktreeDir, commonDir); err != nil {
856 return err
857 }
858 chain := chainedHooksDir(ctx, worktreeDir, commonDir)
859
860 hooksDir := filepath.Join(gitDir, "hooks")
861 if err := os.MkdirAll(hooksDir, 0o755); err != nil {
862 return fmt.Errorf("creating hooks dir: %w", err)
863 }
864 conf := filepath.Join(hooksDir, hookConfigName)
865 if err := os.Remove(conf); err != nil && !os.IsNotExist(err) {
866 return fmt.Errorf("replacing %s: %w", hookConfigName, err)
867 }
868 for _, kv := range [][2]string{{"run", prov.RunID}, {"changeid", prov.ChangeID}, {"chaindir", chain}} {
869 if kv[1] == "" {
870 continue
871 }
872 if _, err := runGit(ctx, worktreeDir, "config", "--file", conf, "klaus."+kv[0], kv[1]); err != nil {
873 return fmt.Errorf("writing %s: %w", hookConfigName, err)
874 }
875 }
876 for _, arg := range format {
877 if _, err := runGit(ctx, worktreeDir, "config", "--file", conf, "--add", "klaus.format", arg); err != nil {
878 return fmt.Errorf("writing %s: %w", hookConfigName, err)
879 }
880 }
881 for name, script := range map[string]string{"commit-msg": commitMsgHookScript, "pre-commit": preCommitHookScript} {
882 if err := os.WriteFile(filepath.Join(hooksDir, name), []byte(script), 0o755); err != nil {
883 return fmt.Errorf("writing %s hook: %w", name, err)
884 }
885 }
886
887 if err := enableWorktreeConfig(ctx, worktreeDir); err != nil {
888 return err
889 }
890 if _, err := runGit(ctx, worktreeDir, "config", "--worktree", "core.hooksPath", hooksDir); err != nil {
891 return fmt.Errorf("setting core.hooksPath: %w", err)
892 }
893 return nil
894}
895
896// absGitPath runs git rev-parse with flag (--git-dir, --git-common-dir) in dir
897// and returns the path it names, made absolute.
898func absGitPath(ctx context.Context, dir, flag string) (string, error) {
899 p, err := runGit(ctx, dir, "rev-parse", flag)
900 if err != nil {
901 return "", err
902 }
903 if !filepath.IsAbs(p) {
904 p = filepath.Join(dir, p)
905 }
906 return filepath.Clean(p), nil
907}
908
909// enableWorktreeConfig turns on extensions.worktreeConfig in the shared
910// repository config, so git config --worktree has a file of its own. Git
911// honours the extension in format-0 repositories too.
912func enableWorktreeConfig(ctx context.Context, dir string) error {
913 enabled := func() bool {
914 v, err := runGit(ctx, dir, "config", "--local", "--type=bool", "--get", "extensions.worktreeConfig")
915 return err == nil && v == "true"
916 }
917 if err := updateSharedConfig(ctx, dir, enabled, "config", "--local", "extensions.worktreeConfig", "true"); err != nil {
918 return fmt.Errorf("enabling extensions.worktreeConfig: %w", err)
919 }
920 return nil
921}
922
923// removeLeakedHooksPath removes a shared core.hooksPath that points inside the
924// common git dir's worktrees/. Earlier klaus versions wrote one there, which
925// made every worktree of the clone run the last-set-up worktree's hooks, and
926// none at all once that worktree was cleaned up. Any other value is the
927// repository's own choice and is kept.
928func removeLeakedHooksPath(ctx context.Context, dir, commonDir string) error {
929 leaked := func() []string {
930 out, err := runGit(ctx, dir, "config", "--local", "--get-all", "core.hooksPath")
931 if err != nil {
932 return nil // unset
933 }
934 var vs []string
935 for _, v := range strings.Split(out, "\n") {
936 if inWorktreesDir(v, commonDir) {
937 vs = append(vs, v)
938 }
939 }
940 return vs
941 }
942 for _, v := range leaked() {
943 gone := func() bool { return !slices.Contains(leaked(), v) }
944 if err := updateSharedConfig(ctx, dir, gone, "config", "--local", "--fixed-value", "--unset-all", "core.hooksPath", v); err != nil {
945 return fmt.Errorf("removing shared core.hooksPath %s: %w", v, err)
946 }
947 }
948 return nil
949}
950
951// configLockWait bounds how long updateSharedConfig keeps retrying while
952// another process holds the shared config's lock.
953var configLockWait = 2 * time.Second
954
955// updateSharedConfig runs git with args in dir to change the shared config,
956// unless done reports the change is already there. git config fails at once
957// when another process holds config.lock, as a concurrent launch does while
958// it makes the same change, and that launch may not have renamed its new
959// config into place yet. So a failed write is retried with a short backoff,
960// re-checking done after each wait, and fails only once configLockWait has
961// passed.
962func updateSharedConfig(ctx context.Context, dir string, done func() bool, args ...string) error {
963 deadline := time.Now().Add(configLockWait)
964 wait := 10 * time.Millisecond
965 for {
966 if done() {
967 return nil
968 }
969 _, err := runGit(ctx, dir, args...)
970 if err == nil {
971 return nil
972 }
973 remaining := time.Until(deadline)
974 if remaining <= 0 {
975 return err
976 }
977 select {
978 case <-ctx.Done():
979 return err
980 case <-time.After(min(wait, remaining)):
981 }
982 wait = min(2*wait, 200*time.Millisecond)
983 }
984}
985
986// chainedHooksDir returns the hooks directory git would use in the worktree
987// at dir without klaus's: the core.hooksPath set outside the worktree's own
988// config, else the common git dir's hooks/. It returns "" when that path is
989// inside a worktree's git dir: another run's klaus hooks.
990func chainedHooksDir(ctx context.Context, dir, commonDir string) string {
991 hooksDir := filepath.Join(commonDir, "hooks")
992 // --show-scope lists values lowest precedence first; the last one wins.
993 if out, err := runGit(ctx, dir, "config", "--show-scope", "--type=path", "--get-all", "core.hooksPath"); err == nil {
994 for _, line := range strings.Split(out, "\n") {
995 scope, v, ok := strings.Cut(line, "\t")
996 if !ok || scope == "worktree" || scope == "command" {
997 continue
998 }
999 hooksDir = v
1000 }
1001 }
1002 // A relative core.hooksPath is relative to the worktree root, where git
1003 // runs hooks.
1004 if !filepath.IsAbs(hooksDir) {
1005 hooksDir = filepath.Join(dir, hooksDir)
1006 }
1007 if inWorktreesDir(hooksDir, commonDir) {
1008 return ""
1009 }
1010 return hooksDir
1011}
1012
1013// inWorktreesDir reports whether the absolute path p is inside the common git
1014// dir's worktrees/, where linked worktrees keep their git dirs.
1015func inWorktreesDir(p, commonDir string) bool {
1016 if !filepath.IsAbs(p) {
1017 return false
1018 }
1019 roots := []string{commonDir}
1020 if real, err := filepath.EvalSymlinks(commonDir); err == nil {
1021 roots = append(roots, real)
1022 }
1023 for _, root := range roots {
1024 rel, err := filepath.Rel(filepath.Join(root, "worktrees"), p)
1025 if err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
1026 return true
1027 }
1028 }
1029 return false
1030}
1031
1032// samePath reports whether a and b name the same directory.
1033func samePath(a, b string) bool {
1034 if ra, err := filepath.EvalSymlinks(a); err == nil {
1035 a = ra
1036 }
1037 if rb, err := filepath.EvalSymlinks(b); err == nil {
1038 b = rb
1039 }
1040 return filepath.Clean(a) == filepath.Clean(b)
1041}
1042
1043// CommitChangeID returns the Change-Id trailer of commit rev in dir, or ""
1044// when it has none.
1045func CommitChangeID(ctx context.Context, dir, rev string) (string, error) {
1046 out, err := runGit(ctx, dir, "log", "-1", "--format=%(trailers:key=Change-Id,valueonly,separator=%x0A)", rev)
1047 if err != nil {
1048 return "", err
1049 }
1050 first, _, _ := strings.Cut(out, "\n")
1051 return strings.TrimSpace(first), nil
1052}
1053
1054// ensureTimeout returns a context with the given default timeout applied if
1055// the parent context has no deadline set.
1056func ensureTimeout(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
1057 if ctx == nil {
1058 ctx = context.Background()
1059 }
1060 if _, ok := ctx.Deadline(); ok {
1061 return ctx, func() {}
1062 }
1063 return context.WithTimeout(ctx, timeout)
1064}
1065
1066// runGit executes a local git command and returns trimmed stdout.
1067func runGit(ctx context.Context, dir string, args ...string) (string, error) {
1068 ctx, cancel := ensureTimeout(ctx, localTimeout)
1069 defer cancel()
1070
1071 cmd := exec.CommandContext(ctx, "git", args...)
1072 if dir != "" {
1073 cmd.Dir = dir
1074 }
1075 var stdout, stderr bytes.Buffer
1076 cmd.Stdout = &stdout
1077 cmd.Stderr = &stderr
1078 if err := cmd.Run(); err != nil {
1079 if ctx.Err() == context.DeadlineExceeded {
1080 return "", fmt.Errorf("git %s timed out after %s", args[0], localTimeout)
1081 }
1082 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, stderr.String())
1083 }
1084 return strings.TrimSpace(stdout.String()), nil
1085}
1086
1087// runGitNetwork executes a git command that talks to a remote and returns trimmed stdout.
1088func runGitNetwork(ctx context.Context, dir string, args ...string) (string, error) {
1089 ctx, cancel := ensureTimeout(ctx, networkTimeout)
1090 defer cancel()
1091
1092 cmd := exec.CommandContext(ctx, "git", args...)
1093 if dir != "" {
1094 cmd.Dir = dir
1095 }
1096 var stdout, stderr bytes.Buffer
1097 cmd.Stdout = &stdout
1098 cmd.Stderr = &stderr
1099 if err := cmd.Run(); err != nil {
1100 if ctx.Err() == context.DeadlineExceeded {
1101 return "", fmt.Errorf("git %s timed out after %s", args[0], networkTimeout)
1102 }
1103 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, stderr.String())
1104 }
1105 return strings.TrimSpace(stdout.String()), nil
1106}
1107
1108// runGitStdin executes a git command with stdin and returns trimmed stdout.
1109func runGitStdin(ctx context.Context, dir, stdin string, args ...string) (string, error) {
1110 ctx, cancel := ensureTimeout(ctx, localTimeout)
1111 defer cancel()
1112
1113 cmd := exec.CommandContext(ctx, "git", args...)
1114 if dir != "" {
1115 cmd.Dir = dir
1116 }
1117 cmd.Stdin = strings.NewReader(stdin)
1118 var stdout, stderr bytes.Buffer
1119 cmd.Stdout = &stdout
1120 cmd.Stderr = &stderr
1121 if err := cmd.Run(); err != nil {
1122 if ctx.Err() == context.DeadlineExceeded {
1123 return "", fmt.Errorf("git %s timed out after %s", args[0], localTimeout)
1124 }
1125 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, stderr.String())
1126 }
1127 return strings.TrimSpace(stdout.String()), nil
1128}
1129
1130// runGitEnv executes a git command with extra env vars (no stdout capture needed for some).
1131func runGitEnv(ctx context.Context, dir string, env map[string]string, args ...string) error {
1132 ctx, cancel := ensureTimeout(ctx, localTimeout)
1133 defer cancel()
1134
1135 cmd := exec.CommandContext(ctx, "git", args...)
1136 if dir != "" {
1137 cmd.Dir = dir
1138 }
1139 cmd.Env = os.Environ()
1140 for k, v := range env {
1141 cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
1142 }
1143 var stderr bytes.Buffer
1144 cmd.Stderr = &stderr
1145 if err := cmd.Run(); err != nil {
1146 if ctx.Err() == context.DeadlineExceeded {
1147 return fmt.Errorf("git %s timed out after %s", args[0], localTimeout)
1148 }
1149 return fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, stderr.String())
1150 }
1151 return nil
1152}
1153
1154// runGitOutput executes a git command with extra env vars and returns stdout.
1155func runGitOutput(ctx context.Context, dir string, env map[string]string, args ...string) (string, error) {
1156 ctx, cancel := ensureTimeout(ctx, localTimeout)
1157 defer cancel()
1158
1159 cmd := exec.CommandContext(ctx, "git", args...)
1160 if dir != "" {
1161 cmd.Dir = dir
1162 }
1163 cmd.Env = os.Environ()
1164 for k, v := range env {
1165 cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
1166 }
1167 var stdout, stderr bytes.Buffer
1168 cmd.Stdout = &stdout
1169 cmd.Stderr = &stderr
1170 if err := cmd.Run(); err != nil {
1171 if ctx.Err() == context.DeadlineExceeded {
1172 return "", fmt.Errorf("git %s timed out after %s", args[0], localTimeout)
1173 }
1174 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, stderr.String())
1175 }
1176 return strings.TrimSpace(stdout.String()), nil
1177}
1178
1179// LsRemote returns the commit ref points at in the remote repository repo (a
1180// URL or a path), read with git ls-remote, or "" when repo has no such ref.
1181// env is added to git's environment, e.g. to restrict GIT_ALLOW_PROTOCOL.
1182func LsRemote(ctx context.Context, repo, ref string, env ...string) (string, error) {
1183 ctx, cancel := ensureTimeout(ctx, networkTimeout)
1184 defer cancel()
1185 cmd := exec.CommandContext(ctx, "git", "ls-remote", "--", repo, ref)
1186 cmd.Env = append(os.Environ(), env...)
1187 var stdout, stderr bytes.Buffer
1188 cmd.Stdout, cmd.Stderr = &stdout, &stderr
1189 if err := cmd.Run(); err != nil {
1190 if ctx.Err() == context.DeadlineExceeded {
1191 return "", fmt.Errorf("git ls-remote timed out after %s", networkTimeout)
1192 }
1193 return "", fmt.Errorf("git ls-remote: %w: %s", err, strings.TrimSpace(stderr.String()))
1194 }
1195 for _, line := range strings.Split(strings.TrimSpace(stdout.String()), "\n") {
1196 // ls-remote matches patterns by their tail; keep the exact ref.
1197 if sha, name, ok := strings.Cut(line, "\t"); ok && name == ref {
1198 return sha, nil
1199 }
1200 }
1201 return "", nil
1202}
1203
1204// ShowFile returns the content of path at ref, as git show reads it from the
1205// object store, never from a working tree.
1206func ShowFile(ctx context.Context, repoDir, ref, path string) (string, error) {
1207 return runGit(ctx, repoDir, "show", ref+":"+path)
1208}