gunk-dev/the-valley

git.go

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