gunk-dev/the-valley

status.go

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