gunk-dev/the-valley

main.go

source60ad80d5a5a5main's published tip history
16.6 KiB
1// valley is the command line of a valley project: the public verbs
2// `valley help` lists, each with its help topic (help.go), and the
3// internal verbs the valley's own programs and checks run.
4//
5// status reads one change's integration status (status.go). changes and
6// pending read every record and how far each version has landed
7// (inventory.go, pending.go). ready, unready and withdraw write the
8// change's record, refs/the-valley/changes/main/<change ID> (ready.go), in
9// the format the change module defines and the push hook guards. The
10// integrator reads records only to refuse: it lands no request that would
11// bring a version of a change that is not ready, and it voids a withdrawn
12// change's requests. The integration request stays the only way to main.
13// review pages a change or a stack for the operator's answer, and with no
14// change walks what needs the operator (review.go, walk.go). approve is
15// review's [a]pprove without the pager (approve.go), and rebase its
16// [b]ase, which rebases a change's whole stack onto main (rebase.go). knot
17// is the plan graph's API (knot.go), which reads and writes a project's
18// knots at refs/the-valley/knots, and plan shows that graph as a view
19// (plan.go). checks prints which checks a change requires, as the Go
20// deriver derives them (checks.go). tail and replay watch the bus and
21// fill it from a repository's refs (bus.go). self-update installs the tip
22// of a branch of the-valley into the user's nix profile (selfupdate.go),
23// and telemetry reads a host's diagnostics and sends the workstation's
24// own (telemetry.go).
25//
26// The internal verbs are in neither the usage nor any help topic. resolve
27// turns the name of a change into its record or branch (changes.go), stack
28// lists the layers under a change (stack.go), checkline says what review
29// shows of a change's checks and their build times (versionchecks.go), and
30// style styles review's page for a terminal (style.go): review runs
31// checkline in the background while the operator reads, and style in its
32// pager. work is one pass of a check worker, which builds and publishes
33// the evidence for ready changes before they are approved (worker.go);
34// valley-worker runs it.
35//
36// review reads the rest in process: the knots each change does (does.go),
37// where a change stands now (standing.go), whether its answer carries to
38// the version the change moved to (carry.go), the version it shows set
39// against the change's approved version (compare.go), and the lines
40// approve and its prompt print (verdict.go). coverage says which of a
41// head's required nix checks already have evidence on origin that approve
42// can reuse rather than build (coverage.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 "sync"
57 "time"
58
59 "the-valley/rebase"
60)
61
62func main() {
63 takeEnvironment()
64 // A public verb records its command record once it has run
65 // (command.go), in the current checkout. A verb a signal ends records
66 // it too, through end.
67 inv := commandOf(os.Args[1:])
68 here := git{env: gitEnvironment(os.Environ()), stderr: io.Discard}
69 end := func(status int) {
70 inv.record(here, status, commandTimed)
71 os.Exit(status)
72 }
73 end(cli(os.Args[1:], os.Stdout, os.Stderr, end))
74}
75
76// versionStamp is the version the package stamped on this valley when nix built
77// it (nix/packages.nix): the CLI's version and the commit it was built
78// from, or "" for a build the package did not stamp. --version prints it,
79// self-update reads which commit is installed from it, and telemetry
80// names the producer of its records with it.
81var versionStamp string
82
83// takeEnvironment sets up the environment this process, and every program
84// it starts, runs in. The stamp is taken from VALLEY_VERSION, which is
85// removed, so no program this one starts takes the stamp for its own. git
86// ignores replacement refs, whatever configuration says, and loses the
87// variables that point it at other objects or at another replacement
88// namespace, for the reason gitEnvironment gives.
89func takeEnvironment() {
90 versionStamp = os.Getenv("VALLEY_VERSION")
91 os.Unsetenv("VALLEY_VERSION")
92 os.Setenv("GIT_NO_REPLACE_OBJECTS", "1")
93 for _, name := range []string{"GIT_REPLACE_REF_BASE", "GIT_GRAFT_FILE",
94 "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES"} {
95 os.Unsetenv(name)
96 }
97}
98
99// commandTimed is whether the command record holds each phase's time.
100// A review of one change clears it: its time is the operator's reading,
101// which no phase of the program accounts for.
102var commandTimed = true
103
104// failure is a verb that ends without doing what it was asked: a message
105// for stderr and nothing on stdout. Exit status 1.
106type failure string
107
108func (f failure) Error() string { return string(f) }
109
110// cli runs the valley command line args. No verb at all is help. A public
111// verb given one argument, -h or --help, prints its help topic before
112// anything reads its arguments. pending and rebase read origin's branches
113// through this checkout's remote-tracking refs, so they fetch origin
114// first, and a fetch that fails exits with git's status. end ends the
115// process from a verb a signal interrupts, as run's does.
116func cli(args []string, stdout, stderr io.Writer, end func(int)) int {
117 verb := "help"
118 if len(args) > 0 {
119 verb, args = args[0], args[1:]
120 }
121 if publicVerb(verb) && len(args) == 1 && (args[0] == "-h" || args[0] == "--help") {
122 return runHelp([]string{verb}, stdout, stderr)
123 }
124 g := git{env: gitEnvironment(os.Environ()), stderr: stderr}
125 switch verb {
126 case "help", "-h", "--help":
127 return runHelp(args, stdout, stderr)
128 case "--version":
129 v := versionStamp
130 if v == "" {
131 v = "unstamped (built without the package's version stamp)"
132 }
133 fmt.Fprintf(stdout, "valley %s\n", v)
134 return 0
135 case "tail":
136 return runTail(args, stderr)
137 case "replay":
138 return runReplay(g, args, stdout, stderr)
139 case "pending", "rebase":
140 if verb == "rebase" {
141 var err error
142 if args, err = rebaseCommandArgs(args); err != nil {
143 fmt.Fprintf(stderr, "valley: %s\n", err)
144 return 1
145 }
146 }
147 fetched := phase("fetch")
148 err := fetchOrigin(g, stdout, stderr)
149 fetched()
150 if err != nil {
151 return exitCode(err)
152 }
153 }
154 return run(append([]string{verb}, args...), stdout, stderr, end)
155}
156
157// run runs the verb args name. end ends the process from a verb a signal
158// interrupts, once the verb has cleaned up; it does not return.
159func run(args []string, stdout, stderr io.Writer, end func(int)) int {
160 g := git{env: gitEnvironment(os.Environ()), stderr: stderr}
161 verb := ""
162 if len(args) > 0 {
163 verb, args = args[0], args[1:]
164 }
165 // git runs at the checkout's top level (at), and a checkout whose top
166 // level git cannot say is refused rather than read from here.
167 if _, err := topLevel(g.env); err != nil {
168 fmt.Fprintf(stderr, "valley: %s\n", err)
169 return 1
170 }
171 // What this run verifies a transfer statement with (signers.go). Only
172 // the verbs that read how far a version has landed take the flags.
173 verification = &signerSource{g: g, stderr: stderr}
174 defer verification.done()
175 if signerVerbs[verb] {
176 var err error
177 if args, verification.keys, verification.name, err = takeSignerFlags(args); err != nil {
178 fmt.Fprintf(stderr, "valley: %s\n", err)
179 return 1
180 }
181 }
182 var err error
183 switch verb {
184 case "status":
185 return runStatus(g, args, stdout, stderr)
186 case "ready":
187 err = runReady(g, args, stdout, stderr)
188 case "unready":
189 err = runUnready(g, args, stdout, stderr)
190 case "withdraw":
191 err = runWithdraw(g, args, stdout, stderr)
192 case "resolve":
193 err = runResolve(g, args, stdout)
194 case "stack":
195 err = runStack(g, args, stdout)
196 case "checkline":
197 err = runCheckLine(g, args, stdout, stderr)
198 case "rebase":
199 return runRebase(g, args, stdout, stderr)
200 case "style":
201 err = runStyle(args, os.Stdin, stdout)
202 case "checks":
203 if buildMode(args) {
204 return runCheckBuild(g, args, stdout, stderr)
205 }
206 err = runChecks(g, args, stdout)
207 case checkBuildChild:
208 return runCheckBuildChild(g, args, stdout, stderr)
209 case "approve":
210 return runApprove(g, args, stdout, stderr, end)
211 case "changes":
212 err = runChanges(g, args, stdout, stderr)
213 case "pending":
214 err = runPending(g, args, stdout, stderr)
215 case "review":
216 return runReview(g, args, stdout, stderr, end)
217 case "telemetry":
218 err = runTelemetry(g, args, stdout, stderr)
219 case "self-update":
220 return runSelfUpdate(args, stdout, stderr)
221 case "knot", "plan", "work":
222 if _, err := clockSetting(); err != nil {
223 fmt.Fprintf(stderr, "valley: %s\n", err)
224 return 2
225 }
226 switch verb {
227 case "knot":
228 return runKnot(g, args, os.Stdin, stdout, stderr)
229 case "plan":
230 err = runPlan(g, args, stdout, stderr)
231 default:
232 err = runWork(g, args, stdout, stderr)
233 var unclaimed claimFailure
234 if errors.As(err, &unclaimed) {
235 fmt.Fprintf(stderr, "valley: %s\n", err)
236 return claimFailedStatus
237 }
238 }
239 default:
240 stderr = droppable(stderr)
241 fmt.Fprintf(stderr, "valley: unknown verb: %s\n\n", verb)
242 io.WriteString(stderr, helpPart("usage"))
243 return 1
244 }
245 if err != nil {
246 fmt.Fprintf(stderr, "valley: %s\n", err)
247 return 1
248 }
249 return 0
250}
251
252// git runs git in a repository, in the environment valley gives every git
253// it runs.
254type git struct {
255 env []string
256 stderr io.Writer // where git's own diagnostics go, unless quiet
257 dir string // the repository's directory; "" for the checkout the process runs in
258}
259
260// at is the directory git runs in for g: its repository's directory, or
261// for the checkout the process runs in, the top level of its work tree.
262// git reads some paths against the directory it runs in: ls-tree lists
263// only what a tree holds under it, a pathspec names a path under it, and
264// diff.relative narrows a diff to it. Every path valley gives git or reads
265// from it is from the root of a tree, so git runs at the top level, and a
266// command reads the same from any directory of the checkout. Outside a
267// work tree, as in a bare repository, at is "", the current directory.
268// run refuses a verb in a checkout whose top level git cannot say, so a
269// git that reads from a subdirectory fails closed.
270//
271// Programs other than git run in g.dir: a path they take, such as a
272// key's, is the person's, and reads from where the person is.
273func (g git) at() string {
274 if g.dir != "" {
275 return g.dir
276 }
277 top, _ := topLevel(g.env)
278 return top
279}
280
281// topLevels is what topLevel found for each directory, so git is asked
282// once per directory a process runs in.
283var topLevels = struct {
284 sync.Mutex
285 of map[string]foundTop
286}{of: map[string]foundTop{}}
287
288type foundTop struct {
289 top string
290 err error
291}
292
293// topLevel is the top level of the work tree the current directory is in,
294// or "" when it is in none: in a bare repository, in a git directory, or
295// in no repository at all. It is an error when git says the directory is
296// in a work tree and does not say where its top level is.
297func topLevel(env []string) (string, error) {
298 cwd, err := os.Getwd()
299 if err != nil {
300 return "", fmt.Errorf("could not read the current directory: %v", err)
301 }
302 topLevels.Lock()
303 defer topLevels.Unlock()
304 f, found := topLevels.of[cwd]
305 if !found {
306 f.top, f.err = askTopLevel(env)
307 topLevels.of[cwd] = f
308 }
309 return f.top, f.err
310}
311
312// askTopLevel asks git for the top level of the work tree here, and when
313// git gives none, whether here is in a work tree at all.
314func askTopLevel(env []string) (string, error) {
315 ask := func(args ...string) (string, error) {
316 processStarted()
317 cmd := exec.Command("git", args...)
318 cmd.Env = env
319 out, err := cmd.Output()
320 return strings.TrimSuffix(string(out), "\n"), err
321 }
322 top, err := ask("rev-parse", "--show-toplevel")
323 if err == nil {
324 return top, nil
325 }
326 if inside, ierr := ask("rev-parse", "--is-inside-work-tree"); ierr == nil && inside == "true" {
327 return "", fmt.Errorf("could not find the top level of this checkout: git rev-parse --show-toplevel: %v", err)
328 }
329 return "", nil
330}
331
332// engine is g as the rebase engine runs git: in the same repository and
333// environment, with git's own diagnostics on the same stderr.
334func (g git) engine() rebase.Git {
335 return rebase.Git{Dir: g.at(), Env: g.env, Stderr: g.stderr, Phase: phase, Started: processStarted}
336}
337
338// gitEnvironment is the caller's environment with replacement refs off.
339// A replacement ref makes one object stand in for another wherever git
340// looks it up, so a fetched or planted refs/replace/* could change which
341// commit this read takes for a change's head. git is told to ignore them,
342// and the variables that point it at other objects or at another
343// replacement namespace are dropped. The person's own configuration is
344// kept: reaching origin needs it, and it does not change what an object
345// id reads as once replacement refs are off.
346func gitEnvironment(inherited []string) []string {
347 var kept []string
348 for _, kv := range inherited {
349 name, _, _ := strings.Cut(kv, "=")
350 switch name {
351 case "GIT_NO_REPLACE_OBJECTS", "GIT_REPLACE_REF_BASE", "GIT_GRAFT_FILE",
352 "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES":
353 continue
354 }
355 kept = append(kept, kv)
356 }
357 return append(kept, "GIT_NO_REPLACE_OBJECTS=1")
358}
359
360// command is git run with args in g's repository and environment, at
361// the top level of its work tree (at).
362func (g git) command(args ...string) *exec.Cmd {
363 cmd := g.program("git", args...)
364 cmd.Dir = g.at()
365 return cmd
366}
367
368// program is the program name run with args in g's repository directory
369// and environment, the current directory's when g names none.
370func (g git) program(name string, args ...string) *exec.Cmd {
371 cmd := exec.Command(name, args...)
372 cmd.Env, cmd.Dir = g.env, g.dir
373 return cmd
374}
375
376// output runs git and returns what it printed, less trailing newlines, as
377// a shell's command substitution reads it. A quiet run discards git's
378// diagnostics; any other passes them on.
379func (g git) output(quiet bool, args ...string) (string, error) {
380 return g.input(quiet, nil, args...)
381}
382
383// input is output with stdin.
384func (g git) input(quiet bool, stdin io.Reader, args ...string) (string, error) {
385 processStarted()
386 cmd := g.command(args...)
387 cmd.Stdin = stdin
388 if !quiet {
389 cmd.Stderr = g.stderr
390 }
391 out, err := cmd.Output()
392 return strings.TrimRight(string(out), "\n"), err
393}
394
395// succeeds reports whether git exits zero. A failure to run git at all is
396// a no as well, as it is to a shell condition.
397func (g git) succeeds(quiet bool, args ...string) bool {
398 _, err := g.output(quiet, args...)
399 return err == nil
400}
401
402// ref reads the object ID that name, a full ref name, holds. It reads that
403// one ref, with git show-ref. ok is false when there is no ref of that
404// name. An error is a repository git could not read.
405//
406// git rev-parse is not used, because it does not stop at the name it is
407// given. For a missing refs/heads/topic, it goes on to try other names,
408// refs/heads/refs/heads/topic among them.
409func (g git) ref(name string) (oid string, ok bool, err error) {
410 // show-ref --exists exits 2 for a ref that is missing, and with
411 // another status for a failure to read.
412 _, err = g.output(true, "show-ref", "--exists", "--end-of-options", name)
413 var exit *exec.ExitError
414 if errors.As(err, &exit) && exit.ExitCode() == 2 {
415 return "", false, nil
416 } else if err != nil {
417 return "", false, err
418 }
419 oid, err = g.output(true, "show-ref", "--verify", "--hash", "--end-of-options", name)
420 if err != nil {
421 return "", false, err
422 }
423 return oid, true, nil
424}
425
426// clock is the time the knot and plan verbs take as now: the time
427// VALLEY_NOW holds, when it is set, or else the system's clock. A knot's
428// created date, a claim's time and a comment's stamp are written at it,
429// and a claim's age is read against it. Checks set it, so the dates a
430// graph records and the ages a view shows are the same on every run. It
431// grants nothing: the push hook holds none of those times to its own
432// clock, so a writer could record any of them by writing the file. The
433// check worker measures its waits after a failed batch from it too
434// (worker.go).
435func clock() time.Time {
436 if t, err := clockSetting(); err == nil && !t.IsZero() {
437 return t
438 }
439 return time.Now().UTC()
440}
441
442// clockSetting is the time VALLEY_NOW holds, in UTC, or the zero time when
443// it is unset. A value that is no RFC 3339 time is refused.
444func clockSetting() (time.Time, error) {
445 v := os.Getenv("VALLEY_NOW")
446 if v == "" {
447 return time.Time{}, nil
448 }
449 t, err := time.Parse(time.RFC3339, v)
450 if err != nil {
451 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))
452 }
453 return t.UTC(), nil
454}
455
456// exitCode is the status a failed git exited with, for passing it on.
457func exitCode(err error) int {
458 var exit *exec.ExitError
459 if errors.As(err, &exit) && exit.ExitCode() > 0 {
460 return exit.ExitCode()
461 }
462 return 1
463}