gunk-dev/the-valley

git.go

sourceb70056c25abamain's published tip history
5.9 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 // First, and unconditionally. `git worktree add` keeps metadata under
100 // $GIT_DIR/worktrees, so a worktree whose directory is gone leaves an
101 // entry behind in the repository, and prune is the only thing that
102 // clears one. It runs before the listing rather than after it, so that
103 // a repository whose worktrees cannot be listed still gets its stale
104 // metadata cleared — that is the repository most likely to have some.
105 _, _ = gitTry(repo, "worktree", "prune")
106
107 out, ok := gitTry(repo, "worktree", "list", "--porcelain")
108 if !ok {
109 return
110 }
111 for _, line := range strings.Split(out, "\n") {
112 dir, found := strings.CutPrefix(strings.TrimSpace(line), "worktree ")
113 if !found || !strings.HasPrefix(filepath.Base(dir), scratchPrefix) {
114 continue
115 }
116 _, _ = gitTry(repo, "worktree", "remove", "--force", dir)
117 _ = os.RemoveAll(dir)
118 }
119 // Again, because the loop above removes directories git did not always
120 // get to remove for itself: a `worktree remove` that failed leaves the
121 // entry standing after RemoveAll has taken the checkout.
122 _, _ = gitTry(repo, "worktree", "prune")
123}
124
125// mergeDelta applies a change's delta onto a tip without a working tree:
126// a three-way merge of tip and head against the base the delta was authored
127// against. It writes the resulting tree into the object store and returns
128// its id, or the conflict.
129//
130// This is the whole of the first part of the commit rule. It is deliberately
131// not `git rebase`: the serialized section at the commit point is a tree
132// computation and a ref write, and a rebase would want a checkout, a
133// sequencer state, and a cleanup path for every way it can be interrupted.
134func mergeDelta(repo, base, tip, head string) (tree string, conflict string, err error) {
135 out, ok := gitTry(repo, "merge-tree", "--write-tree", "--merge-base="+base, tip, head)
136 if !ok {
137 return "", conflictMessage(out), nil
138 }
139 lines := strings.SplitN(out, "\n", 2)
140 tree = strings.TrimSpace(lines[0])
141 if len(tree) < 40 {
142 return "", "", fmt.Errorf("merge-tree wrote no tree: %s", out)
143 }
144 return tree, "", nil
145}
146
147// conflictMessage picks the sentence out of a conflicted merge-tree's
148// report. That report opens with the tree oid and the conflicted entries
149// and ends with the informational messages, which are the part naming what
150// could not be merged.
151func conflictMessage(out string) string {
152 var last string
153 for _, line := range strings.Split(out, "\n") {
154 line = strings.TrimSpace(line)
155 if strings.HasPrefix(line, "CONFLICT") {
156 return line
157 }
158 if line != "" {
159 last = line
160 }
161 }
162 return last
163}