gunk-dev/the-valley

main.go

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