gunk-dev/the-valley

ready.go

source60224096edd0main's published tip history
19.1 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 {
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.
267func setState(g git, args []string, stdout, stderr io.Writer, verb, to string) error {
268 if len(args) != 1 {
269 return failure("usage: valley " + verb + " <change>")
270 }
271 if !g.succeeds(true, "rev-parse", "--git-dir") {
272 return failure("not a git repository")
273 }
274 name := args[0]
275 o, err := listOrigin(g, append([]string{"refs/heads/" + strings.TrimPrefix(name, "origin/")},
276 inventoryPatterns...)...)
277 if err != nil {
278 return err
279 }
280 n, found, err := lookup(g, o, name)
281 if err != nil {
282 return err
283 }
284 if !found {
285 if n, err = onBranch(g, o, strings.TrimPrefix(name, "origin/")); err != nil {
286 return err
287 }
288 }
289 handle := o.handle(n.id)
290 switch from := n.record.State; {
291 case from == change.Withdrawn && to == change.Withdrawn:
292 return failure(fmt.Sprintf("%s is withdrawn already; ready it to bring it back", handle))
293 case from == change.Withdrawn:
294 return failure(fmt.Sprintf("%s is withdrawn, and a withdrawn change is never made a draft; ready it to bring it back", handle))
295 case from == change.Draft && to == change.Draft:
296 return failure(fmt.Sprintf("%s is a draft already; ready it to resume it", handle))
297 case n.record.Seq >= change.MaxSeq:
298 return failure(fmt.Sprintf("%s's record has been updated %d times, the most a record may be", handle, n.record.Seq))
299 }
300 after := *n.record
301 after.State, after.Seq = to, n.record.Seq+1
302 message := fmt.Sprintf("valley %s: %s\n\nChange %s, %s at version %d.", verb, handle, n.id, to, after.Active)
303 commit, err := writeRecord(g, &after, message, n.commit)
304 if err != nil {
305 return err
306 }
307 if err := pushRecord(g, n.id, n.commit, commit); err != nil {
308 return err
309 }
310 fmt.Fprintf(stdout, "%s %s v%d %s\n", project(g), handle, after.Active, to)
311 warnPending(stderr, o, n, handle, to)
312 return nil
313}
314
315// warnPending says so when origin held an integration request for the
316// change as the verb read it. The integrator lands no request at a head of
317// a change that is not ready, so the request is held back while the change
318// is a draft or withdrawn, and stands for when it is ready again. That is
319// what a draft means. A withdrawal voids the request, and the integrator
320// deletes it on its next pass. withdraw warns that a ready before then
321// leaves it standing, and that only the operator can drop it. The request is named either way approve has named
322// a change's: as c-<change ID>, or by a branch, the way approve named one
323// before it named a change by its ID. A request filed for an earlier
324// version is named by that version's branch, so the branch of every
325// version is looked for, each once.
326func warnPending(w io.Writer, o origin, n recorded, handle string, to string) {
327 var refs []string
328 seen := map[string]bool{}
329 add := func(ref string) {
330 if !seen[ref] {
331 seen[ref] = true
332 refs = append(refs, ref)
333 }
334 }
335 for _, v := range n.record.Versions {
336 if v.Branch != "" {
337 add(requestPrefix + changeName(v.Branch))
338 }
339 }
340 add(requestPrefix + "c-" + n.id)
341 kind := "note"
342 if to == change.Withdrawn {
343 kind = "warning"
344 }
345 pending := false
346 for _, ref := range refs {
347 if oid := o.refs[ref]; oid != "" {
348 fmt.Fprintf(w, "valley: %s: the integration request %s for %s is pending on origin, at %s\n", kind, ref, handle, short(oid))
349 pending = true
350 }
351 }
352 switch {
353 case !pending:
354 case to == change.Withdrawn:
355 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")
356 default:
357 fmt.Fprintln(w, "valley: the integrator lands nothing for a draft. The request stands, and lands once the change is ready again")
358 }
359}
360
361// onBranch is the change whose active version is on branch, and has not
362// landed, for a change named by its branch. Every record on origin is
363// read to find it. o must list inventoryPatterns.
364func onBranch(g git, o origin, branch string) (recorded, error) {
365 found, err := unlandedOn(g, o, branch)
366 if err != nil {
367 return recorded{}, err
368 }
369 switch len(found) {
370 case 0:
371 return recorded{}, failure(fmt.Sprintf("no change on origin is named %s or has its active version on that branch", branch))
372 case 1:
373 return found[0], nil
374 }
375 var handles []string
376 for _, n := range found {
377 handles = append(handles, o.handle(n.id))
378 }
379 return recorded{}, failure(fmt.Sprintf("the changes %s all have their active version on %s; name one by its handle",
380 strings.Join(handles, ", "), branch))
381}
382
383// checkRange refuses a change whose commits are not one line, as the
384// rebase engine checks a version's head (rebase.CheckRange).
385func checkRange(g git, tip, head string) error {
386 return rebase.CheckRange(context.Background(), g.engine(), tip, head)
387}
388
389// changeID is the change's ID: --change when given, then the head
390// commit's change-id header, as jj writes it, then a Change-Id trailer in
391// its message, and otherwise a new ID. Both the header and the trailer are
392// read whatever the source, and either one malformed, or the two
393// disagreeing, is refused. IDs on the other commits of the change are
394// their own provenance and are not read.
395func changeID(g git, head, flag string) (id string, generated bool, err error) {
396 header, trailer, err := headIDs(g, head)
397 if err != nil {
398 return "", false, err
399 }
400 switch {
401 case header != "" && trailer != "" && header != trailer:
402 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))
403 case flag != "":
404 if !change.ValidID(flag) {
405 return "", false, failure("--change takes a change ID, 32 letters from k to z, and " + flag + " is not one")
406 }
407 return flag, false, nil
408 case header != "":
409 return header, false, nil
410 case trailer != "":
411 return trailer, false, nil
412 }
413 id, err = change.NewID()
414 if err != nil {
415 return "", false, failure("could not make a change ID: " + err.Error())
416 }
417 return id, true, nil
418}
419
420// headIDs reads the change IDs a commit carries: the change-id header in
421// the commit object itself, and the Change-Id trailer (rebase.HeadIDs).
422func headIDs(g git, head string) (header, trailer string, err error) {
423 return rebase.HeadIDs(context.Background(), g.engine(), head)
424}
425
426// stamp amends the head of the local branch to carry the change ID as a
427// Change-Id trailer, and pushes the branch so that the amended head is on
428// origin. It returns the amended head, or the head as it was when it
429// carries the trailer already.
430//
431// Amending rewrites a commit, which is harmless only while nobody else can
432// have it. So stamp refuses a head that is on origin already. It refuses a
433// local branch that is behind origin's or has diverged from it too, since
434// pushing the amended head would drop commits origin holds. Its caller
435// refuses a change that has a record already.
436func stamp(g git, branch, head, remote, tip, id string) (string, error) {
437 _, trailer, err := headIDs(g, head)
438 if err != nil {
439 return "", err
440 }
441 if trailer == id {
442 return head, nil
443 }
444 if trailer != "" {
445 return "", failure(fmt.Sprintf("%s carries the Change-Id trailer %s already, and --stamp would add %s", short(head), trailer, id))
446 }
447 onBranch := remote != "" && g.succeeds(true, "merge-base", "--is-ancestor", head, remote)
448 inTarget := g.succeeds(true, "merge-base", "--is-ancestor", head, tip)
449 switch {
450 case onBranch && head != remote:
451 return "", failure(fmt.Sprintf("origin's %s is ahead of yours; bring yours up to date before stamping its head", branch))
452 case remote != "" && !onBranch && !g.succeeds(true, "merge-base", "--is-ancestor", remote, head):
453 return "", failure(fmt.Sprintf("your %s and origin's have diverged; --stamp would drop what origin holds", branch))
454 case onBranch || inTarget:
455 return "", failure(fmt.Sprintf("%s is on origin already, so --stamp will not rewrite it; ready it with --change %s instead", short(head), id))
456 }
457
458 raw, err := g.output(true, "cat-file", "commit", head)
459 if err != nil {
460 return "", failure("could not read the commit " + short(head))
461 }
462 _, message, _ := strings.Cut(raw, "\n\n")
463 stamped, err := g.input(true, strings.NewReader(message), "interpret-trailers", "--trailer", "Change-Id: "+id)
464 if err != nil {
465 return "", failure("could not add the Change-Id trailer to " + short(head))
466 }
467 // The amended commit keeps the head's tree, parents and author, as
468 // git commit --amend does. The committer is whoever stamps it.
469 who, err := g.output(true, "log", "-1", "--date=raw", "--format=%an%x00%ae%x00%ad%x00%T%x00%P", head)
470 if err != nil {
471 return "", failure("could not read the commit " + short(head))
472 }
473 f := strings.Split(who, "\x00")
474 if len(f) != 5 {
475 return "", failure("could not read the commit " + short(head))
476 }
477 args := []string{"commit-tree", f[3]}
478 for _, p := range strings.Fields(f[4]) {
479 args = append(args, "-p", p)
480 }
481 amend := g
482 amend.env = append(append([]string(nil), g.env...),
483 "GIT_AUTHOR_NAME="+f[0], "GIT_AUTHOR_EMAIL="+f[1], "GIT_AUTHOR_DATE=@"+f[2])
484 amended, err := amend.input(false, strings.NewReader(stamped+"\n"), append(args, "-F", "-")...)
485 if err != nil {
486 return "", failure("could not write the amended commit")
487 }
488 if _, err := g.output(false, "update-ref", "-m", "valley ready --stamp", "refs/heads/"+branch, amended, head); err != nil {
489 return "", failure("could not move your " + branch + " to the amended head")
490 }
491 _, err = g.output(false, "push", "--quiet", "--force-with-lease=refs/heads/"+branch+":"+remote,
492 "origin", amended+":refs/heads/"+branch)
493 if err != nil {
494 return "", failure(fmt.Sprintf("your %s carries the stamped head %s, and origin did not take it", branch, short(amended)))
495 }
496 return amended, nil
497}
498
499func isHexPrefix(s string) bool {
500 if len(s) < 4 || len(s) > 40 {
501 return false
502 }
503 for _, c := range []byte(s) {
504 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
505 return false
506 }
507 }
508 return true
509}