gunk-dev/the-valley

binding.go

source026c37612e61main's published tip history
12.3 KiB
1package review
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "math"
9 "os/exec"
10 "strconv"
11 "strings"
12
13 "the-valley/change"
14 "the-valley/delta"
15)
16
17// A review's binding says exactly what its reviewer read, so anyone
18// holding the objects can recompute it.
19//
20// The reviewer reads version n of a change: the head that the change
21// record commit names as version n. They compare it with the target as
22// it stood at a tip they name. What they read is the delta from the merge
23// base of that tip and the head to the head, as valley-delta-v1 gives it:
24// the files the version changes, whole. The binding records the record
25// commit, n, the head, the tip, the base and the delta's digest.
26//
27// The base is the one merge base of the tip and the head. When they have
28// none, or more than one, there is no single base to compare from, and so
29// no binding and no review: Bind refuses with ErrNoBase or
30// ErrAmbiguousBase, and Verify refuses a binding that names a base there.
31// The reviewer can review again against another tip, or once the author
32// rebases.
33
34// ErrNoBase is returned when the head and the target tip share no history.
35var ErrNoBase = errors.New("the head and the target tip share no history, so there is no base to compare from")
36
37// ErrAmbiguousBase is returned when the head and the target tip have more
38// than one merge base.
39var ErrAmbiguousBase = errors.New("the head and the target tip have more than one merge base, so the base to compare from is ambiguous")
40
41// recordLayout is a change record commit's layout, held to the bounds
42// every reader of a record holds it to (../change).
43var recordLayout = oneFile{
44 subject: "the change record", name: "record.json",
45 commit: change.MaxRecordCommit, tree: change.MaxRecordTree, blob: change.MaxRecordBlob,
46}
47
48// Bind makes the binding of a review of version n of a change, as the
49// change record commit record names it, judged against the target tip
50// tip. record and tip are full object IDs. It returns the change record
51// too, which names the change and the target the review is about.
52//
53// Reading the record and the delta is held to the budget: each to its
54// bytes and entries, and both to its deadline.
55func Bind(r Repo, record string, n int, tip string, b delta.Budget) (*change.Record, Binding, error) {
56 if b.Deadline.IsZero() {
57 return nil, Binding{}, errors.New("a binding is made within a deadline, and the budget sets none")
58 }
59 ctx, cancel := context.WithDeadline(context.Background(), b.Deadline)
60 defer cancel()
61 o, err := openObjects(ctx, r, b.Bytes)
62 if err != nil {
63 return nil, Binding{}, err
64 }
65 defer o.close()
66 rec, v, err := o.version(record, n)
67 if err != nil {
68 return nil, Binding{}, err
69 }
70 head := objectOf(v.Head)
71 if err := o.isCommit(tip, "the target tip"); err != nil {
72 return nil, Binding{}, err
73 }
74 if err := o.isCommit(head, "the head"); err != nil {
75 return nil, Binding{}, err
76 }
77 base, err := mergeBase(ctx, r, tip, head)
78 if err != nil {
79 return nil, Binding{}, err
80 }
81 d, err := delta.BetweenWithin(r, base, head, b)
82 if err != nil {
83 return nil, Binding{}, fmt.Errorf("the delta from %s to %s: %w", base, head, err)
84 }
85 digest := d.Digest()
86 digested()
87 if ctx.Err() != nil {
88 return nil, Binding{}, late(ctx)
89 }
90 return rec, Binding{
91 Record: change.HeadPrefix + record,
92 Version: n,
93 Head: v.Head,
94 TargetTip: change.HeadPrefix + tip,
95 Base: change.HeadPrefix + base,
96 Delta: digest,
97 }, nil
98}
99
100// digested is called once Bind or Verify has the delta's digest. Tests
101// make it slow, to pass the deadline there.
102var digested = func() {}
103
104// Against is what a binding is verified against, past the objects it
105// names: refs as they stand now, and what the verification may spend.
106type Against struct {
107 // RecordTip is the commit the change's record ref points at now.
108 // When it is set, the bound record commit must be the record of its
109 // own seq on that ref's history, so a review binds a record the change
110 // really has, and not one written to look like it.
111 RecordTip string
112 // TargetTip is the commit the target branch points at now. When it is
113 // set, the bound target tip must be on its history.
114 TargetTip string
115 // Budget bounds the verification. The delta's reading and the reading
116 // of the record and the notes' files are each held to its bytes, the
117 // delta's to its entries, and all of it to its deadline.
118 Budget delta.Budget
119}
120
121// Verify recomputes the binding of a review that judges a version, and
122// refuses it unless every part reproduces. The bound record commit is a
123// change record of the review's change and target, and names the bound
124// version with the bound head. The target tip is a commit, and the base is
125// the one merge base of it and the head. The delta from the base to the
126// head has the bound digest. Each note's path holds its blob on its side,
127// the base for before and the head for after, and a note's lines are
128// within that blob. And the refs Against names, when set, hold the record
129// and the tip on their histories.
130//
131// An error that wraps delta.ErrBudget says the binding could not be
132// recomputed within the budget, not that it is wrong.
133func Verify(r Repo, rec *Record, a Against) error {
134 if !rec.Judges() || rec.Binding == nil {
135 return errors.New("it is a withdrawal, and a withdrawal binds nothing to verify")
136 }
137 if a.Budget.Deadline.IsZero() {
138 return errors.New("a binding is verified within a deadline, and the budget sets none")
139 }
140 ctx, cancel := context.WithDeadline(context.Background(), a.Budget.Deadline)
141 defer cancel()
142 o, err := openObjects(ctx, r, a.Budget.Bytes)
143 if err != nil {
144 return err
145 }
146 defer o.close()
147 b := rec.Binding
148 record, head, tip, base := objectOf(b.Record), objectOf(b.Head), objectOf(b.TargetTip), objectOf(b.Base)
149
150 cr, v, err := o.version(record, b.Version)
151 switch {
152 case err != nil:
153 return fmt.Errorf("its binding.record: %w", err)
154 case cr.ChangeID != rec.ChangeID:
155 return fmt.Errorf("its binding.record is a record of the change %s, and the review is about %s", cr.ChangeID, rec.ChangeID)
156 case cr.Target != rec.Target:
157 return fmt.Errorf("its binding.record is a record on the target %s, and the review is about %s", cr.Target, rec.Target)
158 case v.Head != b.Head:
159 return fmt.Errorf("its binding.record names %s as version %d, and the binding names %s", v.Head, b.Version, b.Head)
160 }
161 if a.RecordTip != "" {
162 if err := o.onRecordHistory(ctx, r, a.RecordTip, record, cr.Seq); err != nil {
163 return err
164 }
165 }
166 if err := o.isCommit(tip, "its binding.target_tip"); err != nil {
167 return err
168 }
169 if a.TargetTip != "" {
170 on, err := isAncestor(ctx, r, tip, a.TargetTip)
171 switch {
172 case err != nil:
173 return err
174 case !on:
175 return fmt.Errorf("its binding.target_tip %s is not on the history of the target's tip, %s", tip, a.TargetTip)
176 }
177 }
178 found, err := mergeBase(ctx, r, tip, head)
179 switch {
180 case err != nil:
181 return fmt.Errorf("its binding names %s as the base: %w", b.Base, err)
182 case found != base:
183 return fmt.Errorf("its binding.base is %s, and the merge base of its target_tip and its head is %s", base, found)
184 }
185 d, err := delta.BetweenWithin(r, base, head, a.Budget)
186 if err != nil {
187 return fmt.Errorf("the delta from its base to its head: %w", err)
188 }
189 digest := d.Digest()
190 digested()
191 if digest != b.Delta {
192 return fmt.Errorf("its binding.delta is %s, and the delta from its base to its head has the digest %s", b.Delta, digest)
193 }
194 for i, n := range rec.Notes {
195 on := head
196 if n.Side == Before {
197 on = base
198 }
199 if err := o.anchor(on, n); err != nil {
200 return fmt.Errorf("its notes[%d] %w", i, err)
201 }
202 }
203 // Hashing the delta and counting a note's lines ask nothing of git, so
204 // a deadline that passes while they run is caught only here.
205 if ctx.Err() != nil {
206 return late(ctx)
207 }
208 return nil
209}
210
211// version reads the change record commit record and the version n it
212// names.
213func (o *objects) version(record string, n int) (*change.Record, change.Version, error) {
214 _, file, err := o.readOneFile(record, recordLayout)
215 if err != nil {
216 return nil, change.Version{}, err
217 }
218 cr, err := change.Parse(file)
219 if err != nil {
220 return nil, change.Version{}, fmt.Errorf("the change record %s does not read: %w", record, err)
221 }
222 if n < 1 || n > len(cr.Versions) {
223 return nil, change.Version{}, fmt.Errorf("the change record %s holds %d versions, and no version %d", record, len(cr.Versions), n)
224 }
225 return cr, cr.Versions[n-1], nil
226}
227
228// isCommit refuses an ID that names no commit.
229func (o *objects) isCommit(id, what string) error {
230 if !validObjectID(id) {
231 return fmt.Errorf("%s %q is not a full SHA-1 object ID", what, id)
232 }
233 _, kind, _, err := o.info(id)
234 switch {
235 case err != nil:
236 return fmt.Errorf("%s %s %w", what, id, err)
237 case kind != "commit":
238 return fmt.Errorf("%s %s is a %s, where a commit is expected", what, id, kind)
239 }
240 return nil
241}
242
243// onRecordHistory refuses a record commit that is not the record of its
244// seq on the history of the change's record ref, whose tip is tip. Every
245// record after the first has the record before it as its first parent,
246// and each seq is one more than the last, so the record of seq s is the
247// commit S-s first parents down from the tip's record of seq S.
248func (o *objects) onRecordHistory(ctx context.Context, r Repo, tip, record string, seq int) error {
249 _, file, err := o.readOneFile(tip, recordLayout)
250 if err != nil {
251 return fmt.Errorf("the change's record ref: %w", err)
252 }
253 now, err := change.Parse(file)
254 if err != nil {
255 return fmt.Errorf("the change's record ref points at a record that does not read: %w", err)
256 }
257 if seq > now.Seq {
258 return fmt.Errorf("its binding.record has the seq %d, and the change's record is at %d, so it is no record the change had", seq, now.Seq)
259 }
260 out, err := git(ctx, r, nil, "rev-list", "--first-parent", "--skip="+strconv.Itoa(now.Seq-seq), "--max-count=1", tip)
261 if err != nil {
262 return err
263 }
264 if found := strings.TrimSpace(string(out)); found != record {
265 return fmt.Errorf("its binding.record %s is not the change's record of seq %d, which is %s", record, seq, found)
266 }
267 return nil
268}
269
270// anchor refuses a note whose path does not hold its blob in the commit
271// given, or whose lines run past the blob's last line. A file a note names
272// has no bound of its own: only the budget's bytes bound reading it, so a
273// file too large for them is the budget's refusal, not the note's.
274func (o *objects) anchor(commit string, n Note) error {
275 id, kind, _, err := o.info(commit + ":" + n.Path)
276 switch {
277 case errors.Is(err, errMissing):
278 return fmt.Errorf("names %q on the %s side, where there is no such file", n.Path, n.Side)
279 case err != nil:
280 return fmt.Errorf("names %q on the %s side, which could not be looked up: %w", n.Path, n.Side, err)
281 case kind != "blob":
282 return fmt.Errorf("names %q on the %s side, where it is a %s, not a file", n.Path, n.Side, kind)
283 case change.HeadPrefix+id != n.Blob:
284 return fmt.Errorf("names %q on the %s side as %s, where it is %s", n.Path, n.Side, n.Blob, change.HeadPrefix+id)
285 case n.Lines == nil:
286 return nil
287 }
288 content, err := o.read(id, "blob", math.MaxInt64)
289 if err != nil {
290 return fmt.Errorf("names lines of %q, which %w", n.Path, err)
291 }
292 lines := bytes.Count(content, []byte{'\n'})
293 if len(content) > 0 && content[len(content)-1] != '\n' {
294 lines++
295 }
296 if n.Lines.End > lines {
297 return fmt.Errorf("names lines %d to %d of %q on the %s side, which has %d", n.Lines.Start, n.Lines.End, n.Path, n.Side, lines)
298 }
299 return nil
300}
301
302// mergeBase is the one merge base of the commits a and b. It refuses with
303// ErrNoBase when they have none and ErrAmbiguousBase when they have more.
304func mergeBase(ctx context.Context, r Repo, a, b string) (string, error) {
305 out, err := git(ctx, r, nil, "merge-base", "--all", a, b)
306 var exit *exec.ExitError
307 switch {
308 case err != nil && errors.As(err, &exit) && exit.ExitCode() == 1 && len(out) == 0:
309 return "", ErrNoBase
310 case err != nil:
311 return "", err
312 }
313 bases := strings.Fields(string(out))
314 switch {
315 case len(bases) == 0:
316 return "", ErrNoBase
317 case len(bases) > 1:
318 return "", fmt.Errorf("%w: %s", ErrAmbiguousBase, strings.Join(bases, ", "))
319 }
320 return bases[0], nil
321}
322
323// isAncestor reports whether the commit a is on the history of the commit
324// b, b itself included.
325func isAncestor(ctx context.Context, r Repo, a, b string) (bool, error) {
326 _, err := git(ctx, r, nil, "merge-base", "--is-ancestor", a, b)
327 var exit *exec.ExitError
328 switch {
329 case err == nil:
330 return true, nil
331 case errors.As(err, &exit) && exit.ExitCode() == 1:
332 return false, nil
333 }
334 return false, err
335}