gunk-dev/the-valley

main.go

sourceddfdc45c1aa2main's published tip history
13.7 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 "time"
57
58 "the-valley/rebase"
59)
60
61func main() {
62 takeEnvironment()
63 // A public verb records its command record once it has run
64 // (command.go), in the current checkout. A verb a signal ends records
65 // it too, through end.
66 inv := commandOf(os.Args[1:])
67 here := git{env: gitEnvironment(os.Environ()), stderr: io.Discard}
68 end := func(status int) {
69 inv.record(here, status, commandTimed)
70 os.Exit(status)
71 }
72 end(cli(os.Args[1:], os.Stdout, os.Stderr, end))
73}
74
75// versionStamp is the version the package stamped on this valley when nix built
76// it (nix/packages.nix): the CLI's version and the commit it was built
77// from, or "" for a build the package did not stamp. --version prints it,
78// self-update reads which commit is installed from it, and telemetry
79// names the producer of its records with it.
80var versionStamp string
81
82// takeEnvironment sets up the environment this process, and every program
83// it starts, runs in. The stamp is taken from VALLEY_VERSION, which is
84// removed, so no program this one starts takes the stamp for its own. git
85// ignores replacement refs, whatever configuration says, and loses the
86// variables that point it at other objects or at another replacement
87// namespace, for the reason gitEnvironment gives.
88func takeEnvironment() {
89 versionStamp = os.Getenv("VALLEY_VERSION")
90 os.Unsetenv("VALLEY_VERSION")
91 os.Setenv("GIT_NO_REPLACE_OBJECTS", "1")
92 for _, name := range []string{"GIT_REPLACE_REF_BASE", "GIT_GRAFT_FILE",
93 "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES"} {
94 os.Unsetenv(name)
95 }
96}
97
98// commandTimed is whether the command record holds each phase's time.
99// A review of one change clears it: its time is the operator's reading,
100// which no phase of the program accounts for.
101var commandTimed = true
102
103// failure is a verb that ends without doing what it was asked: a message
104// for stderr and nothing on stdout. Exit status 1.
105type failure string
106
107func (f failure) Error() string { return string(f) }
108
109// cli runs the valley command line args. No verb at all is help. A public
110// verb given one argument, -h or --help, prints its help topic before
111// anything reads its arguments. pending and rebase read origin's branches
112// through this checkout's remote-tracking refs, so they fetch origin
113// first, and a fetch that fails exits with git's status. end ends the
114// process from a verb a signal interrupts, as run's does.
115func cli(args []string, stdout, stderr io.Writer, end func(int)) int {
116 verb := "help"
117 if len(args) > 0 {
118 verb, args = args[0], args[1:]
119 }
120 if publicVerb(verb) && len(args) == 1 && (args[0] == "-h" || args[0] == "--help") {
121 return runHelp([]string{verb}, stdout, stderr)
122 }
123 g := git{env: gitEnvironment(os.Environ()), stderr: stderr}
124 switch verb {
125 case "help", "-h", "--help":
126 return runHelp(args, stdout, stderr)
127 case "--version":
128 v := versionStamp
129 if v == "" {
130 v = "unstamped (built without the package's version stamp)"
131 }
132 fmt.Fprintf(stdout, "valley %s\n", v)
133 return 0
134 case "tail":
135 return runTail(args, stderr)
136 case "replay":
137 return runReplay(g, args, stdout, stderr)
138 case "pending", "rebase":
139 if verb == "rebase" {
140 var err error
141 if args, err = rebaseCommandArgs(args); err != nil {
142 fmt.Fprintf(stderr, "valley: %s\n", err)
143 return 1
144 }
145 }
146 fetched := phase("fetch")
147 err := fetchOrigin(g, stdout, stderr)
148 fetched()
149 if err != nil {
150 return exitCode(err)
151 }
152 }
153 return run(append([]string{verb}, args...), stdout, stderr, end)
154}
155
156// run runs the verb args name. end ends the process from a verb a signal
157// interrupts, once the verb has cleaned up; it does not return.
158func run(args []string, stdout, stderr io.Writer, end func(int)) int {
159 g := git{env: gitEnvironment(os.Environ()), stderr: stderr}
160 verb := ""
161 if len(args) > 0 {
162 verb, args = args[0], args[1:]
163 }
164 // What this run verifies a transfer statement with (signers.go). Only
165 // the verbs that read how far a version has landed take the flags.
166 verification = &signerSource{g: g, stderr: stderr}
167 defer verification.done()
168 if signerVerbs[verb] {
169 var err error
170 if args, verification.keys, verification.name, err = takeSignerFlags(args); err != nil {
171 fmt.Fprintf(stderr, "valley: %s\n", err)
172 return 1
173 }
174 }
175 var err error
176 switch verb {
177 case "status":
178 return runStatus(g, args, stdout, stderr)
179 case "ready":
180 err = runReady(g, args, stdout)
181 case "unready":
182 err = runUnready(g, args, stdout, stderr)
183 case "withdraw":
184 err = runWithdraw(g, args, stdout, stderr)
185 case "resolve":
186 err = runResolve(g, args, stdout)
187 case "stack":
188 err = runStack(g, args, stdout)
189 case "checkline":
190 err = runCheckLine(g, args, stdout, stderr)
191 case "rebase":
192 return runRebase(g, args, stdout, stderr)
193 case "style":
194 err = runStyle(args, os.Stdin, stdout)
195 case "checks":
196 err = runChecks(g, args, stdout)
197 case "approve":
198 return runApprove(g, args, stdout, stderr, end)
199 case "changes":
200 err = runChanges(g, args, stdout, stderr)
201 case "pending":
202 err = runPending(g, args, stdout, stderr)
203 case "review":
204 return runReview(g, args, stdout, stderr, end)
205 case "telemetry":
206 err = runTelemetry(g, args, stdout, stderr)
207 case "self-update":
208 return runSelfUpdate(args, stdout, stderr)
209 case "knot", "plan", "work":
210 if _, err := clockSetting(); err != nil {
211 fmt.Fprintf(stderr, "valley: %s\n", err)
212 return 2
213 }
214 switch verb {
215 case "knot":
216 return runKnot(g, args, os.Stdin, stdout, stderr)
217 case "plan":
218 err = runPlan(g, args, stdout, stderr)
219 default:
220 err = runWork(g, args, stdout, stderr)
221 var unclaimed claimFailure
222 if errors.As(err, &unclaimed) {
223 fmt.Fprintf(stderr, "valley: %s\n", err)
224 return claimFailedStatus
225 }
226 }
227 default:
228 stderr = droppable(stderr)
229 fmt.Fprintf(stderr, "valley: unknown verb: %s\n\n", verb)
230 io.WriteString(stderr, helpPart("usage"))
231 return 1
232 }
233 if err != nil {
234 fmt.Fprintf(stderr, "valley: %s\n", err)
235 return 1
236 }
237 return 0
238}
239
240// git runs git in a repository, in the environment valley gives every git
241// it runs.
242type git struct {
243 env []string
244 stderr io.Writer // where git's own diagnostics go, unless quiet
245 dir string // the repository's directory; "" for the current one
246}
247
248// engine is g as the rebase engine runs git: in the same repository and
249// environment, with git's own diagnostics on the same stderr.
250func (g git) engine() rebase.Git {
251 return rebase.Git{Dir: g.dir, Env: g.env, Stderr: g.stderr, Phase: phase, Started: processStarted}
252}
253
254// gitEnvironment is the caller's environment with replacement refs off.
255// A replacement ref makes one object stand in for another wherever git
256// looks it up, so a fetched or planted refs/replace/* could change which
257// commit this read takes for a change's head. git is told to ignore them,
258// and the variables that point it at other objects or at another
259// replacement namespace are dropped. The person's own configuration is
260// kept: reaching origin needs it, and it does not change what an object
261// id reads as once replacement refs are off.
262func gitEnvironment(inherited []string) []string {
263 var kept []string
264 for _, kv := range inherited {
265 name, _, _ := strings.Cut(kv, "=")
266 switch name {
267 case "GIT_NO_REPLACE_OBJECTS", "GIT_REPLACE_REF_BASE", "GIT_GRAFT_FILE",
268 "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES":
269 continue
270 }
271 kept = append(kept, kv)
272 }
273 return append(kept, "GIT_NO_REPLACE_OBJECTS=1")
274}
275
276// command is git run with args in g's repository and environment.
277func (g git) command(args ...string) *exec.Cmd { return g.program("git", args...) }
278
279// program is the program name run with args in g's repository directory
280// and environment, the current directory's when g names none.
281func (g git) program(name string, args ...string) *exec.Cmd {
282 cmd := exec.Command(name, args...)
283 cmd.Env, cmd.Dir = g.env, g.dir
284 return cmd
285}
286
287// output runs git and returns what it printed, less trailing newlines, as
288// a shell's command substitution reads it. A quiet run discards git's
289// diagnostics; any other passes them on.
290func (g git) output(quiet bool, args ...string) (string, error) {
291 return g.input(quiet, nil, args...)
292}
293
294// input is output with stdin.
295func (g git) input(quiet bool, stdin io.Reader, args ...string) (string, error) {
296 processStarted()
297 cmd := g.command(args...)
298 cmd.Stdin = stdin
299 if !quiet {
300 cmd.Stderr = g.stderr
301 }
302 out, err := cmd.Output()
303 return strings.TrimRight(string(out), "\n"), err
304}
305
306// succeeds reports whether git exits zero. A failure to run git at all is
307// a no as well, as it is to a shell condition.
308func (g git) succeeds(quiet bool, args ...string) bool {
309 _, err := g.output(quiet, args...)
310 return err == nil
311}
312
313// ref reads the object ID that name, a full ref name, holds. It reads that
314// one ref, with git show-ref. ok is false when there is no ref of that
315// name. An error is a repository git could not read.
316//
317// git rev-parse is not used, because it does not stop at the name it is
318// given. For a missing refs/heads/topic, it goes on to try other names,
319// refs/heads/refs/heads/topic among them.
320func (g git) ref(name string) (oid string, ok bool, err error) {
321 // show-ref --exists exits 2 for a ref that is missing, and with
322 // another status for a failure to read.
323 _, err = g.output(true, "show-ref", "--exists", "--end-of-options", name)
324 var exit *exec.ExitError
325 if errors.As(err, &exit) && exit.ExitCode() == 2 {
326 return "", false, nil
327 } else if err != nil {
328 return "", false, err
329 }
330 oid, err = g.output(true, "show-ref", "--verify", "--hash", "--end-of-options", name)
331 if err != nil {
332 return "", false, err
333 }
334 return oid, true, nil
335}
336
337// clock is the time the knot and plan verbs take as now: the time
338// VALLEY_NOW holds, when it is set, or else the system's clock. A knot's
339// created date, a claim's time and a comment's stamp are written at it,
340// and a claim's age is read against it. Checks set it, so the dates a
341// graph records and the ages a view shows are the same on every run. It
342// grants nothing: the push hook holds none of those times to its own
343// clock, so a writer could record any of them by writing the file. The
344// check worker measures its waits after a failed batch from it too
345// (worker.go).
346func clock() time.Time {
347 if t, err := clockSetting(); err == nil && !t.IsZero() {
348 return t
349 }
350 return time.Now().UTC()
351}
352
353// clockSetting is the time VALLEY_NOW holds, in UTC, or the zero time when
354// it is unset. A value that is no RFC 3339 time is refused.
355func clockSetting() (time.Time, error) {
356 v := os.Getenv("VALLEY_NOW")
357 if v == "" {
358 return time.Time{}, nil
359 }
360 t, err := time.Parse(time.RFC3339, v)
361 if err != nil {
362 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))
363 }
364 return t.UTC(), nil
365}
366
367// exitCode is the status a failed git exited with, for passing it on.
368func exitCode(err error) int {
369 var exit *exec.ExitError
370 if errors.As(err, &exit) && exit.ExitCode() > 0 {
371 return exit.ExitCode()
372 }
373 return 1
374}