gunk-dev/the-valley

git.go

source3705a182e12bmain's published tip history
5.3 KiB
1package main
2
3import (
4 "bytes"
5 "fmt"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "strings"
10)
11
12// git runs a git command in repo and returns its stdout. Stderr is folded
13// into the error, because a git failure that does not say what git said is
14// a failure the reader has to reproduce by hand.
15func git(repo string, args ...string) (string, error) {
16 cmd := exec.Command("git", args...)
17 cmd.Dir = repo
18 var out, errb bytes.Buffer
19 cmd.Stdout = &out
20 cmd.Stderr = &errb
21 if err := cmd.Run(); err != nil {
22 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
23 }
24 return out.String(), nil
25}
26
27func gitLine(repo string, args ...string) (string, error) {
28 out, err := git(repo, args...)
29 return strings.TrimSpace(out), err
30}
31
32// gitTry runs a git command that is allowed to fail, and reports both what
33// it wrote and whether it succeeded. Used where the failure is the answer:
34// a merge that conflicts, a compare-and-swap that lost.
35func gitTry(repo string, args ...string) (string, bool) {
36 cmd := exec.Command("git", args...)
37 cmd.Dir = repo
38 var out bytes.Buffer
39 cmd.Stdout = &out
40 cmd.Stderr = &out
41 err := cmd.Run()
42 return strings.TrimSpace(out.String()), err == nil
43}
44
45// worktree is a throwaway checkout attached to the served repository. The
46// integrator needs one to read the policy at the target tip and another to
47// evaluate check closures over the tree that would land; the served repo is
48// bare, and both of those want a tree on disk.
49type worktree struct {
50 repo string
51 dir string
52}
53
54// scratchPrefix names every directory addWorktree creates. It is what tells
55// a worktree of the integrator's own making from one somebody else attached
56// to the same repository by hand, which is the difference between a leak to
57// clean up and a checkout to leave alone.
58const scratchPrefix = "valley-integrator-wt"
59
60func addWorktree(repo, rev string) (*worktree, error) {
61 dir, err := os.MkdirTemp("", scratchPrefix)
62 if err != nil {
63 return nil, err
64 }
65 // git worktree add refuses an existing directory; the mkdtemp is only
66 // to reserve a name nothing else will take.
67 if err := os.RemoveAll(dir); err != nil {
68 return nil, err
69 }
70 if _, err := git(repo, "worktree", "add", "--quiet", "--detach", dir, rev); err != nil {
71 return nil, err
72 }
73 return &worktree{repo: repo, dir: dir}, nil
74}
75
76func (w *worktree) remove() {
77 if w == nil {
78 return
79 }
80 _, _ = gitTry(w.repo, "worktree", "remove", "--force", w.dir)
81 _ = os.RemoveAll(w.dir)
82}
83
84// sweepScratch removes the scratch worktrees a previous run left attached to
85// the repository. Every tick removes its own worktree on the way out, on the
86// failure path as much as the success one, so a leak needs a run that died
87// between the add and the remove — a crash, a kill, a restart. The checkout
88// and its administrative entry both survive that, and the scratch root is
89// now a state directory that persists across restarts, so leaks would
90// accumulate there without something to sweep them.
91//
92// A leak is found through the repository rather than the filesystem: a
93// worktree is registered in the repository it is attached to, and a
94// controller serves exactly one repository, so this cannot reach another
95// controller's scratch even though they share a scratch root. Called once
96// before the loop starts, when this process holds no worktree of its own, so
97// everything carrying the prefix is a leak.
98func sweepScratch(repo string) {
99 out, ok := gitTry(repo, "worktree", "list", "--porcelain")
100 if !ok {
101 return
102 }
103 for _, line := range strings.Split(out, "\n") {
104 dir, found := strings.CutPrefix(strings.TrimSpace(line), "worktree ")
105 if !found || !strings.HasPrefix(filepath.Base(dir), scratchPrefix) {
106 continue
107 }
108 _, _ = gitTry(repo, "worktree", "remove", "--force", dir)
109 _ = os.RemoveAll(dir)
110 }
111 // An entry whose checkout went away by some other route is still an
112 // entry, and only prune clears those.
113 _, _ = gitTry(repo, "worktree", "prune")
114}
115
116// mergeDelta applies a change's delta onto a tip without a working tree:
117// a three-way merge of tip and head against the base the delta was authored
118// against. It writes the resulting tree into the object store and returns
119// its id, or the conflict.
120//
121// This is the whole of the first part of the commit rule. It is deliberately
122// not `git rebase`: the serialized section at the commit point is a tree
123// computation and a ref write, and a rebase would want a checkout, a
124// sequencer state, and a cleanup path for every way it can be interrupted.
125func mergeDelta(repo, base, tip, head string) (tree string, conflict string, err error) {
126 out, ok := gitTry(repo, "merge-tree", "--write-tree", "--merge-base="+base, tip, head)
127 if !ok {
128 return "", conflictMessage(out), nil
129 }
130 lines := strings.SplitN(out, "\n", 2)
131 tree = strings.TrimSpace(lines[0])
132 if len(tree) < 40 {
133 return "", "", fmt.Errorf("merge-tree wrote no tree: %s", out)
134 }
135 return tree, "", nil
136}
137
138// conflictMessage picks the sentence out of a conflicted merge-tree's
139// report. That report opens with the tree oid and the conflicted entries
140// and ends with the informational messages, which are the part naming what
141// could not be merged.
142func conflictMessage(out string) string {
143 var last string
144 for _, line := range strings.Split(out, "\n") {
145 line = strings.TrimSpace(line)
146 if strings.HasPrefix(line, "CONFLICT") {
147 return line
148 }
149 if line != "" {
150 last = line
151 }
152 }
153 return last
154}