gunk-dev/the-valley

record.go

source2eca5696ca57main's published tip history
14.2 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. The
5// push's outcome is read from git's porcelain report, so a push origin
6// refused is told apart from one whose outcome is unknown, as after a lost
7// connection or an answer origin never gave. The record commit is kept
8// either way: a caller that cannot tell whether origin took it can compare
9// origin's ref with it later.
10
11package rebase
12
13import (
14 "bytes"
15 "context"
16 "errors"
17 "fmt"
18 "strings"
19
20 "the-valley/change"
21)
22
23// WriteRecord writes a record commit holding r, with the parents given,
24// and returns its ID. Its tree holds record.json alone, as a plain file,
25// which is the only shape the hook accepts.
26func WriteRecord(ctx context.Context, g Git, r *change.Record, message string, parents ...string) (string, error) {
27 data, err := change.Encode(r)
28 if err != nil {
29 return "", err
30 }
31 if len(data) > change.MaxRecordBlob {
32 return "", fmt.Errorf("the change's record would be %d bytes, more than the %d a record may be", len(data), change.MaxRecordBlob)
33 }
34 blob, err := g.input(ctx, false, bytes.NewReader(data), "hash-object", "-w", "--stdin")
35 if err != nil {
36 return "", errors.New("could not write the record")
37 }
38 tree, err := g.input(ctx, false, strings.NewReader("100644 blob "+blob+"\trecord.json\n"), "mktree")
39 if err != nil {
40 return "", errors.New("could not write the record's tree")
41 }
42 args := []string{"commit-tree", tree}
43 for _, p := range parents {
44 args = append(args, "-p", p)
45 }
46 commit, err := g.input(ctx, false, strings.NewReader(message+"\n"), append(args, "-F", "-")...)
47 if err != nil {
48 return "", errors.New("could not write the record commit")
49 }
50 return commit, nil
51}
52
53// Push is what became of a ref a push asked origin to move.
54type Push int
55
56const (
57 Unpushed Push = iota // no push was made
58 Refused // origin refused it, and the ref did not move
59 Pushed // origin took it
60 Unknown // the push failed, and whether origin took it is not known
61)
62
63func (p Push) String() string {
64 switch p {
65 case Refused:
66 return "refused"
67 case Pushed:
68 return "pushed"
69 case Unknown:
70 return "unknown"
71 }
72 return "unpushed"
73}
74
75// RefusedRef is a ref origin refused, and git's reason, as its porcelain
76// report gives it.
77type RefusedRef struct {
78 Ref, Why string
79}
80
81// push runs one push to origin, with --porcelain and the arguments given,
82// and reads what became of it: Pushed when git exits zero, and otherwise
83// what readPush makes of git's report. No push is made under a context
84// already done.
85func push(ctx context.Context, g Git, args ...string) (Push, []RefusedRef) {
86 if ctx.Err() != nil {
87 return Unpushed, nil
88 }
89 cmd := g.command(ctx, append([]string{"push", "--porcelain"}, args...)...)
90 cmd.Stderr = g.Stderr
91 out, err := cmd.Output()
92 switch {
93 case finished(err) == nil:
94 return Pushed, nil
95 case cmd.Process == nil:
96 return Unpushed, nil
97 }
98 return readPush(string(out))
99}
100
101// readPush reads a failed push's porcelain report. git prints one line for
102// each ref: a flag, the refspec, and a summary with any reason after it in
103// parentheses, such as "!\trefs/x:refs/x\t[rejected] (stale info)" (see
104// print_ref_status in git's transport.c).
105//
106// The push is Refused, with each ref refused, only when git reports a ref
107// refused outright. That is "[rejected]", which git decides before it
108// sends anything, or "[remote rejected]", which is origin's own answer.
109// Any other line flagged "!" makes the push Unknown. git prints
110// "[remote failure] (remote failed to report status)" for a ref origin
111// sent no status for, and origin may have taken that ref before its
112// answer was lost. A flag this reader does not know, or a report that
113// names no ref refused, is Unknown too.
114func readPush(out string) (Push, []RefusedRef) {
115 var refused []RefusedRef
116 for _, line := range strings.Split(out, "\n") {
117 f := strings.SplitN(line, "\t", 3)
118 if len(f) != 3 || len(f[0]) != 1 {
119 continue
120 }
121 summary, _, _ := strings.Cut(f[2], " (")
122 switch {
123 case f[0] == "!" && (summary == "[rejected]" || summary == "[remote rejected]"):
124 _, to, _ := strings.Cut(f[1], ":")
125 refused = append(refused, RefusedRef{Ref: to, Why: f[2]})
126 case !strings.Contains(" +-*=", f[0]):
127 return Unknown, nil
128 }
129 }
130 if len(refused) > 0 {
131 return Refused, refused
132 }
133 return Unknown, nil
134}
135
136// RecordWrite is a record commit pushed to a change's record ref, and what
137// became of the push.
138type RecordWrite struct {
139 Ref string // the change's record ref
140 Old string // the record commit the push was leased on; "" for a record that did not exist
141 Commit string // the record commit written
142 Push Push
143 Why string // git's reason, when origin refused it
144}
145
146// PushRecord moves the change's record ref on origin from old to commit,
147// leased on old: the push is refused if the ref has moved since it was
148// read, and a record that did not exist must still not exist. The hook's
149// refusal reaches Stderr through git.
150func PushRecord(ctx context.Context, g Git, id, old, commit string) RecordWrite {
151 ref := change.Ref(Target, id)
152 w := RecordWrite{Ref: ref, Old: old, Commit: commit}
153 var refused []RefusedRef
154 w.Push, refused = push(ctx, g, "--quiet", "--force-with-lease="+ref+":"+old, "origin", commit+":"+ref)
155 if len(refused) > 0 {
156 w.Why = refused[0].Why
157 }
158 return w
159}
160
161// CheckRange refuses a change whose commits are not one line: the range
162// from the merge base of origin's main and the head, to the head, must hold
163// no merge commit, and the merge base must be one commit.
164func CheckRange(ctx context.Context, g Git, tip, head string) error {
165 out, err := g.output(ctx, true, "merge-base", "--all", tip, head)
166 bases := strings.Fields(out)
167 switch {
168 case err != nil && len(bases) == 0:
169 return fmt.Errorf("%s shares no history with origin's %s, so it is no change to it", short(head), Target)
170 case len(bases) > 1:
171 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)
172 }
173 merges, err := g.output(ctx, true, "rev-list", "--min-parents=2", bases[0]+".."+head)
174 if err != nil {
175 return fmt.Errorf("could not read the commits from origin's %s to %s", Target, short(head))
176 }
177 if merges != "" {
178 first := strings.Fields(merges)[0]
179 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))
180 }
181 return nil
182}
183
184// HeadIDs reads the change IDs a commit carries: the change-id header in
185// the commit object itself, never text in its message, and the Change-Id
186// trailer, as git interpret-trailers parses the message.
187func HeadIDs(ctx context.Context, g Git, head string) (header, trailer string, err error) {
188 raw, err := g.output(ctx, true, "cat-file", "commit", head)
189 if err != nil {
190 return "", "", errors.New("could not read the commit " + short(head))
191 }
192 headers, message, _ := strings.Cut(raw, "\n\n")
193 var found []string
194 for _, line := range strings.Split(headers, "\n") {
195 // A line opening with a space continues the header above it.
196 if v, ok := strings.CutPrefix(line, "change-id "); ok {
197 found = append(found, v)
198 }
199 }
200 switch {
201 case len(found) > 1:
202 return "", "", errors.New(short(head) + " has more than one change-id header")
203 case len(found) == 1 && !change.ValidID(found[0]):
204 return "", "", fmt.Errorf("%s has the change-id header %q, which is not a change ID", short(head), found[0])
205 case len(found) == 1:
206 header = found[0]
207 }
208
209 parsed, err := g.input(ctx, true, strings.NewReader(message), "interpret-trailers", "--parse")
210 if err != nil {
211 return "", "", errors.New("could not read the trailers of " + short(head))
212 }
213 found = nil
214 for _, line := range strings.Split(parsed, "\n") {
215 key, value, ok := strings.Cut(line, ":")
216 if ok && strings.EqualFold(strings.TrimSpace(key), "Change-Id") {
217 found = append(found, strings.TrimSpace(value))
218 }
219 }
220 switch {
221 case len(found) > 1:
222 return "", "", errors.New(short(head) + " has more than one Change-Id trailer")
223 case len(found) == 1 && !change.ValidID(found[0]):
224 return "", "", fmt.Errorf("%s has the Change-Id trailer %q, which is not a change ID", short(head), found[0])
225 case len(found) == 1:
226 trailer = found[0]
227 }
228 return header, trailer, nil
229}
230
231// CheckActive refuses to add a version unless the change is ready at an
232// active version whose head is ifActive, as `valley ready --if-active`
233// does. before is the record as read, or nil for none.
234func CheckActive(handle string, before *change.Record, ifActive string) error {
235 switch {
236 case before == nil:
237 return fmt.Errorf("--if-active %s: origin holds no record of %s, so no version is added", short(ifActive), handle)
238 case before.State != change.Ready:
239 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)
240 case HeadOf(before.ActiveVersion()) != ifActive:
241 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))
242 }
243 return nil
244}
245
246// NextRecord is before with v added as its next version, active and
247// ready, numbered after its last. It refuses a change ready at v's head
248// already, and a record that has as many versions, or has been updated as
249// many times, as a record may be.
250func NextRecord(handle string, before *change.Record, v change.Version) (*change.Record, error) {
251 active := before.ActiveVersion()
252 switch {
253 case active.Head == v.Head && before.State == change.Ready:
254 return nil, fmt.Errorf("%s v%d is at %s already; a new version needs a new head", handle, active.N, short(HeadOf(v)))
255 case active.Head != v.Head && len(before.Versions) >= change.MaxVersions:
256 return nil, fmt.Errorf("%s has %d versions, the most a change may have", handle, len(before.Versions))
257 case before.Seq >= change.MaxSeq:
258 return nil, fmt.Errorf("%s's record has been updated %d times, the most a record may be", handle, before.Seq)
259 }
260 after := *before
261 v.N = before.Last().N + 1
262 after.Versions = append(append([]change.Version(nil), before.Versions...), v)
263 after.Active, after.State, after.Seq = v.N, change.Ready, before.Seq+1
264 return &after, nil
265}
266
267// ReadyMessage is the message of a record commit that readies a version.
268func ReadyMessage(handle, id string, n int, head string) string {
269 return fmt.Sprintf("valley ready: %s v%d\n\nChange %s, version %d, at %s.", handle, n, id, n, head)
270}
271
272// Append is a version to add to a change's record, as
273// `valley ready --if-active <IfActive> --head <Head> --change <ID> <Branch>`
274// adds it.
275type Append struct {
276 ID string // the change
277 Branch string // the branch the version names; Head must be on it on origin
278 Head string // the head the version records, as a full object ID
279 IfActive string // the head the change must still be ready at
280 Principal string // the principal the push authenticates as, named as the version's uploader
281}
282
283// Appended is what became of an Append.
284type Appended struct {
285 Handle string // the change's handle on origin
286 Version int // the version added; 0 when none was
287 Write RecordWrite // the record commit and what became of its push; Write.Commit is "" when none was written
288 Err error // why no version was added; nil when one was
289}
290
291// AppendVersion adds a.Head to the change's record as its next version,
292// only while the change is still ready at a.IfActive. It reads the record
293// and pushes the new one leased on the record it read, so nothing can
294// unready the change or ready another version between that check and the
295// write.
296func AppendVersion(ctx context.Context, g Git, a Append) Appended {
297 ap := Appended{}
298 ap.Err = func() error {
299 switch {
300 case !change.ValidPrincipal(a.Principal):
301 return fmt.Errorf("%q is not a principal's name", a.Principal)
302 case !change.ValidBranch(a.Branch):
303 return errors.New("not a branch name: " + a.Branch)
304 case !change.ValidID(a.ID):
305 return fmt.Errorf("%q is not a change ID", a.ID)
306 case !IsObjectID(a.Head) || !IsObjectID(a.IfActive):
307 return 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")
308 }
309 o, err := ListOrigin(ctx, g, append([]string{"refs/heads/" + Target, "refs/heads/" + a.Branch}, RecordPatterns...)...)
310 if err != nil {
311 return err
312 }
313 tip, remote := o.Refs["refs/heads/"+Target], o.Refs["refs/heads/"+a.Branch]
314 if tip == "" {
315 return errors.New("origin has no " + Target + " branch, so a change has nothing to target")
316 }
317 if err := Fetch(ctx, g, tip, remote); err != nil {
318 return err
319 }
320 head, err := g.output(ctx, true, "rev-parse", "--verify", "--quiet", a.Head+"^{commit}")
321 if err != nil || remote == "" || !g.succeeds(ctx, true, "merge-base", "--is-ancestor", head, remote) {
322 return errors.New(a.Head + " is not on origin's " + a.Branch + "; push it there first")
323 }
324 if err := CheckRange(ctx, g, tip, head); err != nil {
325 return err
326 }
327 header, trailer, err := HeadIDs(ctx, g, head)
328 if err != nil {
329 return err
330 }
331 if header != "" && trailer != "" && header != trailer {
332 return fmt.Errorf("%s has the change-id header %s and the Change-Id trailer %s, and they must agree", short(head), header, trailer)
333 }
334 ref := change.Ref(Target, a.ID)
335 old := o.Refs[ref]
336 var before *change.Record
337 if old != "" {
338 if err := Fetch(ctx, g, old); err != nil {
339 return err
340 }
341 if before, err = ReadRecord(ctx, g, old); err != nil {
342 return err
343 }
344 }
345 ap.Handle = o.Handle(a.ID)
346 if err := CheckActive(ap.Handle, before, a.IfActive); err != nil {
347 return err
348 }
349 subject, err := g.output(ctx, true, "log", "-1", "--format=%s", head)
350 if err != nil {
351 return errors.New("could not read the subject of " + short(head))
352 }
353 after, err := NextRecord(ap.Handle, before, change.Version{
354 Head: change.HeadPrefix + head, Title: change.Title(subject), Branch: a.Branch, Uploader: a.Principal,
355 })
356 if err != nil {
357 return err
358 }
359 commit, err := WriteRecord(ctx, g, after, ReadyMessage(ap.Handle, a.ID, after.Active, head), old, head)
360 if err != nil {
361 return err
362 }
363 ap.Write = PushRecord(ctx, g, a.ID, old, commit)
364 if ap.Write.Push != Pushed {
365 return errors.New("origin did not take the record of " + a.ID)
366 }
367 ap.Version = after.Active
368 return nil
369 }()
370 return ap
371}