gunk-dev/the-valley

main.go

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