gunk-dev/the-valley

main.go

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