| 1 | package main |
| 2 | |
| 3 | import ( |
| 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. |
| 15 | func 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 | func 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. |
| 35 | func 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. |
| 49 | type 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. |
| 58 | const scratchPrefix = "valley-integrator-wt" |
| 59 | |
| 60 | // scratch makes one throwaway directory under the scratch root, which is |
| 61 | // whatever TMPDIR names. Under a unit that root is a sandboxed path, so a |
| 62 | // refusal here is a statement about the unit rather than about the work: the |
| 63 | // error names the operation, the path, and where the path came from, because |
| 64 | // that is the sentence that would have placed each of this module's |
| 65 | // deployment failures on sight instead of after an investigation. |
| 66 | func scratch(prefix string) (string, error) { |
| 67 | dir, err := os.MkdirTemp("", prefix) |
| 68 | if err != nil { |
| 69 | return "", fmt.Errorf("creating a scratch directory under %s, which TMPDIR names: %w", os.TempDir(), err) |
| 70 | } |
| 71 | return dir, nil |
| 72 | } |
| 73 | |
| 74 | func addWorktree(repo, rev string) (*worktree, error) { |
| 75 | // The directory is made here and handed to git as it stands. git |
| 76 | // worktree add takes an existing empty directory, so there is no reason |
| 77 | // to delete the one just made and let git create it again โ and a |
| 78 | // reason not to. Whoever creates the directory is who a refusal is |
| 79 | // reported by, and a refusal by git arrives as a complaint about |
| 80 | // leading directories of a .git file, which says nothing about the |
| 81 | // scratch root being unwritable. Creating it here keeps the first |
| 82 | // refusal in the sentence above, where it can say so. |
| 83 | dir, err := scratch(scratchPrefix) |
| 84 | if err != nil { |
| 85 | return nil, err |
| 86 | } |
| 87 | if _, err := git(repo, "worktree", "add", "--quiet", "--detach", dir, rev); err != nil { |
| 88 | _ = os.RemoveAll(dir) |
| 89 | return nil, err |
| 90 | } |
| 91 | return &worktree{repo: repo, dir: dir}, nil |
| 92 | } |
| 93 | |
| 94 | func (w *worktree) remove() { |
| 95 | if w == nil { |
| 96 | return |
| 97 | } |
| 98 | _, _ = gitTry(w.repo, "worktree", "remove", "--force", w.dir) |
| 99 | _ = os.RemoveAll(w.dir) |
| 100 | } |
| 101 | |
| 102 | // sweepScratch removes the scratch worktrees a previous run left attached to |
| 103 | // the repository. Every tick removes its own worktree on the way out, on the |
| 104 | // failure path as much as the success one, so a leak needs a run that died |
| 105 | // between the add and the remove โ a crash, a kill, a restart. The checkout |
| 106 | // and its administrative entry both survive that, and the scratch root is |
| 107 | // now a state directory that persists across restarts, so leaks would |
| 108 | // accumulate there without something to sweep them. |
| 109 | // |
| 110 | // A leak is found through the repository rather than the filesystem: a |
| 111 | // worktree is registered in the repository it is attached to, and a |
| 112 | // controller serves exactly one repository, so this cannot reach another |
| 113 | // controller's scratch even though they share a scratch root. Called once |
| 114 | // before the loop starts, when this process holds no worktree of its own, so |
| 115 | // everything carrying the prefix is a leak. |
| 116 | func sweepScratch(repo string) { |
| 117 | // First, and unconditionally. `git worktree add` keeps metadata under |
| 118 | // $GIT_DIR/worktrees, so a worktree whose directory is gone leaves an |
| 119 | // entry behind in the repository, and prune is the only thing that |
| 120 | // clears one. It runs before the listing rather than after it, so that |
| 121 | // a repository whose worktrees cannot be listed still gets its stale |
| 122 | // metadata cleared โ that is the repository most likely to have some. |
| 123 | _, _ = gitTry(repo, "worktree", "prune") |
| 124 | |
| 125 | out, ok := gitTry(repo, "worktree", "list", "--porcelain") |
| 126 | if !ok { |
| 127 | return |
| 128 | } |
| 129 | for _, line := range strings.Split(out, "\n") { |
| 130 | dir, found := strings.CutPrefix(strings.TrimSpace(line), "worktree ") |
| 131 | if !found || !strings.HasPrefix(filepath.Base(dir), scratchPrefix) { |
| 132 | continue |
| 133 | } |
| 134 | _, _ = gitTry(repo, "worktree", "remove", "--force", dir) |
| 135 | _ = os.RemoveAll(dir) |
| 136 | } |
| 137 | // Again, because the loop above removes directories git did not always |
| 138 | // get to remove for itself: a `worktree remove` that failed leaves the |
| 139 | // entry standing after RemoveAll has taken the checkout. |
| 140 | _, _ = gitTry(repo, "worktree", "prune") |
| 141 | } |
| 142 | |
| 143 | // mergeDelta applies a change's delta onto a tip without a working tree: |
| 144 | // a three-way merge of tip and head against the base the delta was authored |
| 145 | // against. It writes the resulting tree into the object store and returns |
| 146 | // its id, or the conflict. |
| 147 | // |
| 148 | // This is the whole of the first part of the commit rule. It is deliberately |
| 149 | // not `git rebase`: the serialized section at the commit point is a tree |
| 150 | // computation and a ref write, and a rebase would want a checkout, a |
| 151 | // sequencer state, and a cleanup path for every way it can be interrupted. |
| 152 | func mergeDelta(repo, base, tip, head string) (tree string, conflict string, err error) { |
| 153 | out, ok := gitTry(repo, "merge-tree", "--write-tree", "--merge-base="+base, tip, head) |
| 154 | if !ok { |
| 155 | return "", conflictMessage(out), nil |
| 156 | } |
| 157 | lines := strings.SplitN(out, "\n", 2) |
| 158 | tree = strings.TrimSpace(lines[0]) |
| 159 | if len(tree) < 40 { |
| 160 | return "", "", fmt.Errorf("merge-tree wrote no tree: %s", out) |
| 161 | } |
| 162 | return tree, "", nil |
| 163 | } |
| 164 | |
| 165 | // conflictMessage picks the sentence out of a conflicted merge-tree's |
| 166 | // report. That report opens with the tree oid and the conflicted entries |
| 167 | // and ends with the informational messages, which are the part naming what |
| 168 | // could not be merged. |
| 169 | func conflictMessage(out string) string { |
| 170 | var last string |
| 171 | for _, line := range strings.Split(out, "\n") { |
| 172 | line = strings.TrimSpace(line) |
| 173 | if strings.HasPrefix(line, "CONFLICT") { |
| 174 | return line |
| 175 | } |
| 176 | if line != "" { |
| 177 | last = line |
| 178 | } |
| 179 | } |
| 180 | return last |
| 181 | } |