gunk-dev/the-valley

record.go

source111eb193e549main's published tip history
13.3 KiB
1// Writing a change's record on origin, and adding a version to it.
2//
3// A record is written as a commit holding record.json, and pushed to the
4// change's record ref leased on the record commit that was read. The
5// push's outcome is read from git's porcelain report, so a push origin
6// refused is told apart from one whose outcome is unknown, as after a lost
7// connection. The record commit is kept either way: a caller that cannot
8// tell whether origin took it can compare origin's ref with it later.
9
10package rebase
11
12import (
13 "bytes"
14 "context"
15 "errors"
16 "fmt"
17 "os/exec"
18 "strings"
19
20 "the-valley/change"
21)
22
23// WriteRecord writes a record commit holding r, with the parents given,
24// and returns its ID. Its tree holds record.json alone, as a plain file,
25// which is the only shape the hook accepts.
26func WriteRecord(ctx context.Context, g Git, r *change.Record, message string, parents ...string) (string, error) {
27 data, err := change.Encode(r)
28 if err != nil {
29 return "", err
30 }
31 if len(data) > change.MaxRecordBlob {
32 return "", fmt.Errorf("the change's record would be %d bytes, more than the %d a record may be", len(data), change.MaxRecordBlob)
33 }
34 blob, err := g.input(ctx, false, bytes.NewReader(data), "hash-object", "-w", "--stdin")
35 if err != nil {
36 return "", errors.New("could not write the record")
37 }
38 tree, err := g.input(ctx, false, strings.NewReader("100644 blob "+blob+"\trecord.json\n"), "mktree")
39 if err != nil {
40 return "", errors.New("could not write the record's tree")
41 }
42 args := []string{"commit-tree", tree}
43 for _, p := range parents {
44 args = append(args, "-p", p)
45 }
46 commit, err := g.input(ctx, false, strings.NewReader(message+"\n"), append(args, "-F", "-")...)
47 if err != nil {
48 return "", errors.New("could not write the record commit")
49 }
50 return commit, nil
51}
52
53// Push is what became of a ref a push asked origin to move.
54type Push int
55
56const (
57 Unpushed Push = iota // no push was made
58 Refused // origin refused it, and the ref did not move
59 Pushed // origin took it
60 Unknown // the push failed, and whether origin took it is not known
61)
62
63func (p Push) String() string {
64 switch p {
65 case Refused:
66 return "refused"
67 case Pushed:
68 return "pushed"
69 case Unknown:
70 return "unknown"
71 }
72 return "unpushed"
73}
74
75// RefusedRef is a ref origin refused, and git's reason, as its porcelain
76// report gives it.
77type RefusedRef struct {
78 Ref, Why string
79}
80
81// push runs one push to origin, with --porcelain and the arguments given,
82// and reads what became of it: Pushed when git exits zero; Refused, with
83// each ref git reports refused, when it reports any; and otherwise
84// Unknown, since with no ref reported the push may have reached origin
85// before it failed. No push is made under a context already done.
86func push(ctx context.Context, g Git, args ...string) (Push, []RefusedRef) {
87 if ctx.Err() != nil {
88 return Unpushed, nil
89 }
90 cmd := exec.CommandContext(ctx, "git", append([]string{"push", "--porcelain"}, args...)...)
91 cmd.Env, cmd.Dir, cmd.Stderr = g.Env, g.Dir, g.Stderr
92 out, err := cmd.Output()
93 switch {
94 case err == nil:
95 return Pushed, nil
96 case cmd.Process == nil:
97 return Unpushed, nil
98 }
99 var refused []RefusedRef
100 for _, line := range strings.Split(string(out), "\n") {
101 f := strings.SplitN(line, "\t", 3)
102 if len(f) == 3 && f[0] == "!" {
103 _, to, _ := strings.Cut(f[1], ":")
104 refused = append(refused, RefusedRef{Ref: to, Why: f[2]})
105 }
106 }
107 if len(refused) > 0 {
108 return Refused, refused
109 }
110 return Unknown, nil
111}
112
113// RecordWrite is a record commit pushed to a change's record ref, and what
114// became of the push.
115type RecordWrite struct {
116 Ref string // the change's record ref
117 Old string // the record commit the push was leased on; "" for a record that did not exist
118 Commit string // the record commit written
119 Push Push
120 Why string // git's reason, when origin refused it
121}
122
123// PushRecord moves the change's record ref on origin from old to commit,
124// leased on old: the push is refused if the ref has moved since it was
125// read, and a record that did not exist must still not exist. The hook's
126// refusal reaches Stderr through git.
127func PushRecord(ctx context.Context, g Git, id, old, commit string) RecordWrite {
128 ref := change.Ref(Target, id)
129 w := RecordWrite{Ref: ref, Old: old, Commit: commit}
130 var refused []RefusedRef
131 w.Push, refused = push(ctx, g, "--quiet", "--force-with-lease="+ref+":"+old, "origin", commit+":"+ref)
132 if len(refused) > 0 {
133 w.Why = refused[0].Why
134 }
135 return w
136}
137
138// CheckRange refuses a change whose commits are not one line: the range
139// from the merge base of origin's main and the head, to the head, must hold
140// no merge commit, and the merge base must be one commit.
141func CheckRange(ctx context.Context, g Git, tip, head string) error {
142 out, err := g.output(ctx, true, "merge-base", "--all", tip, head)
143 bases := strings.Fields(out)
144 switch {
145 case err != nil && len(bases) == 0:
146 return fmt.Errorf("%s shares no history with origin's %s, so it is no change to it", short(head), Target)
147 case len(bases) > 1:
148 return fmt.Errorf("%s has %d merge bases with origin's %s, so the commits of the change are ambiguous", short(head), len(bases), Target)
149 }
150 merges, err := g.output(ctx, true, "rev-list", "--min-parents=2", bases[0]+".."+head)
151 if err != nil {
152 return fmt.Errorf("could not read the commits from origin's %s to %s", Target, short(head))
153 }
154 if merges != "" {
155 first := strings.Fields(merges)[0]
156 return fmt.Errorf("the commits from origin's %s to %s include the merge %s, and a change is a line of commits", Target, short(head), short(first))
157 }
158 return nil
159}
160
161// HeadIDs reads the change IDs a commit carries: the change-id header in
162// the commit object itself, never text in its message, and the Change-Id
163// trailer, as git interpret-trailers parses the message.
164func HeadIDs(ctx context.Context, g Git, head string) (header, trailer string, err error) {
165 raw, err := g.output(ctx, true, "cat-file", "commit", head)
166 if err != nil {
167 return "", "", errors.New("could not read the commit " + short(head))
168 }
169 headers, message, _ := strings.Cut(raw, "\n\n")
170 var found []string
171 for _, line := range strings.Split(headers, "\n") {
172 // A line opening with a space continues the header above it.
173 if v, ok := strings.CutPrefix(line, "change-id "); ok {
174 found = append(found, v)
175 }
176 }
177 switch {
178 case len(found) > 1:
179 return "", "", errors.New(short(head) + " has more than one change-id header")
180 case len(found) == 1 && !change.ValidID(found[0]):
181 return "", "", fmt.Errorf("%s has the change-id header %q, which is not a change ID", short(head), found[0])
182 case len(found) == 1:
183 header = found[0]
184 }
185
186 parsed, err := g.input(ctx, true, strings.NewReader(message), "interpret-trailers", "--parse")
187 if err != nil {
188 return "", "", errors.New("could not read the trailers of " + short(head))
189 }
190 found = nil
191 for _, line := range strings.Split(parsed, "\n") {
192 key, value, ok := strings.Cut(line, ":")
193 if ok && strings.EqualFold(strings.TrimSpace(key), "Change-Id") {
194 found = append(found, strings.TrimSpace(value))
195 }
196 }
197 switch {
198 case len(found) > 1:
199 return "", "", errors.New(short(head) + " has more than one Change-Id trailer")
200 case len(found) == 1 && !change.ValidID(found[0]):
201 return "", "", fmt.Errorf("%s has the Change-Id trailer %q, which is not a change ID", short(head), found[0])
202 case len(found) == 1:
203 trailer = found[0]
204 }
205 return header, trailer, nil
206}
207
208// CheckActive refuses to add a version unless the change is ready at an
209// active version whose head is ifActive, as `valley ready --if-active`
210// does. before is the record as read, or nil for none.
211func CheckActive(handle string, before *change.Record, ifActive string) error {
212 switch {
213 case before == nil:
214 return fmt.Errorf("--if-active %s: origin holds no record of %s, so no version is added", short(ifActive), handle)
215 case before.State != change.Ready:
216 return fmt.Errorf("%s is %s, not ready, so no version is added: --if-active adds one only while the change is ready", handle, before.State)
217 case HeadOf(before.ActiveVersion()) != ifActive:
218 return fmt.Errorf("%s v%d is at %s, not %s, so no version is added", handle, before.Active, short(HeadOf(before.ActiveVersion())), short(ifActive))
219 }
220 return nil
221}
222
223// NextRecord is before with v added as its next version, active and
224// ready, numbered after its last. It refuses a change ready at v's head
225// already, and a record that has as many versions, or has been updated as
226// many times, as a record may be.
227func NextRecord(handle string, before *change.Record, v change.Version) (*change.Record, error) {
228 active := before.ActiveVersion()
229 switch {
230 case active.Head == v.Head && before.State == change.Ready:
231 return nil, fmt.Errorf("%s v%d is at %s already; a new version needs a new head", handle, active.N, short(HeadOf(v)))
232 case active.Head != v.Head && len(before.Versions) >= change.MaxVersions:
233 return nil, fmt.Errorf("%s has %d versions, the most a change may have", handle, len(before.Versions))
234 case before.Seq >= change.MaxSeq:
235 return nil, fmt.Errorf("%s's record has been updated %d times, the most a record may be", handle, before.Seq)
236 }
237 after := *before
238 v.N = before.Last().N + 1
239 after.Versions = append(append([]change.Version(nil), before.Versions...), v)
240 after.Active, after.State, after.Seq = v.N, change.Ready, before.Seq+1
241 return &after, nil
242}
243
244// ReadyMessage is the message of a record commit that readies a version.
245func ReadyMessage(handle, id string, n int, head string) string {
246 return fmt.Sprintf("valley ready: %s v%d\n\nChange %s, version %d, at %s.", handle, n, id, n, head)
247}
248
249// Append is a version to add to a change's record, as
250// `valley ready --if-active <IfActive> --head <Head> --change <ID> <Branch>`
251// adds it.
252type Append struct {
253 ID string // the change
254 Branch string // the branch the version names; Head must be on it on origin
255 Head string // the head the version records, as a full object ID
256 IfActive string // the head the change must still be ready at
257 Principal string // the principal the push authenticates as, named as the version's uploader
258}
259
260// Appended is what became of an Append.
261type Appended struct {
262 Handle string // the change's handle on origin
263 Version int // the version added; 0 when none was
264 Write RecordWrite // the record commit and what became of its push; Write.Commit is "" when none was written
265 Err error // why no version was added; nil when one was
266}
267
268// AppendVersion adds a.Head to the change's record as its next version,
269// only while the change is still ready at a.IfActive. It reads the record
270// and pushes the new one leased on the record it read, so nothing can
271// unready the change or ready another version between that check and the
272// write.
273func AppendVersion(ctx context.Context, g Git, a Append) Appended {
274 ap := Appended{}
275 ap.Err = func() error {
276 switch {
277 case !change.ValidPrincipal(a.Principal):
278 return fmt.Errorf("%q is not a principal's name", a.Principal)
279 case !change.ValidBranch(a.Branch):
280 return errors.New("not a branch name: " + a.Branch)
281 case !change.ValidID(a.ID):
282 return fmt.Errorf("%q is not a change ID", a.ID)
283 case !IsObjectID(a.Head) || !IsObjectID(a.IfActive):
284 return errors.New("a version is added at a head given as a full object ID, while the change is at another given the same way")
285 }
286 o, err := ListOrigin(ctx, g, append([]string{"refs/heads/" + Target, "refs/heads/" + a.Branch}, RecordPatterns...)...)
287 if err != nil {
288 return err
289 }
290 tip, remote := o.Refs["refs/heads/"+Target], o.Refs["refs/heads/"+a.Branch]
291 if tip == "" {
292 return errors.New("origin has no " + Target + " branch, so a change has nothing to target")
293 }
294 if err := Fetch(ctx, g, tip, remote); err != nil {
295 return err
296 }
297 head, err := g.output(ctx, true, "rev-parse", "--verify", "--quiet", a.Head+"^{commit}")
298 if err != nil || remote == "" || !g.succeeds(ctx, true, "merge-base", "--is-ancestor", head, remote) {
299 return errors.New(a.Head + " is not on origin's " + a.Branch + "; push it there first")
300 }
301 if err := CheckRange(ctx, g, tip, head); err != nil {
302 return err
303 }
304 header, trailer, err := HeadIDs(ctx, g, head)
305 if err != nil {
306 return err
307 }
308 if header != "" && trailer != "" && header != trailer {
309 return fmt.Errorf("%s has the change-id header %s and the Change-Id trailer %s, and they must agree", short(head), header, trailer)
310 }
311 ref := change.Ref(Target, a.ID)
312 old := o.Refs[ref]
313 var before *change.Record
314 if old != "" {
315 if err := Fetch(ctx, g, old); err != nil {
316 return err
317 }
318 if before, err = ReadRecord(ctx, g, old); err != nil {
319 return err
320 }
321 }
322 ap.Handle = o.Handle(a.ID)
323 if err := CheckActive(ap.Handle, before, a.IfActive); err != nil {
324 return err
325 }
326 subject, err := g.output(ctx, true, "log", "-1", "--format=%s", head)
327 if err != nil {
328 return errors.New("could not read the subject of " + short(head))
329 }
330 after, err := NextRecord(ap.Handle, before, change.Version{
331 Head: change.HeadPrefix + head, Title: change.Title(subject), Branch: a.Branch, Uploader: a.Principal,
332 })
333 if err != nil {
334 return err
335 }
336 commit, err := WriteRecord(ctx, g, after, ReadyMessage(ap.Handle, a.ID, after.Active, head), old, head)
337 if err != nil {
338 return err
339 }
340 ap.Write = PushRecord(ctx, g, a.ID, old, commit)
341 if ap.Write.Push != Pushed {
342 return errors.New("origin did not take the record of " + a.ID)
343 }
344 ap.Version = after.Active
345 return nil
346 }()
347 return ap
348}