gunk-dev/the-valley

status.go

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