gunk-dev/the-valley

ready.go

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