gunk-dev/the-valley

main.go

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