gunk-dev/the-valley

git.go

sourcef1e680d2de7cmain's published tip history
7.4 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
27// gitInput runs a git command with stdin, and returns its stdout whole,
28// for the batch reads that answer many questions in one process.
29func gitInput(repo string, stdin []byte, args ...string) ([]byte, error) {
30 cmd := exec.Command("git", args...)
31 cmd.Dir = repo
32 cmd.Stdin = bytes.NewReader(stdin)
33 var out, errb bytes.Buffer
34 cmd.Stdout = &out
35 cmd.Stderr = &errb
36 if err := cmd.Run(); err != nil {
37 return nil, fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
38 }
39 return out.Bytes(), nil
40}
41
42func gitLine(repo string, args ...string) (string, error) {
43 out, err := git(repo, args...)
44 return strings.TrimSpace(out), err
45}
46
47// gitTry runs a git command that is allowed to fail, and reports both what
48// it wrote and whether it succeeded. Used where the failure is the answer:
49// a merge that conflicts, a compare-and-swap that lost.
50func gitTry(repo string, args ...string) (string, bool) {
51 cmd := exec.Command("git", args...)
52 cmd.Dir = repo
53 var out bytes.Buffer
54 cmd.Stdout = &out
55 cmd.Stderr = &out
56 err := cmd.Run()
57 return strings.TrimSpace(out.String()), err == nil
58}
59
60// worktree is a throwaway checkout attached to the served repository. The
61// integrator needs one to read the policy at the target tip and another to
62// evaluate check closures over the tree that would land; the served repo is
63// bare, and both of those want a tree on disk.
64type worktree struct {
65 repo string
66 dir string
67}
68
69// scratchPrefix names every directory addWorktree creates. It is what tells
70// a worktree of the integrator's own making from one somebody else attached
71// to the same repository by hand, which is the difference between a leak to
72// clean up and a checkout to leave alone.
73const scratchPrefix = "valley-integrator-wt"
74
75// scratch makes one throwaway directory under the scratch root, which is
76// whatever TMPDIR names. Under a unit that root is a sandboxed path, so a
77// refusal here is a statement about the unit rather than about the work: the
78// error names the operation, the path, and where the path came from, because
79// that is the sentence that would have placed each of this module's
80// deployment failures on sight instead of after an investigation.
81func scratch(prefix string) (string, error) {
82 dir, err := os.MkdirTemp("", prefix)
83 if err != nil {
84 return "", fmt.Errorf("creating a scratch directory under %s, which TMPDIR names: %w", os.TempDir(), err)
85 }
86 return dir, nil
87}
88
89func addWorktree(repo, rev string) (*worktree, error) {
90 // The directory is made here and handed to git as it stands. git
91 // worktree add takes an existing empty directory, so there is no reason
92 // to delete the one just made and let git create it again โ€” and a
93 // reason not to. Whoever creates the directory is who a refusal is
94 // reported by, and a refusal by git arrives as a complaint about
95 // leading directories of a .git file, which says nothing about the
96 // scratch root being unwritable. Creating it here keeps the first
97 // refusal in the sentence above, where it can say so.
98 dir, err := scratch(scratchPrefix)
99 if err != nil {
100 return nil, err
101 }
102 if _, err := git(repo, "worktree", "add", "--quiet", "--detach", dir, rev); err != nil {
103 _ = os.RemoveAll(dir)
104 return nil, err
105 }
106 return &worktree{repo: repo, dir: dir}, nil
107}
108
109func (w *worktree) remove() {
110 if w == nil {
111 return
112 }
113 _, _ = gitTry(w.repo, "worktree", "remove", "--force", w.dir)
114 _ = os.RemoveAll(w.dir)
115}
116
117// sweepScratch removes the scratch worktrees a previous run left attached to
118// the repository. Every tick removes its own worktree on the way out, on the
119// failure path as much as the success one, so a leak needs a run that died
120// between the add and the remove โ€” a crash, a kill, a restart. The checkout
121// and its administrative entry both survive that, and the scratch root is
122// now a state directory that persists across restarts, so leaks would
123// accumulate there without something to sweep them.
124//
125// A leak is found through the repository rather than the filesystem: a
126// worktree is registered in the repository it is attached to, and a
127// controller serves exactly one repository, so this cannot reach another
128// controller's scratch even though they share a scratch root. Called once
129// before the loop starts, when this process holds no worktree of its own, so
130// everything carrying the prefix is a leak.
131func sweepScratch(repo string) {
132 // First, and unconditionally. `git worktree add` keeps metadata under
133 // $GIT_DIR/worktrees, so a worktree whose directory is gone leaves an
134 // entry behind in the repository, and prune is the only thing that
135 // clears one. It runs before the listing rather than after it, so that
136 // a repository whose worktrees cannot be listed still gets its stale
137 // metadata cleared โ€” that is the repository most likely to have some.
138 _, _ = gitTry(repo, "worktree", "prune")
139
140 out, ok := gitTry(repo, "worktree", "list", "--porcelain")
141 if !ok {
142 return
143 }
144 for _, line := range strings.Split(out, "\n") {
145 dir, found := strings.CutPrefix(strings.TrimSpace(line), "worktree ")
146 if !found || !strings.HasPrefix(filepath.Base(dir), scratchPrefix) {
147 continue
148 }
149 _, _ = gitTry(repo, "worktree", "remove", "--force", dir)
150 _ = os.RemoveAll(dir)
151 }
152 // Again, because the loop above removes directories git did not always
153 // get to remove for itself: a `worktree remove` that failed leaves the
154 // entry standing after RemoveAll has taken the checkout.
155 _, _ = gitTry(repo, "worktree", "prune")
156}
157
158// mergeDelta applies a change's delta onto a tip without a working tree:
159// a three-way merge of tip and head against the base the delta was authored
160// against. It writes the resulting tree into the object store and returns
161// its id, or the conflict.
162//
163// This is the whole of the first part of the commit rule. It is deliberately
164// not `git rebase`: the serialized section at the commit point is a tree
165// computation and a ref write, and a rebase would want a checkout, a
166// sequencer state, and a cleanup path for every way it can be interrupted.
167func mergeDelta(repo, base, tip, head string) (tree string, conflict string, err error) {
168 out, ok := gitTry(repo, "merge-tree", "--write-tree", "--merge-base="+base, tip, head)
169 if !ok {
170 return "", conflictMessage(out), nil
171 }
172 lines := strings.SplitN(out, "\n", 2)
173 tree = strings.TrimSpace(lines[0])
174 if len(tree) < 40 {
175 return "", "", fmt.Errorf("merge-tree wrote no tree: %s", out)
176 }
177 return tree, "", nil
178}
179
180// conflictMessage picks the sentence out of a conflicted merge-tree's
181// report. That report opens with the tree oid and the conflicted entries
182// and ends with the informational messages, which are the part naming what
183// could not be merged.
184func conflictMessage(out string) string {
185 var last string
186 for _, line := range strings.Split(out, "\n") {
187 line = strings.TrimSpace(line)
188 if strings.HasPrefix(line, "CONFLICT") {
189 return line
190 }
191 if line != "" {
192 last = line
193 }
194 }
195 return last
196}