gunk-dev/the-valley

status.go

sourced5649addb600main's published tip history
14.5 KiB
1// status reads one change's integration status from origin: the change's
2// head, its integration request, and the integrator's last recorded
3// outcome for it. It is `valley status`.
4//
5// A change with a record is read at the head its active version records,
6// under the request name approve files it under, c-<change ID>, and its
7// status carries what its record says and how far its active version has
8// landed. Any other name is a branch, read at its head on origin under the
9// request name approve gives a branch.
10//
11// It writes nothing. The objects it reads are fetched without writing
12// FETCH_HEAD or moving a branch, so a status read leaves the checkout and
13// its working tree exactly as it found them. No check runs and no request
14// is filed.
15//
16// Without flags it prints the sentences an operator reads. With --json it
17// prints one object, valley-status/v1, which is a contract front ends
18// read; docs/architecture.md documents it. Both are rendered from one
19// decision (decide), so the two forms cannot disagree about a change.
20
21package main
22
23import (
24 "crypto/sha256"
25 "encoding/hex"
26 "fmt"
27 "io"
28 "sort"
29 "strings"
30 "unicode/utf8"
31
32 "the-valley/change"
33 "the-valley/rebase"
34)
35
36const statusUsage = "usage: valley status [--json] <change>"
37
38func runStatus(g git, args []string, stdout, stderr io.Writer) int {
39 asJSON, name, err := parseStatusArgs(args)
40 if err == nil && asJSON && !utf8.ValidString(name) {
41 err = failure(name + ": not UTF-8, so JSON cannot carry the change name")
42 }
43 var s *status
44 if err == nil {
45 s, err = readNamed(g, name, stderr)
46 }
47 if err != nil {
48 fmt.Fprintf(stderr, "valley: %s\n", err)
49 return 1
50 }
51 if asJSON {
52 return writeJSON(s, stdout, stderr)
53 }
54 return writeHuman(g, s, stdout)
55}
56
57// parseStatusArgs takes one change and an optional --json, in either
58// order. The change is named the way every verb names one (changes.go).
59func parseStatusArgs(args []string) (asJSON bool, name string, err error) {
60 var rest []string
61 for _, a := range args {
62 if a == "--json" {
63 asJSON = true
64 continue
65 }
66 rest = append(rest, a)
67 }
68 if len(rest) != 1 {
69 return false, "", failure(statusUsage)
70 }
71 return asJSON, rest[0], nil
72}
73
74const (
75 target = "main"
76 requestPrefix = rebase.RequestPrefix
77 outcomePrefix = rebase.OutcomePrefix
78 attestationRefs = rebase.AttestationRefs
79)
80
81// status is what one read of origin found for a change, and the state
82// decide made of it.
83type status struct {
84 branch string // the change's branch: as given, without origin/, or as its record names it
85 change string // the request's name for it (changeName, or c-<change ID>)
86 requestRef string
87 outcomeRef string
88
89 // recorded is what the change's record says, for a change with one,
90 // and nil for a branch.
91 recorded *statusRecord
92
93 tip string // origin's main
94 head string // the change's head as this read knows it; "" for none
95 request string // the commit the integration request names; "" for none
96 outcome string // the outcome record's blob; "" for none
97 memo memo // the outcome record, read; meaningful when outcome is set
98
99 state string
100}
101
102// statusRecord is what a change's record says about its active version,
103// and how far that version has landed (inventory.go).
104type statusRecord struct {
105 id, handle, title, owner, landing string
106 version int
107}
108
109// name is how the status names the change in the commands it suggests:
110// its handle when it has a record, and otherwise its branch.
111func (s *status) name() string {
112 if s.recorded != nil {
113 return s.recorded.handle
114 }
115 return s.branch
116}
117
118// label is how the status names the change in its sentences: its handle
119// and version when it has a record, and otherwise its branch.
120func (s *status) label() string {
121 if s.recorded != nil {
122 return fmt.Sprintf("%s v%d", s.recorded.handle, s.recorded.version)
123 }
124 return s.branch
125}
126
127// readNamed reads the status of a change by any of its names, as review
128// and approve read one (resolveRecorded): a change's ID or handle, or a
129// branch that exactly one record's active version is on. Any other name
130// is a branch.
131func readNamed(g git, name string, stderr io.Writer) (*status, error) {
132 if !g.succeeds(true, "rev-parse", "--git-dir") {
133 return nil, failure("not a git repository")
134 }
135 o, n, found, err := lookupRecorded(g, name)
136 var s *status
137 switch {
138 case err != nil:
139 return nil, err
140 case !found:
141 s, err = read(g, strings.TrimPrefix(name, "origin/"))
142 default:
143 s, err = readRecorded(g, o, n, stderr)
144 }
145 if err != nil {
146 return nil, err
147 }
148 if err := warnUnread(g, o, s, stderr); err != nil {
149 return nil, err
150 }
151 return s, nil
152}
153
154// warnUnread warns of each record on origin that does not read and may
155// name a commit the change's request brings. The integrator lands such a
156// request as though the record did not exist, so whether the record holds
157// it back cannot be checked.
158func warnUnread(g git, o origin, s *status, stderr io.Writer) error {
159 if s.request == "" {
160 return nil
161 }
162 _, unread, err := readAll(g, o)
163 if err != nil {
164 return err
165 }
166 for _, u := range unread {
167 if mayName(g, u, s.request, s.tip) {
168 fmt.Fprintf(stderr, "valley: warning: the change record %s does not read: %s. It may name a commit the request %s brings, and the integrator lands that request as though the record did not exist. The hook refuses such a record, so origin's storage is corrupt\n", u.ref, u.why, s.requestRef)
169 }
170 }
171 return nil
172}
173
174// reservedName refuses a branch whose request name is c-<change ID>.
175// Every such name is reserved for the change with that ID, so a branch
176// mapping to one is never filed or read under it.
177func reservedName(branch string) error {
178 name := changeName(branch)
179 if id, ok := change.RequestID(name); ok {
180 return failure(fmt.Sprintf("the branch %s would be requested as %s, and that name is reserved for the change with the ID %s; rename the branch, or name the change by its ID", branch, name, id))
181 }
182 return nil
183}
184
185// changeName is the change segment of a request ref. The integrator reads
186// a request as <prefix>/<target>/<change> and refuses a change segment
187// holding a slash (integrator/refs.go), so a branch name with one is
188// written with dashes instead. bin/valley's change_name is the same
189// mapping, and the request approve files is named by it.
190func changeName(branch string) string { return rebase.ChangeName(branch) }
191
192// read takes one snapshot of origin and decides the change's state from
193// it. A status read is a snapshot of origin, not a replay of this
194// checkout's cached refs: one ls-remote lists every ref the decision
195// reads, and the objects they name are fetched by id, so the decision is
196// about one moment of origin and never about refs/remotes. Nothing local
197// is pruned, so evidence this checkout produced survives the read.
198func read(g git, branch string) (*status, error) {
199 if !g.succeeds(true, "rev-parse", "--git-dir") {
200 return nil, failure("not a git repository")
201 }
202 if !g.succeeds(true, "check-ref-format", "refs/heads/"+branch) {
203 return nil, failure("not a branch name: " + branch)
204 }
205 if err := reservedName(branch); err != nil {
206 return nil, err
207 }
208 s := &status{branch: branch, change: changeName(branch)}
209 s.requestRef = requestPrefix + s.change
210 s.outcomeRef = outcomePrefix + s.change
211
212 snapshot, err := g.output(false, "ls-remote", "--refs", "origin",
213 "refs/heads/"+branch, "refs/heads/"+target, s.requestRef, s.outcomeRef,
214 attestationRefs+"*")
215 if err != nil {
216 return nil, failure("could not read origin; integration status is unknown. Try valley status " +
217 shellQuote(branch) + " again")
218 }
219 // ls-remote prints "<oid>\t<ref>", and a ref name may hold any space
220 // but ASCII's, so the line is split at the tab alone. ls-remote matches
221 // a pattern against the tail of a ref name, so every ref is compared
222 // whole by settle.
223 refs := map[string]string{}
224 for _, line := range strings.Split(snapshot, "\n") {
225 if oid, ref, ok := strings.Cut(line, "\t"); ok && ref != "" {
226 refs[ref] = oid
227 }
228 }
229 s.head = refs["refs/heads/"+branch]
230 if err := s.settle(g, refs); err != nil {
231 return nil, err
232 }
233 return s, nil
234}
235
236// readRecorded reads a change with a record from the snapshot o its name
237// was resolved in. The change is read at the head its active version
238// records, under its request name, c-<change ID>.
239func readRecorded(g git, o origin, n recorded, stderr io.Writer) (*status, error) {
240 v := n.record.ActiveVersion()
241 name := change.RequestName(n.id)
242 s := &status{
243 branch: v.Branch, change: name, requestRef: requestPrefix + name, outcomeRef: outcomePrefix + name,
244 head: headOf(v),
245 recorded: &statusRecord{
246 id: n.id, handle: o.handle(n.id), version: v.N, title: v.Title, owner: n.record.Owner,
247 },
248 }
249 if s.branch == "" {
250 s.branch = s.recorded.handle
251 }
252 if err := s.settle(g, o.refs); err != nil {
253 return nil, err
254 }
255 // How far the active version has landed, by the rules changes uses.
256 var want []string
257 for ref, oid := range o.refs {
258 if strings.HasPrefix(ref, outcomePrefix) {
259 want = append(want, oid)
260 }
261 }
262 if err := fetch(g, want...); err != nil {
263 return nil, err
264 }
265 snap := newSnapshot(g, o, nil, verifierFromEnv())
266 s.recorded.landing, _ = snap.landing(n.id, v)
267 if snap.unverified() {
268 fmt.Fprintf(stderr, "valley: a transfer statement could not be verified, so %s may have landed though its landing does not say so. %s\n", s.recorded.handle, verifierHint)
269 }
270 return s, nil
271}
272
273// settle reads the request, the outcome record and the evidence from
274// refs, a snapshot of origin, fetches what they name, and decides the
275// change's state. s.head is the change's head as the snapshot knows it,
276// or "" for none.
277func (s *status) settle(g git, refs map[string]string) error {
278 var attestations []string
279 for ref, oid := range refs {
280 switch {
281 case ref == "refs/heads/"+target:
282 s.tip = oid
283 case ref == s.requestRef:
284 s.request = oid
285 case ref == s.outcomeRef:
286 s.outcome = oid
287 case strings.HasPrefix(ref, attestationRefs):
288 attestations = append(attestations, ref+" "+oid)
289 }
290 }
291 if s.tip == "" {
292 return failure("origin has no main branch; integration status is unknown")
293 }
294 if s.head == "" && s.request == "" && s.outcome == "" {
295 return failure(s.branch + ": no remote branch or recorded integration request on origin")
296 }
297 fetch := []string{"fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "origin", s.tip}
298 for _, oid := range []string{s.head, s.request, s.outcome} {
299 if oid != "" {
300 fetch = append(fetch, oid)
301 }
302 }
303 if _, err := g.output(false, fetch...); err != nil {
304 return failure("could not fetch the status objects; origin may have changed. Try valley status " +
305 shellQuote(s.name()) + " again")
306 }
307
308 if s.outcome != "" {
309 record, err := g.output(true, "cat-file", "blob", s.outcome)
310 if err != nil {
311 record = ""
312 }
313 s.memo = parseMemo(record)
314 }
315 // A deleted topic can still have a pending request or a recorded
316 // result. The memo's head stands in only when it is an object id: any
317 // other text would be resolved as a revision of this checkout.
318 if s.head == "" {
319 s.head = s.request
320 }
321 if s.head == "" && isObjectID(s.memo.head) {
322 s.head = s.memo.head
323 }
324 s.state = decide(g, s, evidenceFingerprint(attestations))
325 return nil
326}
327
328// memo is the integrator's outcome record for a request, one line: the
329// head it judged, the target tip it judged that head against, the
330// fingerprint of the evidence it saw, and its decision. A failed pass
331// adds when it failed (integrator/refs.go writes it). The first three are
332// what the integrator compares to decide whether to judge a request again.
333type memo struct {
334 head, tip, evidence string
335 decision string // land, stale, reject, refused-not-ready, refused-merge, voided-withdrawn, failed, or unknown
336 failedAt string // set for failed alone
337}
338
339// parseMemo reads an outcome record, as the rebase engine reads one
340// (rebase.ParseOutcome). Anything it does not recognise is unknown, never
341// a decision.
342func parseMemo(record string) memo { return memoOf(rebase.ParseOutcome(record)) }
343
344// memoOf is an outcome record as status holds one.
345func memoOf(o rebase.Outcome) memo {
346 return memo{head: o.Head, tip: o.Tip, evidence: o.Evidence, decision: o.Decision, failedAt: o.FailedAt}
347}
348
349// isObjectID is a full SHA-1 or SHA-256 object id, lowercase.
350func isObjectID(s string) bool { return rebase.IsObjectID(s) }
351
352// evidenceFingerprint is the evidence state the integrator records in a
353// memo: the first 16 hex digits of the SHA-256 over every attestation ref
354// on origin, one "<ref> <oid>" line each, in byte order. A memo with a
355// different fingerprint was written about other evidence.
356func evidenceFingerprint(attestations []string) string {
357 sorted := append([]string(nil), attestations...)
358 sort.Strings(sorted)
359 h := sha256.New()
360 for _, line := range sorted {
361 h.Write([]byte(line + "\n"))
362 }
363 return hex.EncodeToString(h.Sum(nil))[:16]
364}
365
366// decide names the change's state, one per answer status gives.
367//
368// main is authoritative for a landing, so ancestry is read first: main can
369// advance before the integrator records its outcome, and a failure
370// storing evidence afterwards must not hide an integration already there.
371// A delta applied onto a moved tip lands as a different commit, so a land
372// memo for this head is the next answer. Only after both does a request or
373// a recorded decision speak for the change.
374func decide(g git, s *status, evidence string) string {
375 if s.head != "" && g.succeeds(true, "cat-file", "-e", s.head+"^{commit}") &&
376 g.succeeds(false, "merge-base", "--is-ancestor", s.head, s.tip) {
377 return "integrated"
378 }
379 decision := s.memo.decision // "" when there is no outcome record
380 switch {
381 case decision == "land" && s.memo.head == s.head && (s.request == "" || s.request == s.head):
382 return "integrated-recorded"
383 case s.request != "" && s.request != s.head:
384 return "outdated-request"
385 case decision == "unknown":
386 return "outcome-unreadable"
387 case s.request == "" && decision == "voided-withdrawn" && s.memo.head == s.head:
388 return "voided-withdrawn"
389 case s.request == "":
390 return "not-requested"
391 case decision == "" || s.memo.head != s.head:
392 return "awaiting-decision"
393 case s.memo.tip != s.tip || s.memo.evidence != evidence:
394 return "awaiting-new-decision"
395 }
396 switch decision {
397 case "stale":
398 return "stale"
399 case "reject":
400 return "rejected"
401 case "refused-not-ready", "refused-merge":
402 return decision
403 case "voided-withdrawn":
404 // The request the integrator voided is gone, so one that stands
405 // at the same head is a fresh approval.
406 return "awaiting-decision"
407 case "failed":
408 return "failed"
409 }
410 // A land memo for this head with the request at this head was
411 // integrated-recorded above, and no other decision parses.
412 panic("valley-status: no state for decision " + decision)
413}