gunk-dev/the-valley

ready.go

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