gunk-dev/the-valley

main.go

source57b716740065main's published tip history
12.6 KiB
1// valley-go is the part of the valley command written in Go: the verbs
2// that read a change's state from origin, and the verbs that write its
3// change record there. bin/valley runs it for status, ready, unready and
4// withdraw, for changes and pending, which list every change across the
5// repositories a host serves, for review, which pages a change or a stack
6// for the operator's answer, and with no change walks what needs the
7// operator (review.go, walk.go), for approve, for
8// rebase, which rebases a change's whole stack onto main, and brings, which
9// lists the changes a head would bring that have not landed, for approve
10// (rebase.go), for knot, the plan graph's API (knot.go), which reads and
11// writes a project's knots at refs/the-valley/knots, for plan, which
12// shows that graph as a view (plan.go), and for self-update, which
13// installs the tip of a branch of the-valley into the user's nix profile
14// (selfupdate.go). resolve turns the name of a change into its record or
15// branch (changes.go), stack lists the layers under a change (stack.go),
16// does lists the knots each change does (does.go), checkline says what
17// review shows of a change's checks and their build times
18// (versionchecks.go), and compare sets a version review shows against the
19// change's approved version (compare.go); review calls each, and runs
20// checkline as a background process while the operator reads. checks prints
21// which checks a change requires, as the Go deriver derives them
22// (checks.go); no verb of bin/valley runs it. coverage says which of a
23// head's required nix checks already have evidence on origin that approve
24// can reuse rather than build (coverage.go), and verdict prints what
25// approve and review's prompt say (verdict.go). work is one pass of a check
26// worker, which builds and publishes that evidence for ready changes
27// before they are approved (worker.go); no verb of bin/valley runs it.
28//
29// status reads one change's integration status (status.go). changes and
30// pending read every record and how far each version has landed
31// (inventory.go, pending.go). ready,
32// unready and withdraw write the change's record,
33// refs/the-valley/changes/main/<change ID> (ready.go), in the format the
34// change module defines and the push hook guards. The integrator reads
35// records only to refuse: it lands no request that would bring a version
36// of a change that is not ready, and it voids a withdrawn change's
37// requests. The integration request stays the only way
38// to main. versions lists a change's versions, for approve, and standing
39// says where a change stands now, for review (standing.go). carry says
40// whether review's answer about the version it showed carries to the
41// version the change moved to (carry.go). style styles review's page for
42// a terminal (style.go).
43//
44// A change is named by its full change ID, by its handle (the shortest
45// prefix of the ID, four letters at least, that no other change on origin
46// shares), or by its branch (changes.go).
47package main
48
49import (
50 "errors"
51 "fmt"
52 "io"
53 "os"
54 "os/exec"
55 "strings"
56 "time"
57
58 "the-valley/rebase"
59)
60
61const usage = `usage: valley-go status [--json] [-v] <change>
62 valley-go ready [--head <sha>] [--change <id>] [--if-active <sha>] [--stamp] [<branch>]
63 valley-go unready <change>
64 valley-go withdraw <change>
65 valley-go review [-v] [--build-here] [<change> | --repo <name>]
66 valley-go resolve <change>
67 valley-go stack <change>
68 valley-go does [-v] <change ID>...
69 valley-go checkline <change ID>...
70 valley-go rebase [--head <sha>] <change>
71 valley-go standing <change ID>
72 valley-go compare [-v] --tip <commit> <change ID> <version> <head>
73 valley-go carry <change ID> <version shown> <later version>
74 valley-go style [--paged] < page
75 valley-go checks [--schema <file>] --instance <dir> --project <dir> <base> <head>
76 valley-go approve [-v] [--head <sha>] [--build-here] <change>
77 valley-go verdict prompt <clause>... -- <key>...
78 valley-go work --repo <name>... --key <file> [--name <name>] [--state <dir>]
79 valley-go changes --json [--all] [--repo <name>] [-v]
80 valley-go pending [--json] [--all] [--repo <name>] [--checks] [-v]
81 valley-go walk [--repo <name>] [-v] [--build-here]
82 valley-go knot <verb> [args] (valley-go knot for its verbs)
83 valley-go plan [--project <name> | --all] [--owner <name>] [--json]
84 valley-go self-update [-v] [--retry | --rollback | --pin | --unpin] [--repo <url>] [--branch <name>]
85
86status, stack, rebase, brings, changes, pending, walk and plan read how far a
87version has landed, and also take --known-signers <file> and
88--integrator-name <name>: what an integrator's transfer statement is
89verified with, ahead of VALLEY_KNOWN_SIGNERS, VALLEY_INTEGRATOR_SIGNER and
90what the serving host publishes at refs/the-valley/signers.`
91
92func main() {
93 // A verb bin/valley execs this program for records its command record
94 // once it has run (command.go).
95 inv := execed(os.Args[1:])
96 exitWith = func(status int) {
97 inv.record(status, commandTimed)
98 os.Exit(status)
99 }
100 status := run(os.Args[1:], os.Stdout, os.Stderr)
101 inv.record(status, commandTimed)
102 os.Exit(status)
103}
104
105// commandTimed is whether the command record holds each phase's time.
106// A review of one change clears it: its time is the operator's reading,
107// which no phase of the program accounts for.
108var commandTimed = true
109
110// failure is a verb that ends without doing what it was asked: a message
111// for stderr and nothing on stdout. Exit status 1, as bin/valley's die
112// gives.
113type failure string
114
115func (f failure) Error() string { return string(f) }
116
117func run(args []string, stdout, stderr io.Writer) int {
118 g := git{env: gitEnvironment(os.Environ()), stderr: stderr}
119 verb := ""
120 if len(args) > 0 {
121 verb, args = args[0], args[1:]
122 }
123 // What this run verifies a transfer statement with (signers.go). Only
124 // the verbs that read how far a version has landed take the flags.
125 verification = &signerSource{g: g, stderr: stderr}
126 defer verification.done()
127 if signerVerbs[verb] {
128 var err error
129 if args, verification.keys, verification.name, err = takeSignerFlags(args); err != nil {
130 fmt.Fprintf(stderr, "valley: %s\n", err)
131 return 1
132 }
133 }
134 var err error
135 switch verb {
136 case "status":
137 return runStatus(g, args, stdout, stderr)
138 case "ready":
139 err = runReady(g, args, stdout)
140 case "unready":
141 err = runUnready(g, args, stdout, stderr)
142 case "withdraw":
143 err = runWithdraw(g, args, stdout, stderr)
144 case "resolve":
145 err = runResolve(g, args, stdout)
146 case "stack":
147 err = runStack(g, args, stdout)
148 case "does":
149 err = runDoes(g, args, stdout, stderr)
150 case "checkline":
151 err = runCheckLine(g, args, stdout, stderr)
152 case "rebase":
153 return runRebase(g, args, stdout, stderr)
154 case "standing":
155 err = runStanding(g, args, stdout)
156 case "compare":
157 err = runCompare(g, args, stdout)
158 case "carry":
159 err = runCarry(g, args, stdout)
160 case "style":
161 err = runStyle(args, os.Stdin, stdout)
162 case "checks":
163 err = runChecks(g, args, stdout)
164 case "approve":
165 return runApprove(g, args, stdout, stderr)
166 case "verdict":
167 return runVerdict(args, stdout, stderr)
168 case "changes":
169 err = runChanges(g, args, stdout, stderr)
170 case "pending":
171 err = runPending(g, args, stdout, stderr)
172 case "review":
173 return runReview(g, args, stdout, stderr)
174 case "walk":
175 return runWalk(g, args, stdout, stderr)
176 case "telemetry":
177 err = runTelemetry(g, args, stdout, stderr)
178 case "self-update":
179 return runSelfUpdate(args, stdout, stderr)
180 case "knot", "plan", "work":
181 if _, err := clockSetting(); err != nil {
182 fmt.Fprintf(stderr, "valley: %s\n", err)
183 return 2
184 }
185 switch verb {
186 case "knot":
187 return runKnot(g, args, os.Stdin, stdout, stderr)
188 case "plan":
189 err = runPlan(g, args, stdout, stderr)
190 default:
191 err = runWork(g, args, stdout, stderr)
192 var unclaimed claimFailure
193 if errors.As(err, &unclaimed) {
194 fmt.Fprintf(stderr, "valley: %s\n", err)
195 return claimFailedStatus
196 }
197 }
198 default:
199 fmt.Fprintln(stderr, usage)
200 return 2
201 }
202 if err != nil {
203 fmt.Fprintf(stderr, "valley: %s\n", err)
204 return 1
205 }
206 return 0
207}
208
209// git runs git in a repository, in the environment bin/valley gives every
210// git it runs.
211type git struct {
212 env []string
213 stderr io.Writer // where git's own diagnostics go, unless quiet
214 dir string // the repository's directory; "" for the current one
215}
216
217// engine is g as the rebase engine runs git: in the same repository and
218// environment, with git's own diagnostics on the same stderr.
219func (g git) engine() rebase.Git {
220 return rebase.Git{Dir: g.dir, Env: g.env, Stderr: g.stderr, Phase: phase, Started: processStarted}
221}
222
223// gitEnvironment is the caller's environment with replacement refs off.
224// A replacement ref makes one object stand in for another wherever git
225// looks it up, so a fetched or planted refs/replace/* could change which
226// commit this read takes for a change's head. git is told to ignore them,
227// and the variables that point it at other objects or at another
228// replacement namespace are dropped. The person's own configuration is
229// kept: reaching origin needs it, and it does not change what an object
230// id reads as once replacement refs are off.
231func gitEnvironment(inherited []string) []string {
232 var kept []string
233 for _, kv := range inherited {
234 name, _, _ := strings.Cut(kv, "=")
235 switch name {
236 case "GIT_NO_REPLACE_OBJECTS", "GIT_REPLACE_REF_BASE", "GIT_GRAFT_FILE",
237 "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES":
238 continue
239 }
240 kept = append(kept, kv)
241 }
242 return append(kept, "GIT_NO_REPLACE_OBJECTS=1")
243}
244
245// output runs git and returns what it printed, less trailing newlines, as
246// a shell's command substitution reads it. A quiet run discards git's
247// diagnostics; any other passes them on.
248func (g git) output(quiet bool, args ...string) (string, error) {
249 return g.input(quiet, nil, args...)
250}
251
252// input is output with stdin.
253func (g git) input(quiet bool, stdin io.Reader, args ...string) (string, error) {
254 processStarted()
255 cmd := exec.Command("git", args...)
256 cmd.Env = g.env
257 cmd.Dir = g.dir
258 cmd.Stdin = stdin
259 if !quiet {
260 cmd.Stderr = g.stderr
261 }
262 out, err := cmd.Output()
263 return strings.TrimRight(string(out), "\n"), err
264}
265
266// succeeds reports whether git exits zero. A failure to run git at all is
267// a no as well, as it is to a shell condition.
268func (g git) succeeds(quiet bool, args ...string) bool {
269 _, err := g.output(quiet, args...)
270 return err == nil
271}
272
273// ref reads the object ID that name, a full ref name, holds. It reads that
274// one ref, with git show-ref. ok is false when there is no ref of that
275// name. An error is a repository git could not read.
276//
277// git rev-parse is not used, because it does not stop at the name it is
278// given. For a missing refs/heads/topic, it goes on to try other names,
279// refs/heads/refs/heads/topic among them.
280func (g git) ref(name string) (oid string, ok bool, err error) {
281 // show-ref --exists exits 2 for a ref that is missing, and with
282 // another status for a failure to read.
283 _, err = g.output(true, "show-ref", "--exists", "--end-of-options", name)
284 var exit *exec.ExitError
285 if errors.As(err, &exit) && exit.ExitCode() == 2 {
286 return "", false, nil
287 } else if err != nil {
288 return "", false, err
289 }
290 oid, err = g.output(true, "show-ref", "--verify", "--hash", "--end-of-options", name)
291 if err != nil {
292 return "", false, err
293 }
294 return oid, true, nil
295}
296
297// clock is the time the knot and plan verbs take as now: the time
298// VALLEY_NOW holds, when it is set, or else the system's clock. A knot's
299// created date, a claim's time and a comment's stamp are written at it,
300// and a claim's age is read against it. Checks set it, so the dates a
301// graph records and the ages a view shows are the same on every run. It
302// grants nothing: the push hook holds none of those times to its own
303// clock, so a writer could record any of them by writing the file. The
304// check worker measures its waits after a failed batch from it too
305// (worker.go).
306func clock() time.Time {
307 if t, err := clockSetting(); err == nil && !t.IsZero() {
308 return t
309 }
310 return time.Now().UTC()
311}
312
313// clockSetting is the time VALLEY_NOW holds, in UTC, or the zero time when
314// it is unset. A value that is no RFC 3339 time is refused.
315func clockSetting() (time.Time, error) {
316 v := os.Getenv("VALLEY_NOW")
317 if v == "" {
318 return time.Time{}, nil
319 }
320 t, err := time.Parse(time.RFC3339, v)
321 if err != nil {
322 return time.Time{}, failure(fmt.Sprintf("VALLEY_NOW is %q, and it takes an RFC 3339 time, such as 2026-10-15T09:30:00Z", v))
323 }
324 return t.UTC(), nil
325}
326
327// exitCode is the status a failed git exited with, for passing it on.
328func exitCode(err error) int {
329 var exit *exec.ExitError
330 if errors.As(err, &exit) && exit.ExitCode() > 0 {
331 return exit.ExitCode()
332 }
333 return 1
334}