gunk-dev/the-valley

ready.go

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