gunk-dev/the-valley

ready.go

source9067b6d5ac52main's published tip history
21.9 KiB
1// ready, unready and withdraw write a change's record on origin.
2//
3// `valley ready [--head <sha>] [--change <id>] [--stamp] [<branch>]` marks
4// a head of a branch ready, as a new version of its change. The branch is
5// the current one unless named. The head is --head when given, and
6// otherwise the branch's head on origin; either way it must be on origin
7// already. ready creates the change's record at v1, or adds the next
8// version to the record there, and pushes the record ref with a lease on
9// the value it read. A change that is a draft or withdrawn, readied at the
10// head of its active version, is ready again at that version, and gains no
11// new one.
12//
13// --if-active <sha> adds the version only while the change is ready at an
14// active version whose head is <sha>. The record ref is pushed leased on
15// the record that was read, so nothing can unready the change or ready
16// another version between that check and the write. rebase readies the
17// head it rebased this way.
18//
19// `valley unready <change>` makes a ready change a draft: a pause, which
20// voids nothing. `valley withdraw <change>` withdraws a ready change or a
21// draft, which voids everything outstanding on it. Either is undone by
22// readying the change again. The integrator lands no request at a head of
23// a change that is not ready, so either stops a pending request. Each says
24// when one is pending. The integrator deletes a withdrawn change's
25// requests on its next pass, and withdraw warns that a ready before then
26// leaves the request standing.
27//
28// The record names the principal that pushes it as the uploader of the
29// version it adds, and as the owner of a change it creates. The host
30// derives that principal from the ssh key a push authenticates with, and
31// nothing on this side can ask the host for it. So the principal is read
32// from git config valley.principal, and the hook refuses a record that
33// names any other.
34
35package main
36
37import (
38 "fmt"
39 "io"
40 "strings"
41
42 "the-valley/change"
43)
44
45const readyUsage = "usage: valley ready [--head <sha>] [--change <id>] [--if-active <sha>] [--stamp] [<branch>]"
46
47type readyArgs struct {
48 head, id, branch, ifActive string
49 stamp bool
50}
51
52func parseReadyArgs(args []string) (readyArgs, error) {
53 var a readyArgs
54 var rest []string
55 for i := 0; i < len(args); i++ {
56 arg := args[i]
57 value := func(flag string) (string, error) {
58 if v, ok := strings.CutPrefix(arg, flag+"="); ok {
59 return v, nil
60 }
61 if i+1 >= len(args) {
62 return "", failure(flag + " needs a value; " + readyUsage)
63 }
64 i++
65 return args[i], nil
66 }
67 var err error
68 switch {
69 case arg == "--head" || strings.HasPrefix(arg, "--head="):
70 a.head, err = value("--head")
71 case arg == "--change" || strings.HasPrefix(arg, "--change="):
72 a.id, err = value("--change")
73 case arg == "--if-active" || strings.HasPrefix(arg, "--if-active="):
74 a.ifActive, err = value("--if-active")
75 case arg == "--stamp":
76 a.stamp = true
77 case strings.HasPrefix(arg, "-"):
78 err = failure("unknown option " + arg + "; " + readyUsage)
79 default:
80 rest = append(rest, arg)
81 }
82 if err != nil {
83 return a, err
84 }
85 }
86 switch {
87 case len(rest) > 1:
88 return a, failure(readyUsage)
89 case len(rest) == 1:
90 a.branch = strings.TrimPrefix(rest[0], "origin/")
91 }
92 return a, nil
93}
94
95func runReady(g git, args []string, w io.Writer) error {
96 a, err := parseReadyArgs(args)
97 if err != nil {
98 return err
99 }
100 if !g.succeeds(true, "rev-parse", "--git-dir") {
101 return failure("not a git repository")
102 }
103 principal, err := g.output(true, "config", "valley.principal")
104 if err != nil || !change.ValidPrincipal(principal) {
105 return failure("ready records the principal your key pushes as, and git config valley.principal names none; set it with git config valley.principal <name>")
106 }
107 if a.branch == "" {
108 if a.branch, err = g.output(true, "symbolic-ref", "--quiet", "--short", "HEAD"); err != nil {
109 return failure("HEAD is on no branch; name one: " + readyUsage)
110 }
111 }
112 if !change.ValidBranch(a.branch) {
113 return failure("not a branch name: " + a.branch)
114 }
115 if a.stamp && a.head != "" {
116 return failure("--stamp amends the branch's own head, so it takes no --head")
117 }
118 if a.ifActive != "" && !isObjectID(a.ifActive) {
119 return failure("--if-active takes the full object ID of a version's head, and " + a.ifActive + " is not one")
120 }
121 if a.ifActive != "" && a.stamp {
122 return failure("--stamp starts a new change, so it takes no --if-active")
123 }
124
125 o, err := listOrigin(g, append([]string{"refs/heads/" + recordTarget, "refs/heads/" + a.branch}, recordPatterns...)...)
126 if err != nil {
127 return err
128 }
129 tip, remote := o.refs["refs/heads/"+recordTarget], o.refs["refs/heads/"+a.branch]
130 if tip == "" {
131 return failure("origin has no " + recordTarget + " branch, so a change has nothing to target")
132 }
133 if err := fetch(g, tip, remote); err != nil {
134 return err
135 }
136
137 var head string
138 switch {
139 case a.stamp:
140 if head, err = g.output(true, "rev-parse", "--verify", "--quiet", "refs/heads/"+a.branch+"^{commit}"); err != nil {
141 return failure("--stamp amends the head of your local " + a.branch + ", and there is no such branch")
142 }
143 case a.head != "":
144 if !isHexPrefix(a.head) {
145 return failure("--head takes a commit's object ID, and " + a.head + " is not one")
146 }
147 head, err = g.output(true, "rev-parse", "--verify", "--quiet", a.head+"^{commit}")
148 if err != nil || remote == "" || !g.succeeds(true, "merge-base", "--is-ancestor", head, remote) {
149 return failure(a.head + " is not on origin's " + a.branch + "; push it there first")
150 }
151 default:
152 if remote == "" {
153 return failure(a.branch + " is not on origin; push it there first")
154 }
155 head = remote
156 }
157 if err := checkRange(g, tip, head); err != nil {
158 return err
159 }
160 id, generated, err := changeID(g, head, a.id)
161 if err != nil {
162 return err
163 }
164
165 ref := change.Ref(recordTarget, id)
166 old := o.refs[ref]
167 var before *change.Record
168 if old != "" {
169 if err := fetch(g, old); err != nil {
170 return err
171 }
172 if before, err = readRecord(g, old); err != nil {
173 return err
174 }
175 }
176 handle := o.handle(id)
177 if a.ifActive != "" {
178 switch {
179 case before == nil:
180 return failure(fmt.Sprintf("--if-active %s: origin holds no record of %s, so no version is added", short(a.ifActive), handle))
181 case before.State != change.Ready:
182 return failure(fmt.Sprintf("%s is %s, not ready, so no version is added: --if-active adds one only while the change is ready", handle, before.State))
183 case headOf(before.ActiveVersion()) != a.ifActive:
184 return failure(fmt.Sprintf("%s v%d is at %s, not %s, so no version is added", handle, before.Active, short(headOf(before.ActiveVersion())), short(a.ifActive)))
185 }
186 }
187
188 if a.stamp {
189 // Who owns a change is the host's to say, from the key a push
190 // authenticates with, and valley.principal is only what this
191 // checkout claims. So --stamp, which rewrites a branch before the
192 // record is pushed, starts new changes alone and never asks whose
193 // an existing one is.
194 if before != nil {
195 return failure(fmt.Sprintf("--stamp marks only a new change's first version, and %s has a record on origin already; ready this head with --change %s instead, without --stamp", handle, id))
196 }
197 if head, err = stamp(g, a.branch, head, remote, tip, id); err != nil {
198 return err
199 }
200 }
201
202 subject, err := g.output(true, "log", "-1", "--format=%s", head)
203 if err != nil {
204 return failure("could not read the subject of " + short(head))
205 }
206 version := change.Version{
207 Head: change.HeadPrefix + head, Title: change.Title(subject), Branch: a.branch, Uploader: principal,
208 }
209 var after change.Record
210 var parents []string
211 if before == nil {
212 version.N = 1
213 after = change.Record{
214 Schema: change.Schema, ChangeID: id, Target: recordTarget, Owner: principal,
215 State: change.Ready, Seq: 1, Versions: []change.Version{version}, Active: 1,
216 }
217 parents = []string{head}
218 } else {
219 active := before.ActiveVersion()
220 same := active.Head == version.Head
221 switch {
222 case same && before.State == change.Ready:
223 return failure(fmt.Sprintf("%s v%d is at %s already; a new version needs a new head", handle, active.N, short(head)))
224 case !same && len(before.Versions) >= change.MaxVersions:
225 return failure(fmt.Sprintf("%s has %d versions, the most a change may have", handle, len(before.Versions)))
226 case before.Seq >= change.MaxSeq:
227 return failure(fmt.Sprintf("%s's record has been updated %d times, the most a record may be", handle, before.Seq))
228 }
229 after = *before
230 if same {
231 // A draft or a withdrawn change readied at its active head is
232 // ready again at the version it had, and the record changes
233 // nothing else.
234 version = active
235 parents = []string{old}
236 } else {
237 version.N = before.Last().N + 1
238 after.Versions = append(append([]change.Version(nil), before.Versions...), version)
239 after.Active = version.N
240 parents = []string{old, head}
241 }
242 after.State, after.Seq = change.Ready, before.Seq+1
243 }
244 message := fmt.Sprintf("valley ready: %s v%d\n\nChange %s, version %d, at %s.", handle, version.N, id, version.N, head)
245 commit, err := writeRecord(g, &after, message, parents...)
246 if err != nil {
247 return err
248 }
249 if err := pushRecord(g, id, old, commit); err != nil {
250 return err
251 }
252 fmt.Fprintf(w, "%s %s v%d ready\n", project(g), handle, version.N)
253 if generated {
254 fmt.Fprintf(w, "The change ID %s is new. Ready a later head of this change with --change %s, or carry the ID in the head with --stamp.\n", id, id)
255 }
256 return nil
257}
258
259func runUnready(g git, args []string, stdout, stderr io.Writer) error {
260 return setState(g, args, stdout, stderr, "unready", change.Draft)
261}
262
263func runWithdraw(g git, args []string, stdout, stderr io.Writer) error {
264 return setState(g, args, stdout, stderr, "withdraw", change.Withdrawn)
265}
266
267// setState writes a record that moves a change to the state to, and
268// changes nothing else but the seq. unready moves a ready change to draft,
269// and withdraw moves a ready change or a draft to withdrawn.
270func setState(g git, args []string, stdout, stderr io.Writer, verb, to string) error {
271 if len(args) != 1 {
272 return failure("usage: valley " + verb + " <change>")
273 }
274 if !g.succeeds(true, "rev-parse", "--git-dir") {
275 return failure("not a git repository")
276 }
277 name := args[0]
278 o, err := listOrigin(g, append([]string{"refs/heads/" + strings.TrimPrefix(name, "origin/")},
279 inventoryPatterns...)...)
280 if err != nil {
281 return err
282 }
283 n, found, err := lookup(g, o, name)
284 if err != nil {
285 return err
286 }
287 if !found {
288 if n, err = onBranch(g, o, strings.TrimPrefix(name, "origin/")); err != nil {
289 return err
290 }
291 }
292 handle := o.handle(n.id)
293 switch from := n.record.State; {
294 case from == change.Withdrawn && to == change.Withdrawn:
295 return failure(fmt.Sprintf("%s is withdrawn already; ready it to bring it back", handle))
296 case from == change.Withdrawn:
297 return failure(fmt.Sprintf("%s is withdrawn, and a withdrawn change is never made a draft; ready it to bring it back", handle))
298 case from == change.Draft && to == change.Draft:
299 return failure(fmt.Sprintf("%s is a draft already; ready it to resume it", handle))
300 case n.record.Seq >= change.MaxSeq:
301 return failure(fmt.Sprintf("%s's record has been updated %d times, the most a record may be", handle, n.record.Seq))
302 }
303 after := *n.record
304 after.State, after.Seq = to, n.record.Seq+1
305 message := fmt.Sprintf("valley %s: %s\n\nChange %s, %s at version %d.", verb, handle, n.id, to, after.Active)
306 commit, err := writeRecord(g, &after, message, n.commit)
307 if err != nil {
308 return err
309 }
310 if err := pushRecord(g, n.id, n.commit, commit); err != nil {
311 return err
312 }
313 fmt.Fprintf(stdout, "%s %s v%d %s\n", project(g), handle, after.Active, to)
314 warnPending(stderr, o, n, handle, to)
315 return nil
316}
317
318// warnPending says so when origin held an integration request for the
319// change as the verb read it. The integrator lands no request at a head of
320// a change that is not ready, so the request is held back while the change
321// is a draft or withdrawn, and stands for when it is ready again. That is
322// what a draft means. A withdrawal voids the request, and the integrator
323// deletes it on its next pass. withdraw warns that a ready before then
324// leaves it standing, and that only the operator can drop it. The request is named either way approve has named
325// a change's: as c-<change ID>, or by a branch, the way approve named one
326// before it named a change by its ID. A request filed for an earlier
327// version is named by that version's branch, so the branch of every
328// version is looked for, each once.
329func warnPending(w io.Writer, o origin, n recorded, handle string, to string) {
330 var refs []string
331 seen := map[string]bool{}
332 add := func(ref string) {
333 if !seen[ref] {
334 seen[ref] = true
335 refs = append(refs, ref)
336 }
337 }
338 for _, v := range n.record.Versions {
339 if v.Branch != "" {
340 add(requestPrefix + changeName(v.Branch))
341 }
342 }
343 add(requestPrefix + "c-" + n.id)
344 kind := "note"
345 if to == change.Withdrawn {
346 kind = "warning"
347 }
348 pending := false
349 for _, ref := range refs {
350 if oid := o.refs[ref]; oid != "" {
351 fmt.Fprintf(w, "valley: %s: the integration request %s for %s is pending on origin, at %s\n", kind, ref, handle, short(oid))
352 pending = true
353 }
354 }
355 switch {
356 case !pending:
357 case to == change.Withdrawn:
358 fmt.Fprintln(w, "valley: withdrawing voids the request, and the integrator deletes it on its next pass while the change is still withdrawn. If the change is readied again before then, the request stands and can land. Only a holder of the request grant may touch a request ref, so the operator must drop it then")
359 default:
360 fmt.Fprintln(w, "valley: the integrator lands nothing for a draft. The request stands, and lands once the change is ready again")
361 }
362}
363
364// onBranch is the change whose active version is on branch, and has not
365// landed, for a change named by its branch. Every record on origin is
366// read to find it. o must list inventoryPatterns.
367func onBranch(g git, o origin, branch string) (recorded, error) {
368 found, err := unlandedOn(g, o, branch)
369 if err != nil {
370 return recorded{}, err
371 }
372 switch len(found) {
373 case 0:
374 return recorded{}, failure(fmt.Sprintf("no change on origin is named %s or has its active version on that branch", branch))
375 case 1:
376 return found[0], nil
377 }
378 var handles []string
379 for _, n := range found {
380 handles = append(handles, o.handle(n.id))
381 }
382 return recorded{}, failure(fmt.Sprintf("the changes %s all have their active version on %s; name one by its handle",
383 strings.Join(handles, ", "), branch))
384}
385
386// checkRange refuses a change whose commits are not one line: the range
387// from the merge base of origin's main and the head, to the head, must hold
388// no merge commit, and the merge base must be one commit.
389func checkRange(g git, tip, head string) error {
390 out, err := g.output(true, "merge-base", "--all", tip, head)
391 bases := strings.Fields(out)
392 switch {
393 case err != nil && len(bases) == 0:
394 return failure(fmt.Sprintf("%s shares no history with origin's %s, so it is no change to it", short(head), recordTarget))
395 case len(bases) > 1:
396 return failure(fmt.Sprintf("%s has %d merge bases with origin's %s, so the commits of the change are ambiguous", short(head), len(bases), recordTarget))
397 }
398 merges, err := g.output(true, "rev-list", "--min-parents=2", bases[0]+".."+head)
399 if err != nil {
400 return failure("could not read the commits from origin's " + recordTarget + " to " + short(head))
401 }
402 if merges != "" {
403 first := strings.Fields(merges)[0]
404 return failure(fmt.Sprintf("the commits from origin's %s to %s include the merge %s, and a change is a line of commits", recordTarget, short(head), short(first)))
405 }
406 return nil
407}
408
409// changeID is the change's ID: --change when given, then the head
410// commit's change-id header, as jj writes it, then a Change-Id trailer in
411// its message, and otherwise a new ID. Both the header and the trailer are
412// read whatever the source, and either one malformed, or the two
413// disagreeing, is refused. IDs on the other commits of the change are
414// their own provenance and are not read.
415func changeID(g git, head, flag string) (id string, generated bool, err error) {
416 header, trailer, err := headIDs(g, head)
417 if err != nil {
418 return "", false, err
419 }
420 switch {
421 case header != "" && trailer != "" && header != trailer:
422 return "", false, failure(fmt.Sprintf("%s has the change-id header %s and the Change-Id trailer %s, and they must agree", short(head), header, trailer))
423 case flag != "":
424 if !change.ValidID(flag) {
425 return "", false, failure("--change takes a change ID, 32 letters from k to z, and " + flag + " is not one")
426 }
427 return flag, false, nil
428 case header != "":
429 return header, false, nil
430 case trailer != "":
431 return trailer, false, nil
432 }
433 id, err = change.NewID()
434 if err != nil {
435 return "", false, failure("could not make a change ID: " + err.Error())
436 }
437 return id, true, nil
438}
439
440// headIDs reads the change IDs a commit carries: the change-id header in
441// the commit object itself, never text in its message, and the Change-Id
442// trailer, as git interpret-trailers parses the message.
443func headIDs(g git, head string) (header, trailer string, err error) {
444 raw, err := g.output(true, "cat-file", "commit", head)
445 if err != nil {
446 return "", "", failure("could not read the commit " + short(head))
447 }
448 headers, message, _ := strings.Cut(raw, "\n\n")
449 var found []string
450 for _, line := range strings.Split(headers, "\n") {
451 // A line opening with a space continues the header above it.
452 if v, ok := strings.CutPrefix(line, "change-id "); ok {
453 found = append(found, v)
454 }
455 }
456 switch {
457 case len(found) > 1:
458 return "", "", failure(short(head) + " has more than one change-id header")
459 case len(found) == 1 && !change.ValidID(found[0]):
460 return "", "", failure(fmt.Sprintf("%s has the change-id header %q, which is not a change ID", short(head), found[0]))
461 case len(found) == 1:
462 header = found[0]
463 }
464
465 parsed, err := g.input(true, strings.NewReader(message), "interpret-trailers", "--parse")
466 if err != nil {
467 return "", "", failure("could not read the trailers of " + short(head))
468 }
469 found = nil
470 for _, line := range strings.Split(parsed, "\n") {
471 key, value, ok := strings.Cut(line, ":")
472 if ok && strings.EqualFold(strings.TrimSpace(key), "Change-Id") {
473 found = append(found, strings.TrimSpace(value))
474 }
475 }
476 switch {
477 case len(found) > 1:
478 return "", "", failure(short(head) + " has more than one Change-Id trailer")
479 case len(found) == 1 && !change.ValidID(found[0]):
480 return "", "", failure(fmt.Sprintf("%s has the Change-Id trailer %q, which is not a change ID", short(head), found[0]))
481 case len(found) == 1:
482 trailer = found[0]
483 }
484 return header, trailer, nil
485}
486
487// stamp amends the head of the local branch to carry the change ID as a
488// Change-Id trailer, and pushes the branch so that the amended head is on
489// origin. It returns the amended head, or the head as it was when it
490// carries the trailer already.
491//
492// Amending rewrites a commit, which is harmless only while nobody else can
493// have it. So stamp refuses a head that is on origin already. It refuses a
494// local branch that is behind origin's or has diverged from it too, since
495// pushing the amended head would drop commits origin holds. Its caller
496// refuses a change that has a record already.
497func stamp(g git, branch, head, remote, tip, id string) (string, error) {
498 _, trailer, err := headIDs(g, head)
499 if err != nil {
500 return "", err
501 }
502 if trailer == id {
503 return head, nil
504 }
505 if trailer != "" {
506 return "", failure(fmt.Sprintf("%s carries the Change-Id trailer %s already, and --stamp would add %s", short(head), trailer, id))
507 }
508 onBranch := remote != "" && g.succeeds(true, "merge-base", "--is-ancestor", head, remote)
509 inTarget := g.succeeds(true, "merge-base", "--is-ancestor", head, tip)
510 switch {
511 case onBranch && head != remote:
512 return "", failure(fmt.Sprintf("origin's %s is ahead of yours; bring yours up to date before stamping its head", branch))
513 case remote != "" && !onBranch && !g.succeeds(true, "merge-base", "--is-ancestor", remote, head):
514 return "", failure(fmt.Sprintf("your %s and origin's have diverged; --stamp would drop what origin holds", branch))
515 case onBranch || inTarget:
516 return "", failure(fmt.Sprintf("%s is on origin already, so --stamp will not rewrite it; ready it with --change %s instead", short(head), id))
517 }
518
519 raw, err := g.output(true, "cat-file", "commit", head)
520 if err != nil {
521 return "", failure("could not read the commit " + short(head))
522 }
523 _, message, _ := strings.Cut(raw, "\n\n")
524 stamped, err := g.input(true, strings.NewReader(message), "interpret-trailers", "--trailer", "Change-Id: "+id)
525 if err != nil {
526 return "", failure("could not add the Change-Id trailer to " + short(head))
527 }
528 // The amended commit keeps the head's tree, parents and author, as
529 // git commit --amend does. The committer is whoever stamps it.
530 who, err := g.output(true, "log", "-1", "--date=raw", "--format=%an%x00%ae%x00%ad%x00%T%x00%P", head)
531 if err != nil {
532 return "", failure("could not read the commit " + short(head))
533 }
534 f := strings.Split(who, "\x00")
535 if len(f) != 5 {
536 return "", failure("could not read the commit " + short(head))
537 }
538 args := []string{"commit-tree", f[3]}
539 for _, p := range strings.Fields(f[4]) {
540 args = append(args, "-p", p)
541 }
542 amend := g
543 amend.env = append(append([]string(nil), g.env...),
544 "GIT_AUTHOR_NAME="+f[0], "GIT_AUTHOR_EMAIL="+f[1], "GIT_AUTHOR_DATE=@"+f[2])
545 amended, err := amend.input(false, strings.NewReader(stamped+"\n"), append(args, "-F", "-")...)
546 if err != nil {
547 return "", failure("could not write the amended commit")
548 }
549 if _, err := g.output(false, "update-ref", "-m", "valley ready --stamp", "refs/heads/"+branch, amended, head); err != nil {
550 return "", failure("could not move your " + branch + " to the amended head")
551 }
552 _, err = g.output(false, "push", "--quiet", "--force-with-lease=refs/heads/"+branch+":"+remote,
553 "origin", amended+":refs/heads/"+branch)
554 if err != nil {
555 return "", failure(fmt.Sprintf("your %s carries the stamped head %s, and origin did not take it", branch, short(amended)))
556 }
557 return amended, nil
558}
559
560func isHexPrefix(s string) bool {
561 if len(s) < 4 || len(s) > 40 {
562 return false
563 }
564 for _, c := range []byte(s) {
565 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
566 return false
567 }
568 }
569 return true
570}