gunk-dev/the-valley

ready.go

source53fb2c06ff1amain's published tip history
16.9 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 own := before != nil && before.Owner == principal
158 if head, err = stamp(g, a.branch, head, remote, tip, id, own); err != nil {
159 return err
160 }
161 }
162
163 subject, err := g.output(true, "log", "-1", "--format=%s", head)
164 if err != nil {
165 return failure("could not read the subject of " + short(head))
166 }
167 version := change.Version{
168 Head: change.HeadPrefix + head, Title: change.Title(subject), Branch: a.branch, Uploader: principal,
169 }
170 var after change.Record
171 var parents []string
172 if before == nil {
173 version.N = 1
174 after = change.Record{
175 Schema: change.Schema, ChangeID: id, Target: recordTarget, Owner: principal,
176 State: change.Ready, Seq: 1, Versions: []change.Version{version}, Active: 1,
177 }
178 parents = []string{head}
179 } else {
180 active := before.ActiveVersion()
181 switch {
182 case active.Head == version.Head:
183 return failure(fmt.Sprintf("%s v%d is at %s already; a new version needs a new head", handle, active.N, short(head)))
184 case len(before.Versions) >= change.MaxVersions:
185 return failure(fmt.Sprintf("%s has %d versions, the most a change may have", handle, len(before.Versions)))
186 case before.Seq >= change.MaxSeq:
187 return failure(fmt.Sprintf("%s's record has been updated %d times, the most a record may be", handle, before.Seq))
188 }
189 version.N = before.Last().N + 1
190 after = *before
191 after.Versions = append(append([]change.Version(nil), before.Versions...), version)
192 after.Active, after.State, after.Seq = version.N, change.Ready, before.Seq+1
193 parents = []string{old, head}
194 }
195 message := fmt.Sprintf("valley ready: %s v%d\n\nChange %s, version %d, at %s.", handle, version.N, id, version.N, head)
196 commit, err := writeRecord(g, &after, message, parents...)
197 if err != nil {
198 return err
199 }
200 if err := pushRecord(g, id, old, commit); err != nil {
201 return err
202 }
203 fmt.Fprintf(w, "%s %s v%d ready\n", project(g), handle, version.N)
204 if generated {
205 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)
206 }
207 return nil
208}
209
210func runWithdraw(g git, args []string, w io.Writer) error {
211 if len(args) != 1 {
212 return failure("usage: valley withdraw <change>")
213 }
214 if !g.succeeds(true, "rev-parse", "--git-dir") {
215 return failure("not a git repository")
216 }
217 name := args[0]
218 o, err := listOrigin(g, append([]string{"refs/heads/" + strings.TrimPrefix(name, "origin/")}, recordPatterns...)...)
219 if err != nil {
220 return err
221 }
222 n, found, err := lookup(g, o, name)
223 if err != nil {
224 return err
225 }
226 if !found {
227 if n, err = onBranch(g, o, strings.TrimPrefix(name, "origin/")); err != nil {
228 return err
229 }
230 }
231 handle := o.handle(n.id)
232 if n.record.State != change.Ready {
233 return failure(fmt.Sprintf("%s is withdrawn already; ready a new version to bring it back", handle))
234 }
235 if n.record.Seq >= change.MaxSeq {
236 return failure(fmt.Sprintf("%s's record has been updated %d times, the most a record may be", handle, n.record.Seq))
237 }
238 after := *n.record
239 after.State, after.Seq = change.Withdrawn, n.record.Seq+1
240 message := fmt.Sprintf("valley withdraw: %s\n\nChange %s, withdrawn at version %d.", handle, n.id, after.Active)
241 commit, err := writeRecord(g, &after, message, n.commit)
242 if err != nil {
243 return err
244 }
245 if err := pushRecord(g, n.id, n.commit, commit); err != nil {
246 return err
247 }
248 fmt.Fprintf(w, "%s %s v%d withdrawn\n", project(g), handle, after.Active)
249 return nil
250}
251
252// onBranch is the change whose active version is on branch, for a change
253// named by its branch. Every record on origin is read to find it.
254func onBranch(g git, o origin, branch string) (recorded, error) {
255 ids := o.changes()
256 var commits []string
257 for _, id := range ids {
258 commits = append(commits, o.refs[change.Ref(recordTarget, id)])
259 }
260 if err := fetch(g, commits...); err != nil {
261 return recorded{}, err
262 }
263 var found []recorded
264 for i, id := range ids {
265 r, err := readRecord(g, commits[i])
266 if err != nil {
267 return recorded{}, err
268 }
269 if r.ActiveVersion().Branch == branch {
270 found = append(found, recorded{id: id, commit: commits[i], record: r})
271 }
272 }
273 switch len(found) {
274 case 0:
275 return recorded{}, failure(fmt.Sprintf("no change on origin is named %s or has its active version on that branch", branch))
276 case 1:
277 return found[0], nil
278 }
279 var handles []string
280 for _, n := range found {
281 handles = append(handles, change.Handle(n.id, ids))
282 }
283 return recorded{}, failure(fmt.Sprintf("the changes %s all have their active version on %s; name one by its handle",
284 strings.Join(handles, ", "), branch))
285}
286
287// checkRange refuses a change whose commits are not one line: the range
288// from the merge base of origin's main and the head, to the head, must hold
289// no merge commit, and the merge base must be one commit.
290func checkRange(g git, tip, head string) error {
291 out, err := g.output(true, "merge-base", "--all", tip, head)
292 bases := strings.Fields(out)
293 switch {
294 case err != nil && len(bases) == 0:
295 return failure(fmt.Sprintf("%s shares no history with origin's %s, so it is no change to it", short(head), recordTarget))
296 case len(bases) > 1:
297 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))
298 }
299 merges, err := g.output(true, "rev-list", "--min-parents=2", bases[0]+".."+head)
300 if err != nil {
301 return failure("could not read the commits from origin's " + recordTarget + " to " + short(head))
302 }
303 if merges != "" {
304 first := strings.Fields(merges)[0]
305 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)))
306 }
307 return nil
308}
309
310// changeID is the change's ID: --change when given, then the head
311// commit's change-id header, as jj writes it, then a Change-Id trailer in
312// its message, and otherwise a new ID. Both the header and the trailer are
313// read whatever the source, and either one malformed, or the two
314// disagreeing, is refused. IDs on the other commits of the change are
315// their own provenance and are not read.
316func changeID(g git, head, flag string) (id string, generated bool, err error) {
317 header, trailer, err := headIDs(g, head)
318 if err != nil {
319 return "", false, err
320 }
321 switch {
322 case header != "" && trailer != "" && header != trailer:
323 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))
324 case flag != "":
325 if !change.ValidID(flag) {
326 return "", false, failure("--change takes a change ID, 32 letters from k to z, and " + flag + " is not one")
327 }
328 return flag, false, nil
329 case header != "":
330 return header, false, nil
331 case trailer != "":
332 return trailer, false, nil
333 }
334 id, err = change.NewID()
335 if err != nil {
336 return "", false, failure("could not make a change ID: " + err.Error())
337 }
338 return id, true, nil
339}
340
341// headIDs reads the change IDs a commit carries: the change-id header in
342// the commit object itself, never text in its message, and the Change-Id
343// trailer, as git interpret-trailers parses the message.
344func headIDs(g git, head string) (header, trailer string, err error) {
345 raw, err := g.output(true, "cat-file", "commit", head)
346 if err != nil {
347 return "", "", failure("could not read the commit " + short(head))
348 }
349 headers, message, _ := strings.Cut(raw, "\n\n")
350 var found []string
351 for _, line := range strings.Split(headers, "\n") {
352 // A line opening with a space continues the header above it.
353 if v, ok := strings.CutPrefix(line, "change-id "); ok {
354 found = append(found, v)
355 }
356 }
357 switch {
358 case len(found) > 1:
359 return "", "", failure(short(head) + " has more than one change-id header")
360 case len(found) == 1 && !change.ValidID(found[0]):
361 return "", "", failure(fmt.Sprintf("%s has the change-id header %q, which is not a change ID", short(head), found[0]))
362 case len(found) == 1:
363 header = found[0]
364 }
365
366 parsed, err := g.input(true, strings.NewReader(message), "interpret-trailers", "--parse")
367 if err != nil {
368 return "", "", failure("could not read the trailers of " + short(head))
369 }
370 found = nil
371 for _, line := range strings.Split(parsed, "\n") {
372 key, value, ok := strings.Cut(line, ":")
373 if ok && strings.EqualFold(strings.TrimSpace(key), "Change-Id") {
374 found = append(found, strings.TrimSpace(value))
375 }
376 }
377 switch {
378 case len(found) > 1:
379 return "", "", failure(short(head) + " has more than one Change-Id trailer")
380 case len(found) == 1 && !change.ValidID(found[0]):
381 return "", "", failure(fmt.Sprintf("%s has the Change-Id trailer %q, which is not a change ID", short(head), found[0]))
382 case len(found) == 1:
383 trailer = found[0]
384 }
385 return header, trailer, nil
386}
387
388// stamp amends the head of the local branch to carry the change ID as a
389// Change-Id trailer, and pushes the branch so that the amended head is on
390// origin. It returns the amended head, or the head as it was when it
391// carries the trailer already.
392//
393// Amending rewrites a commit, which is harmless only while nobody else can
394// have it. So stamp refuses a head that is on origin already, unless the
395// change is the user's own: its record names the user as owner. It refuses
396// a local branch that is behind origin's or has diverged from it too,
397// since pushing the amended head would drop commits origin holds.
398func stamp(g git, branch, head, remote, tip, id string, own bool) (string, error) {
399 _, trailer, err := headIDs(g, head)
400 if err != nil {
401 return "", err
402 }
403 if trailer == id {
404 return head, nil
405 }
406 if trailer != "" {
407 return "", failure(fmt.Sprintf("%s carries the Change-Id trailer %s already, and --stamp would add %s", short(head), trailer, id))
408 }
409 onBranch := remote != "" && g.succeeds(true, "merge-base", "--is-ancestor", head, remote)
410 inTarget := g.succeeds(true, "merge-base", "--is-ancestor", head, tip)
411 switch {
412 case onBranch && head != remote:
413 return "", failure(fmt.Sprintf("origin's %s is ahead of yours; bring yours up to date before stamping its head", branch))
414 case remote != "" && !onBranch && !g.succeeds(true, "merge-base", "--is-ancestor", remote, head):
415 return "", failure(fmt.Sprintf("your %s and origin's have diverged; --stamp would drop what origin holds", branch))
416 case (onBranch || inTarget) && !own:
417 return "", failure(fmt.Sprintf("%s is on origin already, and the change is not yours, so --stamp will not rewrite it; ready it with --change %s instead", short(head), id))
418 }
419
420 raw, err := g.output(true, "cat-file", "commit", head)
421 if err != nil {
422 return "", failure("could not read the commit " + short(head))
423 }
424 _, message, _ := strings.Cut(raw, "\n\n")
425 stamped, err := g.input(true, strings.NewReader(message), "interpret-trailers", "--trailer", "Change-Id: "+id)
426 if err != nil {
427 return "", failure("could not add the Change-Id trailer to " + short(head))
428 }
429 // The amended commit keeps the head's tree, parents and author, as
430 // git commit --amend does. The committer is whoever stamps it.
431 who, err := g.output(true, "log", "-1", "--date=raw", "--format=%an%x00%ae%x00%ad%x00%T%x00%P", head)
432 if err != nil {
433 return "", failure("could not read the commit " + short(head))
434 }
435 f := strings.Split(who, "\x00")
436 if len(f) != 5 {
437 return "", failure("could not read the commit " + short(head))
438 }
439 args := []string{"commit-tree", f[3]}
440 for _, p := range strings.Fields(f[4]) {
441 args = append(args, "-p", p)
442 }
443 amend := g
444 amend.env = append(append([]string(nil), g.env...),
445 "GIT_AUTHOR_NAME="+f[0], "GIT_AUTHOR_EMAIL="+f[1], "GIT_AUTHOR_DATE=@"+f[2])
446 amended, err := amend.input(false, strings.NewReader(stamped+"\n"), append(args, "-F", "-")...)
447 if err != nil {
448 return "", failure("could not write the amended commit")
449 }
450 if _, err := g.output(false, "update-ref", "-m", "valley ready --stamp", "refs/heads/"+branch, amended, head); err != nil {
451 return "", failure("could not move your " + branch + " to the amended head")
452 }
453 _, err = g.output(false, "push", "--quiet", "--force-with-lease=refs/heads/"+branch+":"+remote,
454 "origin", amended+":refs/heads/"+branch)
455 if err != nil {
456 return "", failure(fmt.Sprintf("your %s carries the stamped head %s, and origin did not take it", branch, short(amended)))
457 }
458 return amended, nil
459}
460
461func isHexPrefix(s string) bool {
462 if len(s) < 4 || len(s) > 40 {
463 return false
464 }
465 for _, c := range []byte(s) {
466 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
467 return false
468 }
469 }
470 return true
471}