gunk-dev/the-valley

ready.go

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