gunk-dev/the-valley

main.go

sourced9c8073fd613main's published tip history
13.8 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 if buildMode(args) {
197 return runCheckBuild(g, args, stdout, stderr)
198 }
199 err = runChecks(g, args, stdout)
200 case checkBuildChild:
201 return runCheckBuildChild(g, args, stdout, stderr)
202 case "approve":
203 return runApprove(g, args, stdout, stderr, end)
204 case "changes":
205 err = runChanges(g, args, stdout, stderr)
206 case "pending":
207 err = runPending(g, args, stdout, stderr)
208 case "review":
209 return runReview(g, args, stdout, stderr, end)
210 case "telemetry":
211 err = runTelemetry(g, args, stdout, stderr)
212 case "self-update":
213 return runSelfUpdate(args, stdout, stderr)
214 case "knot", "plan", "work":
215 if _, err := clockSetting(); err != nil {
216 fmt.Fprintf(stderr, "valley: %s\n", err)
217 return 2
218 }
219 switch verb {
220 case "knot":
221 return runKnot(g, args, os.Stdin, stdout, stderr)
222 case "plan":
223 err = runPlan(g, args, stdout, stderr)
224 default:
225 err = runWork(g, args, stdout, stderr)
226 var unclaimed claimFailure
227 if errors.As(err, &unclaimed) {
228 fmt.Fprintf(stderr, "valley: %s\n", err)
229 return claimFailedStatus
230 }
231 }
232 default:
233 stderr = droppable(stderr)
234 fmt.Fprintf(stderr, "valley: unknown verb: %s\n\n", verb)
235 io.WriteString(stderr, helpPart("usage"))
236 return 1
237 }
238 if err != nil {
239 fmt.Fprintf(stderr, "valley: %s\n", err)
240 return 1
241 }
242 return 0
243}
244
245// git runs git in a repository, in the environment valley gives every git
246// it runs.
247type git struct {
248 env []string
249 stderr io.Writer // where git's own diagnostics go, unless quiet
250 dir string // the repository's directory; "" for the current one
251}
252
253// engine is g as the rebase engine runs git: in the same repository and
254// environment, with git's own diagnostics on the same stderr.
255func (g git) engine() rebase.Git {
256 return rebase.Git{Dir: g.dir, Env: g.env, Stderr: g.stderr, Phase: phase, Started: processStarted}
257}
258
259// gitEnvironment is the caller's environment with replacement refs off.
260// A replacement ref makes one object stand in for another wherever git
261// looks it up, so a fetched or planted refs/replace/* could change which
262// commit this read takes for a change's head. git is told to ignore them,
263// and the variables that point it at other objects or at another
264// replacement namespace are dropped. The person's own configuration is
265// kept: reaching origin needs it, and it does not change what an object
266// id reads as once replacement refs are off.
267func gitEnvironment(inherited []string) []string {
268 var kept []string
269 for _, kv := range inherited {
270 name, _, _ := strings.Cut(kv, "=")
271 switch name {
272 case "GIT_NO_REPLACE_OBJECTS", "GIT_REPLACE_REF_BASE", "GIT_GRAFT_FILE",
273 "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES":
274 continue
275 }
276 kept = append(kept, kv)
277 }
278 return append(kept, "GIT_NO_REPLACE_OBJECTS=1")
279}
280
281// command is git run with args in g's repository and environment.
282func (g git) command(args ...string) *exec.Cmd { return g.program("git", args...) }
283
284// program is the program name run with args in g's repository directory
285// and environment, the current directory's when g names none.
286func (g git) program(name string, args ...string) *exec.Cmd {
287 cmd := exec.Command(name, args...)
288 cmd.Env, cmd.Dir = g.env, g.dir
289 return cmd
290}
291
292// output runs git and returns what it printed, less trailing newlines, as
293// a shell's command substitution reads it. A quiet run discards git's
294// diagnostics; any other passes them on.
295func (g git) output(quiet bool, args ...string) (string, error) {
296 return g.input(quiet, nil, args...)
297}
298
299// input is output with stdin.
300func (g git) input(quiet bool, stdin io.Reader, args ...string) (string, error) {
301 processStarted()
302 cmd := g.command(args...)
303 cmd.Stdin = stdin
304 if !quiet {
305 cmd.Stderr = g.stderr
306 }
307 out, err := cmd.Output()
308 return strings.TrimRight(string(out), "\n"), err
309}
310
311// succeeds reports whether git exits zero. A failure to run git at all is
312// a no as well, as it is to a shell condition.
313func (g git) succeeds(quiet bool, args ...string) bool {
314 _, err := g.output(quiet, args...)
315 return err == nil
316}
317
318// ref reads the object ID that name, a full ref name, holds. It reads that
319// one ref, with git show-ref. ok is false when there is no ref of that
320// name. An error is a repository git could not read.
321//
322// git rev-parse is not used, because it does not stop at the name it is
323// given. For a missing refs/heads/topic, it goes on to try other names,
324// refs/heads/refs/heads/topic among them.
325func (g git) ref(name string) (oid string, ok bool, err error) {
326 // show-ref --exists exits 2 for a ref that is missing, and with
327 // another status for a failure to read.
328 _, err = g.output(true, "show-ref", "--exists", "--end-of-options", name)
329 var exit *exec.ExitError
330 if errors.As(err, &exit) && exit.ExitCode() == 2 {
331 return "", false, nil
332 } else if err != nil {
333 return "", false, err
334 }
335 oid, err = g.output(true, "show-ref", "--verify", "--hash", "--end-of-options", name)
336 if err != nil {
337 return "", false, err
338 }
339 return oid, true, nil
340}
341
342// clock is the time the knot and plan verbs take as now: the time
343// VALLEY_NOW holds, when it is set, or else the system's clock. A knot's
344// created date, a claim's time and a comment's stamp are written at it,
345// and a claim's age is read against it. Checks set it, so the dates a
346// graph records and the ages a view shows are the same on every run. It
347// grants nothing: the push hook holds none of those times to its own
348// clock, so a writer could record any of them by writing the file. The
349// check worker measures its waits after a failed batch from it too
350// (worker.go).
351func clock() time.Time {
352 if t, err := clockSetting(); err == nil && !t.IsZero() {
353 return t
354 }
355 return time.Now().UTC()
356}
357
358// clockSetting is the time VALLEY_NOW holds, in UTC, or the zero time when
359// it is unset. A value that is no RFC 3339 time is refused.
360func clockSetting() (time.Time, error) {
361 v := os.Getenv("VALLEY_NOW")
362 if v == "" {
363 return time.Time{}, nil
364 }
365 t, err := time.Parse(time.RFC3339, v)
366 if err != nil {
367 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))
368 }
369 return t.UTC(), nil
370}
371
372// exitCode is the status a failed git exited with, for passing it on.
373func exitCode(err error) int {
374 var exit *exec.ExitError
375 if errors.As(err, &exit) && exit.ExitCode() > 0 {
376 return exit.ExitCode()
377 }
378 return 1
379}