gunk-dev/the-valley

ready.go

source88a5a486b52fmain's published tip history
19.5 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 "context"
39 "fmt"
40 "io"
41 "strings"
42
43 "the-valley/change"
44 "the-valley/rebase"
45)
46
47const readyUsage = "usage: valley ready [--head <sha>] [--change <id>] [--if-active <sha>] [--stamp] [<branch>]"
48
49type readyArgs struct {
50 head, id, branch, ifActive string
51 stamp bool
52}
53
54func parseReadyArgs(args []string) (readyArgs, error) {
55 var a readyArgs
56 var rest []string
57 for i := 0; i < len(args); i++ {
58 arg := args[i]
59 value := func(flag string) (string, error) {
60 if v, ok := strings.CutPrefix(arg, flag+"="); ok {
61 return v, nil
62 }
63 if i+1 >= len(args) {
64 return "", failure(flag + " needs a value; " + readyUsage)
65 }
66 i++
67 return args[i], nil
68 }
69 var err error
70 switch {
71 case arg == "--head" || strings.HasPrefix(arg, "--head="):
72 a.head, err = value("--head")
73 case arg == "--change" || strings.HasPrefix(arg, "--change="):
74 a.id, err = value("--change")
75 case arg == "--if-active" || strings.HasPrefix(arg, "--if-active="):
76 a.ifActive, err = value("--if-active")
77 case arg == "--stamp":
78 a.stamp = true
79 case strings.HasPrefix(arg, "-"):
80 err = failure("unknown option " + arg + "; " + readyUsage)
81 default:
82 rest = append(rest, arg)
83 }
84 if err != nil {
85 return a, err
86 }
87 }
88 switch {
89 case len(rest) > 1:
90 return a, failure(readyUsage)
91 case len(rest) == 1:
92 a.branch = strings.TrimPrefix(rest[0], "origin/")
93 }
94 return a, nil
95}
96
97func runReady(g git, args []string, w io.Writer) error {
98 a, err := parseReadyArgs(args)
99 if err != nil {
100 return err
101 }
102 _, err = ready(g, a, w)
103 return err
104}
105
106// ready writes the record a asks for, prints the handle and version it
107// made ready, and returns that version's number.
108func ready(g git, a readyArgs, w io.Writer) (int, error) {
109 if !g.succeeds(true, "rev-parse", "--git-dir") {
110 return 0, failure("not a git repository")
111 }
112 principal, err := g.output(true, "config", "valley.principal")
113 if err != nil || !change.ValidPrincipal(principal) {
114 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>")
115 }
116 if a.branch == "" {
117 if a.branch, err = g.output(true, "symbolic-ref", "--quiet", "--short", "HEAD"); err != nil {
118 return 0, failure("HEAD is on no branch; name one: " + readyUsage)
119 }
120 }
121 if !change.ValidBranch(a.branch) {
122 return 0, failure("not a branch name: " + a.branch)
123 }
124 if a.stamp && a.head != "" {
125 return 0, failure("--stamp amends the branch's own head, so it takes no --head")
126 }
127 if a.ifActive != "" && !isObjectID(a.ifActive) {
128 return 0, failure("--if-active takes the full object ID of a version's head, and " + a.ifActive + " is not one")
129 }
130 if a.ifActive != "" && a.stamp {
131 return 0, failure("--stamp starts a new change, so it takes no --if-active")
132 }
133
134 o, err := listOrigin(g, append([]string{"refs/heads/" + recordTarget, "refs/heads/" + a.branch}, recordPatterns...)...)
135 if err != nil {
136 return 0, err
137 }
138 tip, remote := o.refs["refs/heads/"+recordTarget], o.refs["refs/heads/"+a.branch]
139 if tip == "" {
140 return 0, failure("origin has no " + recordTarget + " branch, so a change has nothing to target")
141 }
142 if err := fetch(g, tip, remote); err != nil {
143 return 0, err
144 }
145
146 var head string
147 switch {
148 case a.stamp:
149 // The local branch is read by its exact name, so a branch named
150 // refs/heads/<branch> is not taken for it.
151 var found bool
152 if head, found, err = g.ref("refs/heads/" + a.branch); err != nil || !found {
153 return 0, failure("--stamp amends the head of your local " + a.branch + ", and there is no such branch")
154 }
155 case a.head != "":
156 if !isHexPrefix(a.head) {
157 return 0, failure("--head takes a commit's object ID, and " + a.head + " is not one")
158 }
159 head, err = g.output(true, "rev-parse", "--verify", "--quiet", a.head+"^{commit}")
160 if err != nil || remote == "" || !g.succeeds(true, "merge-base", "--is-ancestor", head, remote) {
161 return 0, failure(a.head + " is not on origin's " + a.branch + "; push it there first")
162 }
163 default:
164 if remote == "" {
165 return 0, failure(a.branch + " is not on origin; push it there first")
166 }
167 head = remote
168 }
169 if err := checkRange(g, tip, head); err != nil {
170 return 0, err
171 }
172 id, generated, err := changeID(g, head, a.id)
173 if err != nil {
174 return 0, err
175 }
176
177 ref := change.Ref(recordTarget, id)
178 old := o.refs[ref]
179 var before *change.Record
180 if old != "" {
181 if err := fetch(g, old); err != nil {
182 return 0, err
183 }
184 if before, err = readRecord(g, old); err != nil {
185 return 0, err
186 }
187 }
188 handle := o.handle(id)
189 if a.ifActive != "" {
190 if err := rebase.CheckActive(handle, before, a.ifActive); err != nil {
191 return 0, err
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 switch {
219 case before == nil:
220 version.N = 1
221 after = &change.Record{
222 Schema: change.Schema, ChangeID: id, Target: recordTarget, Owner: principal,
223 State: change.Ready, Seq: 1, Versions: []change.Version{version}, Active: 1,
224 }
225 parents = []string{head}
226 case before.ActiveVersion().Head == version.Head && before.State != change.Ready:
227 // A draft or a withdrawn change readied at its active head is
228 // ready again at the version it had, and the record changes
229 // nothing else.
230 if before.Seq >= change.MaxSeq {
231 return 0, failure(fmt.Sprintf("%s's record has been updated %d times, the most a record may be", handle, before.Seq))
232 }
233 revived := *before
234 revived.State, revived.Seq = change.Ready, before.Seq+1
235 after, version, parents = &revived, before.ActiveVersion(), []string{old}
236 default:
237 if after, err = rebase.NextRecord(handle, before, version); err != nil {
238 return 0, err
239 }
240 version, parents = after.ActiveVersion(), []string{old, head}
241 }
242 commit, err := writeRecord(g, after, rebase.ReadyMessage(handle, id, version.N, head), parents...)
243 if err != nil {
244 return 0, err
245 }
246 if err := pushRecord(g, id, old, commit); err != nil {
247 return 0, err
248 }
249 fmt.Fprintf(w, "%s %s v%d ready\n", project(g), handle, version.N)
250 if generated && !a.stamp {
251 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)
252 }
253 return version.N, nil
254}
255
256func runUnready(g git, args []string, stdout, stderr io.Writer) error {
257 return setState(g, args, stdout, stderr, "unready", change.Draft, "")
258}
259
260func runWithdraw(g git, args []string, stdout, stderr io.Writer) error {
261 return setState(g, args, stdout, stderr, "withdraw", change.Withdrawn, "")
262}
263
264// setState writes a record that moves a change to the state to, and
265// changes nothing else but the seq. unready moves a ready change to draft,
266// and withdraw moves a ready change or a draft to withdrawn. Given at, a
267// head, it writes only while the change's active version is at it, and
268// the push is leased on the record that check read: review's [r]eject
269// withdraws the version whose branch it deleted, never one readied since.
270func setState(g git, args []string, stdout, stderr io.Writer, verb, to, at 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 at != "" && n.record.ActiveVersion().Head != change.HeadPrefix+at:
295 return failure(fmt.Sprintf("%s is at v%d now, not at %s as it was read", handle, n.record.Active, short(at)))
296 case from == change.Withdrawn && to == change.Withdrawn:
297 return failure(fmt.Sprintf("%s is withdrawn already; ready it to bring it back", handle))
298 case from == change.Withdrawn:
299 return failure(fmt.Sprintf("%s is withdrawn, and a withdrawn change is never made a draft; ready it to bring it back", handle))
300 case from == change.Draft && to == change.Draft:
301 return failure(fmt.Sprintf("%s is a draft already; ready it to resume it", handle))
302 case n.record.Seq >= change.MaxSeq:
303 return failure(fmt.Sprintf("%s's record has been updated %d times, the most a record may be", handle, n.record.Seq))
304 }
305 after := *n.record
306 after.State, after.Seq = to, n.record.Seq+1
307 message := fmt.Sprintf("valley %s: %s\n\nChange %s, %s at version %d.", verb, handle, n.id, to, after.Active)
308 commit, err := writeRecord(g, &after, message, n.commit)
309 if err != nil {
310 return err
311 }
312 if err := pushRecord(g, n.id, n.commit, commit); err != nil {
313 return err
314 }
315 fmt.Fprintf(stdout, "%s %s v%d %s\n", project(g), handle, after.Active, to)
316 warnPending(stderr, o, n, handle, to)
317 return nil
318}
319
320// warnPending says so when origin held an integration request for the
321// change as the verb read it. The integrator lands no request at a head of
322// a change that is not ready, so the request is held back while the change
323// is a draft or withdrawn, and stands for when it is ready again. That is
324// what a draft means. A withdrawal voids the request, and the integrator
325// deletes it on its next pass. withdraw warns that a ready before then
326// leaves it standing, and that only the operator can drop it. The request is named either way approve has named
327// a change's: as c-<change ID>, or by a branch, the way approve named one
328// before it named a change by its ID. A request filed for an earlier
329// version is named by that version's branch, so the branch of every
330// version is looked for, each once.
331func warnPending(w io.Writer, o origin, n recorded, handle string, to string) {
332 var refs []string
333 seen := map[string]bool{}
334 add := func(ref string) {
335 if !seen[ref] {
336 seen[ref] = true
337 refs = append(refs, ref)
338 }
339 }
340 for _, v := range n.record.Versions {
341 if v.Branch != "" {
342 add(requestPrefix + changeName(v.Branch))
343 }
344 }
345 add(requestPrefix + "c-" + n.id)
346 kind := "note"
347 if to == change.Withdrawn {
348 kind = "warning"
349 }
350 pending := false
351 for _, ref := range refs {
352 if oid := o.refs[ref]; oid != "" {
353 fmt.Fprintf(w, "valley: %s: the integration request %s for %s is pending on origin, at %s\n", kind, ref, handle, short(oid))
354 pending = true
355 }
356 }
357 switch {
358 case !pending:
359 case to == change.Withdrawn:
360 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 approve grant (also accepted as request) may touch a request ref, so the operator must drop it then")
361 default:
362 fmt.Fprintln(w, "valley: the integrator lands nothing for a draft. The request stands, and lands once the change is ready again")
363 }
364}
365
366// onBranch is the change whose active version is on branch, and has not
367// landed, for a change named by its branch. Every record on origin is
368// read to find it. o must list inventoryPatterns.
369func onBranch(g git, o origin, branch string) (recorded, error) {
370 found, err := unlandedOn(g, o, branch)
371 if err != nil {
372 return recorded{}, err
373 }
374 switch len(found) {
375 case 0:
376 return recorded{}, failure(fmt.Sprintf("no change on origin is named %s or has its active version on that branch", branch))
377 case 1:
378 return found[0], nil
379 }
380 var handles []string
381 for _, n := range found {
382 handles = append(handles, o.handle(n.id))
383 }
384 return recorded{}, failure(fmt.Sprintf("the changes %s all have their active version on %s; name one by its handle",
385 strings.Join(handles, ", "), branch))
386}
387
388// checkRange refuses a change whose commits are not one line, as the
389// rebase engine checks a version's head (rebase.CheckRange).
390func checkRange(g git, tip, head string) error {
391 return rebase.CheckRange(context.Background(), g.engine(), tip, head)
392}
393
394// changeID is the change's ID: --change when given, then the head
395// commit's change-id header, as jj writes it, then a Change-Id trailer in
396// its message, and otherwise a new ID. Both the header and the trailer are
397// read whatever the source, and either one malformed, or the two
398// disagreeing, is refused. IDs on the other commits of the change are
399// their own provenance and are not read.
400func changeID(g git, head, flag string) (id string, generated bool, err error) {
401 header, trailer, err := headIDs(g, head)
402 if err != nil {
403 return "", false, err
404 }
405 switch {
406 case header != "" && trailer != "" && header != trailer:
407 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))
408 case flag != "":
409 if !change.ValidID(flag) {
410 return "", false, failure("--change takes a change ID, 32 letters from k to z, and " + flag + " is not one")
411 }
412 return flag, false, nil
413 case header != "":
414 return header, false, nil
415 case trailer != "":
416 return trailer, false, nil
417 }
418 id, err = change.NewID()
419 if err != nil {
420 return "", false, failure("could not make a change ID: " + err.Error())
421 }
422 return id, true, nil
423}
424
425// headIDs reads the change IDs a commit carries: the change-id header in
426// the commit object itself, and the Change-Id trailer (rebase.HeadIDs).
427func headIDs(g git, head string) (header, trailer string, err error) {
428 return rebase.HeadIDs(context.Background(), g.engine(), head)
429}
430
431// stamp amends the head of the local branch to carry the change ID as a
432// Change-Id trailer, and pushes the branch so that the amended head is on
433// origin. It returns the amended head, or the head as it was when it
434// carries the trailer already.
435//
436// Amending rewrites a commit, which is harmless only while nobody else can
437// have it. So stamp refuses a head that is on origin already. It refuses a
438// local branch that is behind origin's or has diverged from it too, since
439// pushing the amended head would drop commits origin holds. Its caller
440// refuses a change that has a record already.
441func stamp(g git, branch, head, remote, tip, id string) (string, error) {
442 _, trailer, err := headIDs(g, head)
443 if err != nil {
444 return "", err
445 }
446 if trailer == id {
447 return head, nil
448 }
449 if trailer != "" {
450 return "", failure(fmt.Sprintf("%s carries the Change-Id trailer %s already, and --stamp would add %s", short(head), trailer, id))
451 }
452 onBranch := remote != "" && g.succeeds(true, "merge-base", "--is-ancestor", head, remote)
453 inTarget := g.succeeds(true, "merge-base", "--is-ancestor", head, tip)
454 switch {
455 case onBranch && head != remote:
456 return "", failure(fmt.Sprintf("origin's %s is ahead of yours; bring yours up to date before stamping its head", branch))
457 case remote != "" && !onBranch && !g.succeeds(true, "merge-base", "--is-ancestor", remote, head):
458 return "", failure(fmt.Sprintf("your %s and origin's have diverged; --stamp would drop what origin holds", branch))
459 case onBranch || inTarget:
460 return "", failure(fmt.Sprintf("%s is on origin already, so --stamp will not rewrite it; ready it with --change %s instead", short(head), id))
461 }
462
463 raw, err := g.output(true, "cat-file", "commit", head)
464 if err != nil {
465 return "", failure("could not read the commit " + short(head))
466 }
467 _, message, _ := strings.Cut(raw, "\n\n")
468 stamped, err := g.input(true, strings.NewReader(message), "interpret-trailers", "--trailer", "Change-Id: "+id)
469 if err != nil {
470 return "", failure("could not add the Change-Id trailer to " + short(head))
471 }
472 // The amended commit keeps the head's tree, parents and author, as
473 // git commit --amend does. The committer is whoever stamps it.
474 who, err := g.output(true, "log", "-1", "--date=raw", "--format=%an%x00%ae%x00%ad%x00%T%x00%P", head)
475 if err != nil {
476 return "", failure("could not read the commit " + short(head))
477 }
478 f := strings.Split(who, "\x00")
479 if len(f) != 5 {
480 return "", failure("could not read the commit " + short(head))
481 }
482 args := []string{"commit-tree", f[3]}
483 for _, p := range strings.Fields(f[4]) {
484 args = append(args, "-p", p)
485 }
486 amend := g
487 amend.env = append(append([]string(nil), g.env...),
488 "GIT_AUTHOR_NAME="+f[0], "GIT_AUTHOR_EMAIL="+f[1], "GIT_AUTHOR_DATE=@"+f[2])
489 amended, err := amend.input(false, strings.NewReader(stamped+"\n"), append(args, "-F", "-")...)
490 if err != nil {
491 return "", failure("could not write the amended commit")
492 }
493 if _, err := g.output(false, "update-ref", "-m", "valley ready --stamp", "refs/heads/"+branch, amended, head); err != nil {
494 return "", failure("could not move your " + branch + " to the amended head")
495 }
496 _, err = g.output(false, "push", "--quiet", "--force-with-lease=refs/heads/"+branch+":"+remote,
497 "origin", amended+":refs/heads/"+branch)
498 if err != nil {
499 return "", failure(fmt.Sprintf("your %s carries the stamped head %s, and origin did not take it", branch, short(amended)))
500 }
501 return amended, nil
502}
503
504func isHexPrefix(s string) bool {
505 if len(s) < 4 || len(s) > 40 {
506 return false
507 }
508 for _, c := range []byte(s) {
509 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
510 return false
511 }
512 }
513 return true
514}