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