gunk-dev/the-valley

status.go

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