gunk-dev/the-valley

ready.go

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