gunk-dev/the-valley

main.go

source499d9e61dfeemain's published tip history
13.3 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), in the current checkout. A verb a
95 // signal ends records it too, through end.
96 inv := execed(os.Args[1:])
97 here := git{env: gitEnvironment(os.Environ()), stderr: io.Discard}
98 end := func(status int) {
99 inv.record(here, status, commandTimed)
100 os.Exit(status)
101 }
102 end(run(os.Args[1:], os.Stdout, os.Stderr, end))
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
117// run runs the verb args name. end ends the process from a verb a signal
118// interrupts, once the verb has cleaned up; it does not return.
119func run(args []string, stdout, stderr io.Writer, end func(int)) int {
120 g := git{env: gitEnvironment(os.Environ()), stderr: stderr}
121 verb := ""
122 if len(args) > 0 {
123 verb, args = args[0], args[1:]
124 }
125 // What this run verifies a transfer statement with (signers.go). Only
126 // the verbs that read how far a version has landed take the flags.
127 verification = &signerSource{g: g, stderr: stderr}
128 defer verification.done()
129 if signerVerbs[verb] {
130 var err error
131 if args, verification.keys, verification.name, err = takeSignerFlags(args); err != nil {
132 fmt.Fprintf(stderr, "valley: %s\n", err)
133 return 1
134 }
135 }
136 var err error
137 switch verb {
138 case "status":
139 return runStatus(g, args, stdout, stderr)
140 case "ready":
141 err = runReady(g, args, stdout)
142 case "unready":
143 err = runUnready(g, args, stdout, stderr)
144 case "withdraw":
145 err = runWithdraw(g, args, stdout, stderr)
146 case "resolve":
147 err = runResolve(g, args, stdout)
148 case "stack":
149 err = runStack(g, args, stdout)
150 case "does":
151 err = runDoes(g, args, stdout, stderr)
152 case "checkline":
153 err = runCheckLine(g, args, stdout, stderr)
154 case "rebase":
155 return runRebase(g, args, stdout, stderr)
156 case "standing":
157 err = runStanding(g, args, stdout)
158 case "compare":
159 err = runCompare(g, args, stdout)
160 case "carry":
161 err = runCarry(g, args, stdout)
162 case "style":
163 err = runStyle(args, os.Stdin, stdout)
164 case "checks":
165 err = runChecks(g, args, stdout)
166 case "approve":
167 return runApprove(g, args, stdout, stderr, end)
168 case "verdict":
169 return runVerdict(args, stdout, stderr)
170 case "changes":
171 err = runChanges(g, args, stdout, stderr)
172 case "pending":
173 err = runPending(g, args, stdout, stderr)
174 case "review":
175 return runReview(g, args, stdout, stderr, end)
176 case "walk":
177 return runWalk(g, args, stdout, stderr, end)
178 case "telemetry":
179 err = runTelemetry(g, args, stdout, stderr)
180 case "self-update":
181 return runSelfUpdate(args, stdout, stderr)
182 case "knot", "plan", "work":
183 if _, err := clockSetting(); err != nil {
184 fmt.Fprintf(stderr, "valley: %s\n", err)
185 return 2
186 }
187 switch verb {
188 case "knot":
189 return runKnot(g, args, os.Stdin, stdout, stderr)
190 case "plan":
191 err = runPlan(g, args, stdout, stderr)
192 default:
193 err = runWork(g, args, stdout, stderr)
194 var unclaimed claimFailure
195 if errors.As(err, &unclaimed) {
196 fmt.Fprintf(stderr, "valley: %s\n", err)
197 return claimFailedStatus
198 }
199 }
200 default:
201 fmt.Fprintln(stderr, usage)
202 return 2
203 }
204 if err != nil {
205 fmt.Fprintf(stderr, "valley: %s\n", err)
206 return 1
207 }
208 return 0
209}
210
211// git runs git in a repository, in the environment bin/valley gives every
212// git it runs.
213type git struct {
214 env []string
215 stderr io.Writer // where git's own diagnostics go, unless quiet
216 dir string // the repository's directory; "" for the current one
217}
218
219// engine is g as the rebase engine runs git: in the same repository and
220// environment, with git's own diagnostics on the same stderr.
221func (g git) engine() rebase.Git {
222 return rebase.Git{Dir: g.dir, Env: g.env, Stderr: g.stderr, Phase: phase, Started: processStarted}
223}
224
225// gitEnvironment is the caller's environment with replacement refs off.
226// A replacement ref makes one object stand in for another wherever git
227// looks it up, so a fetched or planted refs/replace/* could change which
228// commit this read takes for a change's head. git is told to ignore them,
229// and the variables that point it at other objects or at another
230// replacement namespace are dropped. The person's own configuration is
231// kept: reaching origin needs it, and it does not change what an object
232// id reads as once replacement refs are off.
233func gitEnvironment(inherited []string) []string {
234 var kept []string
235 for _, kv := range inherited {
236 name, _, _ := strings.Cut(kv, "=")
237 switch name {
238 case "GIT_NO_REPLACE_OBJECTS", "GIT_REPLACE_REF_BASE", "GIT_GRAFT_FILE",
239 "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES":
240 continue
241 }
242 kept = append(kept, kv)
243 }
244 return append(kept, "GIT_NO_REPLACE_OBJECTS=1")
245}
246
247// command is git run with args in g's repository and environment.
248func (g git) command(args ...string) *exec.Cmd { return g.program("git", args...) }
249
250// program is the program name run with args in g's repository directory
251// and environment, the current directory's when g names none.
252func (g git) program(name string, args ...string) *exec.Cmd {
253 cmd := exec.Command(name, args...)
254 cmd.Env, cmd.Dir = g.env, g.dir
255 return cmd
256}
257
258// output runs git and returns what it printed, less trailing newlines, as
259// a shell's command substitution reads it. A quiet run discards git's
260// diagnostics; any other passes them on.
261func (g git) output(quiet bool, args ...string) (string, error) {
262 return g.input(quiet, nil, args...)
263}
264
265// input is output with stdin.
266func (g git) input(quiet bool, stdin io.Reader, args ...string) (string, error) {
267 processStarted()
268 cmd := g.command(args...)
269 cmd.Stdin = stdin
270 if !quiet {
271 cmd.Stderr = g.stderr
272 }
273 out, err := cmd.Output()
274 return strings.TrimRight(string(out), "\n"), err
275}
276
277// succeeds reports whether git exits zero. A failure to run git at all is
278// a no as well, as it is to a shell condition.
279func (g git) succeeds(quiet bool, args ...string) bool {
280 _, err := g.output(quiet, args...)
281 return err == nil
282}
283
284// ref reads the object ID that name, a full ref name, holds. It reads that
285// one ref, with git show-ref. ok is false when there is no ref of that
286// name. An error is a repository git could not read.
287//
288// git rev-parse is not used, because it does not stop at the name it is
289// given. For a missing refs/heads/topic, it goes on to try other names,
290// refs/heads/refs/heads/topic among them.
291func (g git) ref(name string) (oid string, ok bool, err error) {
292 // show-ref --exists exits 2 for a ref that is missing, and with
293 // another status for a failure to read.
294 _, err = g.output(true, "show-ref", "--exists", "--end-of-options", name)
295 var exit *exec.ExitError
296 if errors.As(err, &exit) && exit.ExitCode() == 2 {
297 return "", false, nil
298 } else if err != nil {
299 return "", false, err
300 }
301 oid, err = g.output(true, "show-ref", "--verify", "--hash", "--end-of-options", name)
302 if err != nil {
303 return "", false, err
304 }
305 return oid, true, nil
306}
307
308// clock is the time the knot and plan verbs take as now: the time
309// VALLEY_NOW holds, when it is set, or else the system's clock. A knot's
310// created date, a claim's time and a comment's stamp are written at it,
311// and a claim's age is read against it. Checks set it, so the dates a
312// graph records and the ages a view shows are the same on every run. It
313// grants nothing: the push hook holds none of those times to its own
314// clock, so a writer could record any of them by writing the file. The
315// check worker measures its waits after a failed batch from it too
316// (worker.go).
317func clock() time.Time {
318 if t, err := clockSetting(); err == nil && !t.IsZero() {
319 return t
320 }
321 return time.Now().UTC()
322}
323
324// clockSetting is the time VALLEY_NOW holds, in UTC, or the zero time when
325// it is unset. A value that is no RFC 3339 time is refused.
326func clockSetting() (time.Time, error) {
327 v := os.Getenv("VALLEY_NOW")
328 if v == "" {
329 return time.Time{}, nil
330 }
331 t, err := time.Parse(time.RFC3339, v)
332 if err != nil {
333 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))
334 }
335 return t.UTC(), nil
336}
337
338// exitCode is the status a failed git exited with, for passing it on.
339func exitCode(err error) int {
340 var exit *exec.ExitError
341 if errors.As(err, &exit) && exit.ExitCode() > 0 {
342 return exit.ExitCode()
343 }
344 return 1
345}