gunk-dev/the-valley

main.go

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