gunk-dev/the-valley

status.go

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