gunk-dev/the-valley

status.go

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