gunk-dev/the-valley

binding.go

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