gunk-dev/the-valley

main.go

sourced2a8f94f1870main's published tip history
12.2 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, and for resolve, which turns the name of a
6// change into its branch for the verbs bin/valley runs itself, for
7// stack, which lists the layers under a change for review (stack.go), for
8// walk, which steps review through what needs the operator when it is
9// given no change (walk.go), for
10// rebase, which rebases a change's whole stack onto main, and brings, which
11// lists the changes a head would bring that have not landed, for approve
12// (rebase.go), for does, which lists the knots each change does, for review
13// (does.go), for checkline, which says what review shows of a change's
14// checks and their build times (versionchecks.go), for knot, the plan graph's API (knot.go), which reads and
15// writes a project's knots at refs/the-valley/knots, for plan, which
16// shows that graph as a view (plan.go), for compare, which sets a
17// version review shows against the change's approved version
18// (compare.go), and for self-update, which installs the tip of a branch of
19// the-valley into the user's nix profile (selfupdate.go). checks prints
20// which checks a change requires, as the Go deriver derives them
21// (checks.go); no verb of bin/valley runs it. coverage says which of a
22// head's required nix checks already have evidence on origin that approve
23// can reuse rather than build (coverage.go), and verdict prints what
24// approve and review's prompt say (verdict.go). work is one pass of a check
25// worker, which builds and publishes that evidence for ready changes
26// before they are approved (worker.go); no verb of bin/valley runs it.
27//
28// status reads one change's integration status (status.go). changes and
29// pending read every record and how far each version has landed
30// (inventory.go, pending.go). ready,
31// unready and withdraw write the change's record,
32// refs/the-valley/changes/main/<change ID> (ready.go), in the format the
33// change module defines and the push hook guards. The integrator reads
34// records only to refuse: it lands no request that would bring a version
35// of a change that is not ready, and it voids a withdrawn change's
36// requests. The integration request stays the only way
37// to main. versions lists a change's versions, for approve, and standing
38// says where a change stands now, for review (standing.go). carry says
39// whether review's answer about the version it showed carries to the
40// version the change moved to (carry.go). style styles review's page for
41// a terminal (style.go).
42//
43// A change is named by its full change ID, by its handle (the shortest
44// prefix of the ID, four letters at least, that no other change on origin
45// shares), or by its branch (changes.go).
46package main
47
48import (
49 "errors"
50 "fmt"
51 "io"
52 "os"
53 "os/exec"
54 "strings"
55 "time"
56
57 "the-valley/rebase"
58)
59
60const usage = `usage: valley-go status [--json] [-v] <change>
61 valley-go ready [--head <sha>] [--change <id>] [--if-active <sha>] [--stamp] [<branch>]
62 valley-go unready <change>
63 valley-go withdraw <change>
64 valley-go resolve <change>
65 valley-go stack <change>
66 valley-go does [-v] <change ID>...
67 valley-go checkline <change ID>...
68 valley-go rebase [--head <sha>] <change>
69 valley-go standing <change ID>
70 valley-go compare [-v] --tip <commit> <change ID> <version> <head>
71 valley-go carry <change ID> <version shown> <later version>
72 valley-go style [--paged] < page
73 valley-go checks [--schema <file>] --instance <dir> --project <dir> <base> <head>
74 valley-go approve [-v] [--head <sha>] [--build-here] <change>
75 valley-go verdict prompt <clause>... -- <key>...
76 valley-go work --repo <name>... --key <file> [--name <name>] [--state <dir>]
77 valley-go changes --json [--all] [--repo <name>] [-v]
78 valley-go pending [--json] [--all] [--repo <name>] [--checks] [-v]
79 valley-go walk [--repo <name>] [-v] [--build-here]
80 valley-go knot <verb> [args] (valley-go knot for its verbs)
81 valley-go plan [--project <name> | --all] [--owner <name>] [--json]
82 valley-go self-update [-v] [--retry | --rollback | --pin | --unpin] [--repo <url>] [--branch <name>]
83
84status, stack, rebase, brings, changes, pending, walk and plan read how far a
85version has landed, and also take --known-signers <file> and
86--integrator-name <name>: what an integrator's transfer statement is
87verified with, ahead of VALLEY_KNOWN_SIGNERS, VALLEY_INTEGRATOR_SIGNER and
88what the serving host publishes at refs/the-valley/signers.`
89
90func main() {
91 // A verb bin/valley execs this program for records its command record
92 // once it has run (command.go).
93 inv := execed(os.Args[1:])
94 exitWith = func(status int) {
95 inv.record(status, true)
96 os.Exit(status)
97 }
98 status := run(os.Args[1:], os.Stdout, os.Stderr)
99 inv.record(status, true)
100 os.Exit(status)
101}
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, as bin/valley's die
105// gives.
106type failure string
107
108func (f failure) Error() string { return string(f) }
109
110func run(args []string, stdout, stderr io.Writer) int {
111 g := git{env: gitEnvironment(os.Environ()), stderr: stderr}
112 verb := ""
113 if len(args) > 0 {
114 verb, args = args[0], args[1:]
115 }
116 // What this run verifies a transfer statement with (signers.go). Only
117 // the verbs that read how far a version has landed take the flags.
118 verification = &signerSource{g: g, stderr: stderr}
119 defer verification.done()
120 if signerVerbs[verb] {
121 var err error
122 if args, verification.keys, verification.name, err = takeSignerFlags(args); err != nil {
123 fmt.Fprintf(stderr, "valley: %s\n", err)
124 return 1
125 }
126 }
127 var err error
128 switch verb {
129 case "status":
130 return runStatus(g, args, stdout, stderr)
131 case "ready":
132 err = runReady(g, args, stdout)
133 case "unready":
134 err = runUnready(g, args, stdout, stderr)
135 case "withdraw":
136 err = runWithdraw(g, args, stdout, stderr)
137 case "resolve":
138 err = runResolve(g, args, stdout)
139 case "stack":
140 err = runStack(g, args, stdout)
141 case "does":
142 err = runDoes(g, args, stdout, stderr)
143 case "checkline":
144 err = runCheckLine(g, args, stdout, stderr)
145 case "rebase":
146 return runRebase(g, args, stdout, stderr)
147 case "standing":
148 err = runStanding(g, args, stdout)
149 case "compare":
150 err = runCompare(g, args, stdout)
151 case "carry":
152 err = runCarry(g, args, stdout)
153 case "style":
154 err = runStyle(args, os.Stdin, stdout)
155 case "checks":
156 err = runChecks(g, args, stdout)
157 case "approve":
158 return runApprove(g, args, stdout, stderr)
159 case "verdict":
160 return runVerdict(args, stdout, stderr)
161 case "changes":
162 err = runChanges(g, args, stdout, stderr)
163 case "pending":
164 err = runPending(g, args, stdout, stderr)
165 case "walk":
166 return runWalk(g, args, stdout, stderr)
167 case "telemetry":
168 err = runTelemetry(g, args, stdout, stderr)
169 case "self-update":
170 return runSelfUpdate(args, stdout, stderr)
171 case "knot", "plan", "work":
172 if _, err := clockSetting(); err != nil {
173 fmt.Fprintf(stderr, "valley: %s\n", err)
174 return 2
175 }
176 switch verb {
177 case "knot":
178 return runKnot(g, args, os.Stdin, stdout, stderr)
179 case "plan":
180 err = runPlan(g, args, stdout, stderr)
181 default:
182 err = runWork(g, args, stdout, stderr)
183 var unclaimed claimFailure
184 if errors.As(err, &unclaimed) {
185 fmt.Fprintf(stderr, "valley: %s\n", err)
186 return claimFailedStatus
187 }
188 }
189 default:
190 fmt.Fprintln(stderr, usage)
191 return 2
192 }
193 if err != nil {
194 fmt.Fprintf(stderr, "valley: %s\n", err)
195 return 1
196 }
197 return 0
198}
199
200// git runs git in a repository, in the environment bin/valley gives every
201// git it runs.
202type git struct {
203 env []string
204 stderr io.Writer // where git's own diagnostics go, unless quiet
205 dir string // the repository's directory; "" for the current one
206}
207
208// engine is g as the rebase engine runs git: in the same repository and
209// environment, with git's own diagnostics on the same stderr.
210func (g git) engine() rebase.Git {
211 return rebase.Git{Dir: g.dir, Env: g.env, Stderr: g.stderr, Phase: phase, Started: processStarted}
212}
213
214// gitEnvironment is the caller's environment with replacement refs off.
215// A replacement ref makes one object stand in for another wherever git
216// looks it up, so a fetched or planted refs/replace/* could change which
217// commit this read takes for a change's head. git is told to ignore them,
218// and the variables that point it at other objects or at another
219// replacement namespace are dropped. The person's own configuration is
220// kept: reaching origin needs it, and it does not change what an object
221// id reads as once replacement refs are off.
222func gitEnvironment(inherited []string) []string {
223 var kept []string
224 for _, kv := range inherited {
225 name, _, _ := strings.Cut(kv, "=")
226 switch name {
227 case "GIT_NO_REPLACE_OBJECTS", "GIT_REPLACE_REF_BASE", "GIT_GRAFT_FILE",
228 "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES":
229 continue
230 }
231 kept = append(kept, kv)
232 }
233 return append(kept, "GIT_NO_REPLACE_OBJECTS=1")
234}
235
236// output runs git and returns what it printed, less trailing newlines, as
237// a shell's command substitution reads it. A quiet run discards git's
238// diagnostics; any other passes them on.
239func (g git) output(quiet bool, args ...string) (string, error) {
240 return g.input(quiet, nil, args...)
241}
242
243// input is output with stdin.
244func (g git) input(quiet bool, stdin io.Reader, args ...string) (string, error) {
245 processStarted()
246 cmd := exec.Command("git", args...)
247 cmd.Env = g.env
248 cmd.Dir = g.dir
249 cmd.Stdin = stdin
250 if !quiet {
251 cmd.Stderr = g.stderr
252 }
253 out, err := cmd.Output()
254 return strings.TrimRight(string(out), "\n"), err
255}
256
257// succeeds reports whether git exits zero. A failure to run git at all is
258// a no as well, as it is to a shell condition.
259func (g git) succeeds(quiet bool, args ...string) bool {
260 _, err := g.output(quiet, args...)
261 return err == nil
262}
263
264// ref reads the object ID that name, a full ref name, holds. It reads that
265// one ref, with git show-ref. ok is false when there is no ref of that
266// name. An error is a repository git could not read.
267//
268// git rev-parse is not used, because it does not stop at the name it is
269// given. For a missing refs/heads/topic, it goes on to try other names,
270// refs/heads/refs/heads/topic among them.
271func (g git) ref(name string) (oid string, ok bool, err error) {
272 // show-ref --exists exits 2 for a ref that is missing, and with
273 // another status for a failure to read.
274 _, err = g.output(true, "show-ref", "--exists", "--end-of-options", name)
275 var exit *exec.ExitError
276 if errors.As(err, &exit) && exit.ExitCode() == 2 {
277 return "", false, nil
278 } else if err != nil {
279 return "", false, err
280 }
281 oid, err = g.output(true, "show-ref", "--verify", "--hash", "--end-of-options", name)
282 if err != nil {
283 return "", false, err
284 }
285 return oid, true, nil
286}
287
288// clock is the time the knot and plan verbs take as now: the time
289// VALLEY_NOW holds, when it is set, or else the system's clock. A knot's
290// created date, a claim's time and a comment's stamp are written at it,
291// and a claim's age is read against it. Checks set it, so the dates a
292// graph records and the ages a view shows are the same on every run. It
293// grants nothing: the push hook holds none of those times to its own
294// clock, so a writer could record any of them by writing the file. The
295// check worker measures its waits after a failed batch from it too
296// (worker.go).
297func clock() time.Time {
298 if t, err := clockSetting(); err == nil && !t.IsZero() {
299 return t
300 }
301 return time.Now().UTC()
302}
303
304// clockSetting is the time VALLEY_NOW holds, in UTC, or the zero time when
305// it is unset. A value that is no RFC 3339 time is refused.
306func clockSetting() (time.Time, error) {
307 v := os.Getenv("VALLEY_NOW")
308 if v == "" {
309 return time.Time{}, nil
310 }
311 t, err := time.Parse(time.RFC3339, v)
312 if err != nil {
313 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))
314 }
315 return t.UTC(), nil
316}
317
318// exitCode is the status a failed git exited with, for passing it on.
319func exitCode(err error) int {
320 var exit *exec.ExitError
321 if errors.As(err, &exit) && exit.ExitCode() > 0 {
322 return exit.ExitCode()
323 }
324 return 1
325}