gunk-dev/the-valley

git.go

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