gunk-dev/the-valley

main.go

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