gunk-dev/the-valley

main.go

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