gunk-dev/the-valley

status.go

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