gunk-dev/the-valley

record.go

sourcea9174ca371a5main's published tip history
23.0 KiB
1// Writing a change's record on origin, and adding a version to it.
2//
3// A record is written as a commit holding record.json, and pushed to the
4// change's record ref leased on the record commit that was read. Writing
5// the commit and pushing it are separate steps, so a caller can keep the
6// commit's ID and its lease before the push. The push's outcome is read
7// from git's porcelain report, so a push origin refused is told apart from
8// one whose outcome is unknown, as after a lost connection or an answer
9// origin never gave. The record commit is kept either way: a caller that
10// cannot tell whether origin took it can compare origin's ref with it
11// later.
12
13package rebase
14
15import (
16 "bytes"
17 "context"
18 "errors"
19 "fmt"
20 "strings"
21
22 "the-valley/change"
23)
24
25// WriteRecord writes a record commit holding r, with the parents given,
26// and returns its ID. Its tree holds record.json alone, as a plain file,
27// which is the only shape the hook accepts.
28func WriteRecord(ctx context.Context, g Git, r *change.Record, message string, parents ...string) (string, error) {
29 data, err := change.Encode(r)
30 if err != nil {
31 return "", err
32 }
33 if len(data) > change.MaxRecordBlob {
34 return "", fmt.Errorf("the change's record would be %d bytes, more than the %d a record may be", len(data), change.MaxRecordBlob)
35 }
36 return writeOneFile(ctx, g, "record", "record.json", data, message, parents...)
37}
38
39// writeOneFile writes a commit whose tree holds one plain file, with the
40// parents given, and returns its ID. what names the file in errors.
41func writeOneFile(ctx context.Context, g Git, what, name string, data []byte, message string, parents ...string) (string, error) {
42 blob, err := g.input(ctx, false, bytes.NewReader(data), "hash-object", "-w", "--stdin")
43 if err != nil {
44 return "", errors.New("could not write the " + what)
45 }
46 tree, err := g.input(ctx, false, strings.NewReader("100644 blob "+blob+"\t"+name+"\n"), "mktree")
47 if err != nil {
48 return "", errors.New("could not write the " + what + "'s tree")
49 }
50 args := []string{"commit-tree", tree}
51 for _, p := range parents {
52 args = append(args, "-p", p)
53 }
54 commit, err := g.input(ctx, false, strings.NewReader(message+"\n"), append(args, "-F", "-")...)
55 if err != nil {
56 return "", errors.New("could not write the " + what + " commit")
57 }
58 return commit, nil
59}
60
61// Push is what became of a ref a push asked origin to move.
62type Push int
63
64const (
65 Unpushed Push = iota // no push was made
66 Refused // origin refused it, and the ref did not move
67 Pushed // origin took it
68 Unknown // the push failed, and whether origin took it is not known
69)
70
71func (p Push) String() string {
72 switch p {
73 case Refused:
74 return "refused"
75 case Pushed:
76 return "pushed"
77 case Unknown:
78 return "unknown"
79 }
80 return "unpushed"
81}
82
83// RefusedRef is a ref origin refused, and git's reason, as its porcelain
84// report gives it.
85type RefusedRef struct {
86 Ref, Why string
87}
88
89// push runs one push to origin, with --porcelain and the arguments given,
90// and reads what became of it: Pushed when git exits zero, and otherwise
91// what readPush makes of git's report. No push is made under a context
92// already done.
93func push(ctx context.Context, g Git, args ...string) (Push, []RefusedRef) {
94 if ctx.Err() != nil {
95 return Unpushed, nil
96 }
97 cmd := g.command(ctx, append([]string{"push", "--porcelain"}, args...)...)
98 cmd.Stderr = g.Stderr
99 out, err := cmd.Output()
100 switch {
101 case finished(err) == nil:
102 return Pushed, nil
103 case cmd.Process == nil:
104 return Unpushed, nil
105 }
106 return readPush(string(out))
107}
108
109// readPush reads a failed push's porcelain report. git prints one line for
110// each ref: a flag, the refspec, and a summary with any reason after it in
111// parentheses, such as "!\trefs/x:refs/x\t[rejected] (stale info)" (see
112// print_ref_status in git's transport.c).
113//
114// The push is Refused, with each ref refused, only when git reports a ref
115// refused outright. That is "[rejected]", which git decides before it
116// sends anything, or "[remote rejected]", which is origin's own answer.
117// Any other line flagged "!" makes the push Unknown. git prints
118// "[remote failure] (remote failed to report status)" for a ref origin
119// sent no status for, and origin may have taken that ref before its
120// answer was lost. A flag this reader does not know, or a report that
121// names no ref refused, is Unknown too.
122func readPush(out string) (Push, []RefusedRef) {
123 var refused []RefusedRef
124 for _, line := range strings.Split(out, "\n") {
125 f := strings.SplitN(line, "\t", 3)
126 if len(f) != 3 || len(f[0]) != 1 {
127 continue
128 }
129 summary, _, _ := strings.Cut(f[2], " (")
130 switch {
131 case f[0] == "!" && (summary == "[rejected]" || summary == "[remote rejected]"):
132 _, to, _ := strings.Cut(f[1], ":")
133 refused = append(refused, RefusedRef{Ref: to, Why: f[2]})
134 case !strings.Contains(" +-*=", f[0]):
135 return Unknown, nil
136 }
137 }
138 if len(refused) > 0 {
139 return Refused, refused
140 }
141 return Unknown, nil
142}
143
144// RecordWrite is a record commit pushed to a change's record ref, or a
145// report commit pushed to its report ref, and what became of the push.
146type RecordWrite struct {
147 Ref string // the change's record ref, or its report ref
148 Old string // the commit the push was leased on; "" for a ref that did not exist
149 Commit string // the commit written
150 Push Push
151 Why string // git's reason, when origin refused it
152}
153
154// PushRecord moves the change's record ref on origin from old to commit,
155// leased on old: the push is refused if the ref has moved since it was
156// read, and a record that did not exist must still not exist. The hook's
157// refusal reaches Stderr through git.
158func PushRecord(ctx context.Context, g Git, id, old, commit string) RecordWrite {
159 return pushLeased(ctx, g, change.Ref(Target, id), old, commit)
160}
161
162// pushLeased moves ref on origin from old to commit, leased on old.
163func pushLeased(ctx context.Context, g Git, ref, old, commit string) RecordWrite {
164 w := RecordWrite{Ref: ref, Old: old, Commit: commit}
165 var refused []RefusedRef
166 w.Push, refused = push(ctx, g, "--quiet", "--force-with-lease="+ref+":"+old, "origin", commit+":"+ref)
167 if len(refused) > 0 {
168 w.Why = refused[0].Why
169 }
170 return w
171}
172
173// CheckRange refuses a change whose commits are not one line: the range
174// from the merge base of origin's main and the head, to the head, must hold
175// no merge commit, and the merge base must be one commit.
176func CheckRange(ctx context.Context, g Git, tip, head string) error {
177 out, err := g.output(ctx, true, "merge-base", "--all", tip, head)
178 bases := strings.Fields(out)
179 switch {
180 case err != nil && len(bases) == 0:
181 return fmt.Errorf("%s shares no history with origin's %s, so it is no change to it", short(head), Target)
182 case len(bases) > 1:
183 return fmt.Errorf("%s has %d merge bases with origin's %s, so the commits of the change are ambiguous", short(head), len(bases), Target)
184 }
185 merges, err := g.output(ctx, true, "rev-list", "--min-parents=2", bases[0]+".."+head)
186 if err != nil {
187 return fmt.Errorf("could not read the commits from origin's %s to %s", Target, short(head))
188 }
189 if merges != "" {
190 first := strings.Fields(merges)[0]
191 return fmt.Errorf("the commits from origin's %s to %s include the merge %s, and a change is a line of commits", Target, short(head), short(first))
192 }
193 return nil
194}
195
196// HeadIDs reads the change IDs a commit carries: the change-id header in
197// the commit object itself, never text in its message, and the Change-Id
198// trailer, as git interpret-trailers parses the message.
199func HeadIDs(ctx context.Context, g Git, head string) (header, trailer string, err error) {
200 raw, err := g.output(ctx, true, "cat-file", "commit", head)
201 if err != nil {
202 return "", "", errors.New("could not read the commit " + short(head))
203 }
204 headers, message, _ := strings.Cut(raw, "\n\n")
205 var found []string
206 for _, line := range strings.Split(headers, "\n") {
207 // A line opening with a space continues the header above it.
208 if v, ok := strings.CutPrefix(line, "change-id "); ok {
209 found = append(found, v)
210 }
211 }
212 switch {
213 case len(found) > 1:
214 return "", "", errors.New(short(head) + " has more than one change-id header")
215 case len(found) == 1 && !change.ValidID(found[0]):
216 return "", "", fmt.Errorf("%s has the change-id header %q, which is not a change ID", short(head), found[0])
217 case len(found) == 1:
218 header = found[0]
219 }
220
221 parsed, err := g.input(ctx, true, strings.NewReader(message), "interpret-trailers", "--parse")
222 if err != nil {
223 return "", "", errors.New("could not read the trailers of " + short(head))
224 }
225 found = nil
226 for _, line := range strings.Split(parsed, "\n") {
227 key, value, ok := strings.Cut(line, ":")
228 if ok && strings.EqualFold(strings.TrimSpace(key), "Change-Id") {
229 found = append(found, strings.TrimSpace(value))
230 }
231 }
232 switch {
233 case len(found) > 1:
234 return "", "", errors.New(short(head) + " has more than one Change-Id trailer")
235 case len(found) == 1 && !change.ValidID(found[0]):
236 return "", "", fmt.Errorf("%s has the Change-Id trailer %q, which is not a change ID", short(head), found[0])
237 case len(found) == 1:
238 trailer = found[0]
239 }
240 return header, trailer, nil
241}
242
243// CheckActive refuses to add a version unless the change is ready at an
244// active version whose head is ifActive, as `valley ready --if-active`
245// does. before is the record as read, or nil for none.
246func CheckActive(handle string, before *change.Record, ifActive string) error {
247 switch {
248 case before == nil:
249 return fmt.Errorf("--if-active %s: origin holds no record of %s, so no version is added", short(ifActive), handle)
250 case before.State != change.Ready:
251 return fmt.Errorf("%s is %s, not ready, so no version is added: --if-active adds one only while the change is ready", handle, before.State)
252 case HeadOf(before.ActiveVersion()) != ifActive:
253 return fmt.Errorf("%s v%d is at %s, not %s, so no version is added", handle, before.Active, short(HeadOf(before.ActiveVersion())), short(ifActive))
254 }
255 return nil
256}
257
258// NextRecord is before with v added as its next version, active and
259// ready, numbered after its last. It refuses a change ready at v's head
260// already, and a record that has as many versions, or has been updated as
261// many times, as a record may be.
262func NextRecord(handle string, before *change.Record, v change.Version) (*change.Record, error) {
263 active := before.ActiveVersion()
264 switch {
265 case active.Head == v.Head && before.State == change.Ready:
266 return nil, fmt.Errorf("%s v%d is at %s already; a new version needs a new head", handle, active.N, short(HeadOf(v)))
267 case active.Head != v.Head && len(before.Versions) >= change.MaxVersions:
268 return nil, fmt.Errorf("%s has %d versions, the most a change may have", handle, len(before.Versions))
269 case before.Seq >= change.MaxSeq:
270 return nil, fmt.Errorf("%s's record has been updated %d times, the most a record may be", handle, before.Seq)
271 }
272 after := *before
273 v.N = before.Last().N + 1
274 after.Versions = append(append([]change.Version(nil), before.Versions...), v)
275 after.Active, after.State, after.Seq = v.N, change.Ready, before.Seq+1
276 return &after, nil
277}
278
279// ReadyMessage is the message of a record commit that readies a version.
280func ReadyMessage(handle, id string, n int, head string) string {
281 return fmt.Sprintf("valley ready: %s v%d\n\nChange %s, version %d, at %s.", handle, n, id, n, head)
282}
283
284// Append is a version to add to a change's record, as
285// `valley ready --if-active <IfActive> --head <Head> --change <ID> <Branch>`
286// adds it.
287type Append struct {
288 ID string // the change
289 Branch string // the branch the version names; Head must be on it on origin
290 Head string // the head the version records, as a full object ID
291 IfActive string // the head the change must still be ready at
292 Principal string // the principal the push authenticates as, named as the version's uploader
293}
294
295// RestackAppend is a version the restack grant adds to a ready change: the
296// head a restack moved the change's branch to. The version names the
297// branch of the active version and keeps its title, as the hook requires
298// of a version the restack grant authorises (valleyhook/record.go). The
299// branch on origin must be at Head exactly.
300type RestackAppend struct {
301 ID string // the change
302 Head string // the head the restack moved the branch to, as a full object ID
303 IfActive string // the head the change must still be ready at: the one the restack rebased
304 Principal string // the principal the push authenticates as, named as the version's uploader
305}
306
307// Appended is what became of an Append.
308type Appended struct {
309 Handle string // the change's handle on origin
310 Version int // the version added; 0 when none was
311 Write RecordWrite // the record commit and what became of its push; Write.Commit is "" when none was written
312 Err error // why no version was added; nil when one was
313}
314
315// PendingVersion is a version written into a record commit and not yet
316// pushed. A caller that has to know after a crash whether origin took the
317// commit keeps the whole PendingVersion somewhere durable before it calls
318// Push, in the form MarshalJSON writes, which names the mode it was built
319// in (pending.go). Origin's record ref at Commit then means the push was
320// taken, and at Old that it was not. A PendingVersion restored from that
321// form pushes as the one kept would have: a restack's push still reads
322// the branch first.
323type PendingVersion struct {
324 ID string // the change
325 Handle string // its handle on origin
326 Ref string // its record ref
327 Old string // the record commit read, which the push is leased on
328 Commit string // the record commit written
329 Record *change.Record // the record Commit holds
330 Version int // the version it adds
331 Head string // the head that version records
332 Branch string // the branch that version names
333 restack bool // built by BuildRestack, so Push reads the branch first
334}
335
336// AppendVersion adds a.Head to the change's record as its next version,
337// only while the change is still ready at a.IfActive. It reads the record
338// and pushes the new one leased on the record it read, so nothing can
339// unready the change or ready another version between that check and the
340// write. It is BuildVersion and Push in one call.
341func AppendVersion(ctx context.Context, g Git, a Append) Appended {
342 p, err := buildVersion(ctx, g, a, false)
343 if err != nil {
344 return Appended{Handle: p.Handle, Err: err}
345 }
346 return p.Push(ctx, g)
347}
348
349// BuildVersion reads origin and writes the record commit that adds a.Head
350// as the change's next version, as AppendVersion does, and pushes nothing.
351// The version's title is a.Head's commit subject.
352func BuildVersion(ctx context.Context, g Git, a Append) (*PendingVersion, error) {
353 p, err := buildVersion(ctx, g, a, false)
354 if err != nil {
355 return nil, err
356 }
357 return p, nil
358}
359
360// BuildRestack reads origin and writes the record commit that adds a.Head
361// as the change's next version under the restack grant, and pushes
362// nothing. The change must be ready at a.IfActive. Its active version must
363// name a branch, and origin's branch must be at a.Head exactly: a head
364// further along it is the owner's work, which no restack records. The new
365// version keeps the active version's branch and title.
366//
367// Push reads the branch once more before it pushes. No read can be atomic
368// with the push, though: the push is leased on the record ref alone, and
369// git compares only the refs a push changes, so the branch can still move
370// between that read and the record's write.
371func BuildRestack(ctx context.Context, g Git, a RestackAppend) (*PendingVersion, error) {
372 p, err := buildVersion(ctx, g, Append{ID: a.ID, Head: a.Head, IfActive: a.IfActive, Principal: a.Principal}, true)
373 if err != nil {
374 return nil, err
375 }
376 return p, nil
377}
378
379// buildVersion is BuildVersion, and BuildRestack when restack is set. The
380// PendingVersion it returns with an error names the change, and its
381// handle once origin has been read.
382func buildVersion(ctx context.Context, g Git, a Append, restack bool) (*PendingVersion, error) {
383 p := &PendingVersion{ID: a.ID, restack: restack}
384 switch {
385 case !change.ValidPrincipal(a.Principal):
386 return p, fmt.Errorf("%q is not a principal's name", a.Principal)
387 case !restack && !change.ValidBranch(a.Branch):
388 return p, errors.New("not a branch name: " + a.Branch)
389 case !change.ValidID(a.ID):
390 return p, fmt.Errorf("%q is not a change ID", a.ID)
391 case !IsObjectID(a.Head) || !IsObjectID(a.IfActive):
392 return p, errors.New("a version is added at a head given as a full object ID, while the change is at another given the same way")
393 }
394 // A restack reads its branch from the record, so it lists every branch
395 // in the same read as the record.
396 branches := "refs/heads/" + a.Branch
397 if restack {
398 branches = "refs/heads/*"
399 }
400 o, err := ListOrigin(ctx, g, append([]string{"refs/heads/" + Target, branches}, RecordPatterns...)...)
401 if err != nil {
402 return p, err
403 }
404 tip := o.Refs["refs/heads/"+Target]
405 if tip == "" {
406 return p, errors.New("origin has no " + Target + " branch, so a change has nothing to target")
407 }
408 p.Ref = change.Ref(Target, a.ID)
409 p.Old = o.Refs[p.Ref]
410 var before *change.Record
411 if restack {
412 if before, err = readBefore(ctx, g, p.Old); err != nil {
413 return p, err
414 }
415 p.Handle = o.Handle(a.ID)
416 if err := CheckActive(p.Handle, before, a.IfActive); err != nil {
417 return p, err
418 }
419 active := before.ActiveVersion()
420 if active.Branch == "" {
421 return p, fmt.Errorf("%s v%d names no branch, so no restack moved one and no version is added", p.Handle, active.N)
422 }
423 a.Branch = active.Branch
424 if err := atHead(o, a.Branch, a.Head); err != nil {
425 return p, err
426 }
427 }
428 remote := o.Refs["refs/heads/"+a.Branch]
429 if err := Fetch(ctx, g, tip, remote); err != nil {
430 return p, err
431 }
432 head, err := g.output(ctx, true, "rev-parse", "--verify", "--quiet", a.Head+"^{commit}")
433 if err != nil || remote == "" || !g.succeeds(ctx, true, "merge-base", "--is-ancestor", head, remote) {
434 return p, errors.New(a.Head + " is not on origin's " + a.Branch + "; push it there first")
435 }
436 if err := checkHead(ctx, g, tip, head); err != nil {
437 return p, err
438 }
439 var title string
440 if restack {
441 title = before.ActiveVersion().Title
442 } else {
443 if before, err = readBefore(ctx, g, p.Old); err != nil {
444 return p, err
445 }
446 p.Handle = o.Handle(a.ID)
447 if err := CheckActive(p.Handle, before, a.IfActive); err != nil {
448 return p, err
449 }
450 subject, err := g.output(ctx, true, "log", "-1", "--format=%s", head)
451 if err != nil {
452 return p, errors.New("could not read the subject of " + short(head))
453 }
454 title = change.Title(subject)
455 }
456 return p, p.write(ctx, g, before, head, title, a.Branch, a.Principal)
457}
458
459// checkHead refuses a head no version may record: one whose commits from
460// the target are not one line, or whose change-id header and Change-Id
461// trailer disagree.
462func checkHead(ctx context.Context, g Git, tip, head string) error {
463 if err := CheckRange(ctx, g, tip, head); err != nil {
464 return err
465 }
466 header, trailer, err := HeadIDs(ctx, g, head)
467 if err != nil {
468 return err
469 }
470 if header != "" && trailer != "" && header != trailer {
471 return fmt.Errorf("%s has the change-id header %s and the Change-Id trailer %s, and they must agree", short(head), header, trailer)
472 }
473 return nil
474}
475
476// write writes the record commit that adds head to before as its next
477// version, with the title, branch and uploader given, on p.Old, and fills
478// in what p adds.
479func (p *PendingVersion) write(ctx context.Context, g Git, before *change.Record, head, title, branch, principal string) error {
480 after, err := NextRecord(p.Handle, before, change.Version{
481 Head: change.HeadPrefix + head, Title: title, Branch: branch, Uploader: principal,
482 })
483 if err != nil {
484 return err
485 }
486 commit, err := WriteRecord(ctx, g, after, ReadyMessage(p.Handle, p.ID, after.Active, head), p.Old, head)
487 if err != nil {
488 return err
489 }
490 p.Commit, p.Record, p.Version, p.Head, p.Branch = commit, after, after.Active, head, branch
491 return nil
492}
493
494// BuildAppends writes, for each change layer of a prepared family, lower
495// layers first, the record commit that adds the layer's prepared head as
496// the change's next version under the restack grant, and pushes nothing.
497// Each version keeps the active version's branch and title, and names
498// principal as its uploader, as BuildRestack's does.
499//
500// Each is written from the record the capture read, not from origin, so
501// all of them can be kept before the branches are pushed. Its push is
502// leased on the record commit the capture read, and, as a restack's
503// always does, reads origin's branch first and pushes nothing unless the
504// branch is at the prepared head.
505func (p *Prepared) BuildAppends(ctx context.Context, g Git, principal string) ([]*PendingVersion, error) {
506 if !change.ValidPrincipal(principal) {
507 return nil, fmt.Errorf("%q is not a principal's name", principal)
508 }
509 var built []*PendingVersion
510 for _, l := range p.Family.Layers {
511 if l.ID == "" {
512 continue
513 }
514 v := &PendingVersion{ID: l.ID, Handle: l.Name, Ref: l.Ref, Old: l.Commit, restack: true}
515 if err := CheckActive(l.Name, l.Record, l.Head); err != nil {
516 return nil, err
517 }
518 active := l.Record.ActiveVersion()
519 if active.Branch == "" {
520 return nil, fmt.Errorf("%s v%d names no branch, so no restack moved one and no version is added", l.Name, active.N)
521 }
522 head := p.Heads[l]
523 if err := checkHead(ctx, g, p.Family.Tip, head); err != nil {
524 return nil, err
525 }
526 if err := v.write(ctx, g, l.Record, head, active.Title, active.Branch, principal); err != nil {
527 return nil, err
528 }
529 built = append(built, v)
530 }
531 return built, nil
532}
533
534// Restack reports whether the version was built under the restack grant,
535// so its push reads origin's branch first.
536func (p *PendingVersion) Restack() bool { return p.restack }
537
538// readBefore reads the record a record commit on origin holds, or nil for
539// none.
540func readBefore(ctx context.Context, g Git, old string) (*change.Record, error) {
541 if old == "" {
542 return nil, nil
543 }
544 if err := Fetch(ctx, g, old); err != nil {
545 return nil, err
546 }
547 return ReadRecord(ctx, g, old)
548}
549
550// atHead refuses a branch that o does not list at head exactly.
551func atHead(o Origin, branch, head string) error {
552 switch at := o.Refs["refs/heads/"+branch]; {
553 case at == "":
554 return fmt.Errorf("origin has no %s, so it is not at %s and no version is added", branch, short(head))
555 case at != head:
556 return fmt.Errorf("origin's %s is at %s, not %s, so no version is added: a restack records only the head it moved the branch to", branch, short(at), short(head))
557 }
558 return nil
559}
560
561// Push pushes the record commit to the change's record ref, leased on
562// Old. A restack's push first reads origin's branch once more, and pushes
563// nothing unless the branch is still at Head (see BuildRestack).
564func (p *PendingVersion) Push(ctx context.Context, g Git) Appended {
565 ap := Appended{Handle: p.Handle, Write: RecordWrite{Ref: p.Ref, Old: p.Old, Commit: p.Commit}}
566 if p.restack {
567 o, err := ListOrigin(ctx, g, "refs/heads/"+p.Branch)
568 if err == nil {
569 err = atHead(o, p.Branch, p.Head)
570 }
571 if err != nil {
572 ap.Err = err
573 return ap
574 }
575 }
576 ap.Write = PushRecord(ctx, g, p.ID, p.Old, p.Commit)
577 if ap.Write.Push != Pushed {
578 ap.Err = errors.New("origin did not take the record of " + p.ID)
579 return ap
580 }
581 ap.Version = p.Version
582 return ap
583}