gunk-dev/the-valley

main.go

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