gunk-dev/the-valley

main.go

source2eca5696ca57main's published tip history
13.7 KiB
1// valley-restacker rebases ready changes onto main when main moves under
2// them, as its own principal, so their evidence stays fresh without their
3// owners rebasing and approving again by hand.
4//
5// This slice is the planner: `valley-restacker once --report-only` reads
6// one snapshot of origin and says which families it would restack, which
7// it would hold and why, and what capacity allows. It pushes nothing.
8//
9// It talks to origin only over git, as a client, from a scratch repository
10// under its state directory. Hooks and external filters are off there:
11// the scratch repository's hooks path is /dev/null, and git reads neither
12// the system's nor the user's configuration, so no filter driver is
13// defined. A service that needs ssh settings passes them in
14// GIT_SSH_COMMAND.
15package main
16
17import (
18 "context"
19 "encoding/json"
20 "errors"
21 "flag"
22 "fmt"
23 "io"
24 "os"
25 "os/exec"
26 "path/filepath"
27 "strings"
28
29 "the-valley/change"
30 "the-valley/composed"
31 "the-valley/rebase"
32)
33
34const usage = `valley-restacker: rebase ready changes onto main when main moves.
35
36usage: valley-restacker once --report-only [flags]
37
38 once --report-only
39 read one snapshot of origin and print what a pass would do: each
40 family, restack or hold with the reason, its capacity, and the
41 integration requests it considered. Pushes nothing.
42
43flags:
44 --repo URL origin: the repository the restacker serves (required)
45 --target NAME the target changes are rebased onto (only main)
46 --state DIR where the scratch repository lives (required)
47 --principal NAME the principal the restacker pushes as (required)
48 --known-signers FILE verifier keys, for landings proved by integrator evidence
49 --integrator-name N the name the integrator signs under
50 --attest PATH the attest helper that checks a note (default: attest on PATH)
51 --instance-repo URL the repository carrying the group's floor
52 --instance-ref REF the ref whose tip carries the floor (refs/heads/main)
53 --instance-policy DIR the floor's directory in that tip (policy/instance)
54 --instance DIR a materialized floor, for a host that serves none
55 --project-policy DIR the project layer, in the target tip (policy/project)
56 --schema FILE the verification schema (VALLEY_VERIFICATION_SCHEMA)
57 --json print the plan as JSON
58`
59
60func main() {
61 if len(os.Args) < 2 {
62 fmt.Fprint(os.Stderr, usage)
63 os.Exit(2)
64 }
65 switch os.Args[1] {
66 case "once":
67 if err := once(os.Args[2:], os.Stdout); err != nil {
68 fmt.Fprintf(os.Stderr, "valley-restacker: %v\n", err)
69 os.Exit(1)
70 }
71 case "help", "-h", "--help":
72 fmt.Print(usage)
73 default:
74 fmt.Fprintf(os.Stderr, "valley-restacker: unknown command %q\n\n%s", os.Args[1], usage)
75 os.Exit(2)
76 }
77}
78
79// config is a pass's configuration, from flags.
80type config struct {
81 repo, target, state, principal string
82 verify rebase.Verifier
83 floor composed.Floor
84 instanceRepo, projectPolicy string
85 schema, cue string
86 json bool
87}
88
89func once(args []string, out io.Writer) error {
90 fs := flag.NewFlagSet("valley-restacker once", flag.ContinueOnError)
91 fs.Usage = func() { fmt.Fprint(os.Stderr, usage) }
92 var c config
93 reportOnly := fs.Bool("report-only", false, "")
94 fs.StringVar(&c.repo, "repo", "", "")
95 fs.StringVar(&c.target, "target", rebase.Target, "")
96 fs.StringVar(&c.state, "state", "", "")
97 fs.StringVar(&c.principal, "principal", "", "")
98 fs.StringVar(&c.verify.Keys, "known-signers", "", "")
99 fs.StringVar(&c.verify.Signer, "integrator-name", "", "")
100 fs.StringVar(&c.verify.Attest, "attest", "", "")
101 fs.StringVar(&c.instanceRepo, "instance-repo", "", "")
102 fs.StringVar(&c.floor.Ref, "instance-ref", "refs/heads/main", "")
103 fs.StringVar(&c.floor.Dir, "instance-policy", "policy/instance", "")
104 fs.StringVar(&c.floor.Path, "instance", "", "")
105 fs.StringVar(&c.projectPolicy, "project-policy", "policy/project", "")
106 fs.StringVar(&c.schema, "schema", os.Getenv("VALLEY_VERIFICATION_SCHEMA"), "")
107 fs.BoolVar(&c.json, "json", false, "")
108 if err := fs.Parse(args); err != nil {
109 return err
110 }
111 switch {
112 case fs.NArg() > 0:
113 return fmt.Errorf("unexpected argument %q", fs.Arg(0))
114 case !*reportOnly:
115 return errors.New("once needs --report-only: this restacker plans and does not yet push")
116 case c.target != rebase.Target:
117 return fmt.Errorf("--target %s: a change may name only %s as its target", c.target, rebase.Target)
118 }
119 for _, f := range []struct{ flag, value string }{
120 {"--repo", c.repo}, {"--state", c.state}, {"--principal", c.principal}, {"--schema", c.schema},
121 } {
122 if f.value == "" {
123 return fmt.Errorf("%s is required", f.flag)
124 }
125 }
126 if !change.ValidPrincipal(c.principal) {
127 return fmt.Errorf("--principal %q is not a principal", c.principal)
128 }
129 // The floor comes from the instance repository's tip, or from a
130 // directory on disk, and never from both, as for the integrator.
131 if (c.instanceRepo == "") == (c.floor.Path == "") {
132 return errors.New("exactly one of --instance-repo and --instance is required: the floor is read from the instance repository's tip, or from a materialized directory")
133 }
134 if c.verify.Attest == "" {
135 c.verify.Attest, _ = exec.LookPath("attest")
136 }
137 var err error
138 if c.cue, err = exec.LookPath("cue"); err != nil {
139 return errors.New("cue is not on the path; the restacker composes the policy with it")
140 }
141 ctx := context.Background()
142 g, err := scratchRepo(ctx, c)
143 if err != nil {
144 return err
145 }
146 p, err := planOnce(ctx, g, c)
147 if err != nil {
148 return err
149 }
150 if c.json {
151 enc := json.NewEncoder(out)
152 enc.SetIndent("", " ")
153 return enc.Encode(p)
154 }
155 printPlan(out, p)
156 return nil
157}
158
159// scratchRepo makes, or reuses, the bare repository a pass reads origin
160// into, and returns git run in it with hooks and configured filters off.
161func scratchRepo(ctx context.Context, c config) (rebase.Git, error) {
162 dir := filepath.Join(c.state, "scratch.git")
163 env := append(os.Environ(),
164 "GIT_CONFIG_NOSYSTEM=1",
165 "GIT_CONFIG_GLOBAL=/dev/null",
166 "GIT_ATTR_NOSYSTEM=1",
167 "GIT_TERMINAL_PROMPT=0",
168 )
169 g := rebase.Git{Dir: dir, Env: env, Stderr: os.Stderr}
170 if _, err := os.Stat(filepath.Join(dir, "HEAD")); err != nil {
171 if err := os.MkdirAll(dir, 0o700); err != nil {
172 return g, err
173 }
174 if err := run(ctx, g, "init", "--quiet", "--bare"); err != nil {
175 return g, err
176 }
177 }
178 for _, kv := range [][2]string{{"core.hooksPath", "/dev/null"}, {"core.fsmonitor", "false"}} {
179 if err := run(ctx, g, "config", kv[0], kv[1]); err != nil {
180 return g, err
181 }
182 }
183 // The remote is set every pass, so a changed --repo takes effect.
184 _ = run(ctx, g, "remote", "remove", "origin")
185 return g, run(ctx, g, "remote", "add", "origin", c.repo)
186}
187
188func run(ctx context.Context, g rebase.Git, args ...string) error {
189 _, err := gitOut(ctx, g, args...)
190 return err
191}
192
193func gitOut(ctx context.Context, g rebase.Git, args ...string) (string, error) {
194 cmd := exec.CommandContext(ctx, "git", args...)
195 cmd.Dir, cmd.Env = g.Dir, g.Env
196 var stderr strings.Builder
197 cmd.Stderr = &stderr
198 b, err := cmd.Output()
199 if err != nil {
200 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))
201 }
202 return string(b), nil
203}
204
205// ancestry is merge-base --is-ancestor, telling "no" (exit 1) apart from a
206// question git could not answer.
207func ancestry(ctx context.Context, g rebase.Git) Ancestry {
208 return func(a, b string) (bool, error) {
209 cmd := exec.CommandContext(ctx, "git", "merge-base", "--is-ancestor", a, b)
210 cmd.Dir, cmd.Env = g.Dir, g.Env
211 err := cmd.Run()
212 var exit *exec.ExitError
213 switch {
214 case err == nil:
215 return true, nil
216 case errors.As(err, &exit) && exit.ExitCode() == 1:
217 return false, nil
218 }
219 return false, fmt.Errorf("could not tell whether %s is in %s", short(a), short(b))
220 }
221}
222
223// policyCap composes the policy at the target tip and reads the cap on
224// automatic versions: the floor from the instance repository's tip, read
225// over git into the scratch repository, or from --instance; the project
226// layer from the tip.
227func policyCap(ctx context.Context, g rebase.Git, c config, tip string) (int, error) {
228 floor := c.floor
229 if c.instanceRepo != "" {
230 out, err := gitOut(ctx, g, "ls-remote", c.instanceRepo, floor.Ref)
231 oid, _, _ := strings.Cut(out, "\t")
232 if err != nil || !rebase.IsObjectID(oid) {
233 return 0, fmt.Errorf("no instance policy layer: %s has no %s: %s", c.instanceRepo, floor.Ref, composed.Floorless)
234 }
235 if err := run(ctx, g, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", c.instanceRepo, oid); err != nil {
236 return 0, err
237 }
238 floor.Repo, floor.Ref = g.Dir, oid
239 }
240 instance, done, err := floor.Open("valley-restacker-floor")
241 if err != nil {
242 return 0, err
243 }
244 defer done()
245 project, _, doneProject, err := composed.Project(g.Dir, tip, c.projectPolicy, "valley-restacker-project")
246 if err != nil {
247 return 0, err
248 }
249 defer doneProject()
250 pol, err := composed.Compose(c.cue, c.schema, instance, project)
251 if err != nil {
252 return 0, err
253 }
254 return CapOf(pol.MaxAutomaticVersions)
255}
256
257// planOnce reads one snapshot and plans every family in it.
258func planOnce(ctx context.Context, g rebase.Git, c config) (*Plan, error) {
259 s, err := rebase.ReadSnapshot(ctx, g, c.verify)
260 if err != nil {
261 return nil, err
262 }
263 if s.Tip == "" {
264 return nil, fmt.Errorf("origin has no %s", rebase.Target)
265 }
266 cap, err := policyCap(ctx, g, c, s.Tip)
267 if err != nil {
268 return nil, err
269 }
270 var attestations []string
271 var requests []Request
272 for ref, oid := range s.Refs {
273 switch {
274 case strings.HasPrefix(ref, rebase.AttestationRefs):
275 attestations = append(attestations, ref+" "+oid)
276 case strings.HasPrefix(ref, rebase.RequestPrefix):
277 requests = append(requests, Request{Name: strings.TrimPrefix(ref, rebase.RequestPrefix), Head: oid})
278 }
279 }
280 p := &Plan{Target: rebase.Target, Tip: s.Tip, Evidence: change.EvidenceFingerprint(attestations), Cap: cap}
281
282 // The snapshot lists request heads and does not fetch them. They are
283 // fetched here, before any ancestry is read, all at once and then one
284 // by one when that fails, so one head origin cannot serve leaves the
285 // others readable.
286 var heads []string
287 for _, r := range requests {
288 heads = append(heads, r.Head)
289 }
290 if rebase.Fetch(ctx, g, heads...) != nil {
291 for _, h := range heads {
292 _ = rebase.Fetch(ctx, g, h)
293 }
294 }
295
296 seen := map[string]bool{}
297 for _, n := range s.Changes {
298 if seen[n.ID] || !s.Unlanded(n) {
299 continue
300 }
301 f, err := rebase.Capture(s, rebase.Selection{ID: n.ID, Whole: true})
302 if err != nil {
303 return nil, err
304 }
305 for _, l := range f.Layers {
306 if l.ID != "" {
307 seen[l.ID] = true
308 }
309 }
310 p.Families = append(p.Families, judge(f, s, c.principal, p, requests, ancestry(ctx, g)))
311 }
312 return p, nil
313}
314
315// judge decides what a pass would do with one family.
316func judge(f *rebase.Family, s *rebase.Snapshot, principal string, p *Plan, requests []Request, is Ancestry) FamilyPlan {
317 fp := FamilyPlan{Reasons: []string{}, Notes: []string{}, Requests: []RequestPlan{}}
318 ready := false
319 for _, l := range f.Layers {
320 lp := LayerPlan{Name: l.Name, ID: l.ID, Branch: l.Branch, Head: l.Head, State: string(l.State())}
321 if l.Below != nil {
322 lp.Below = l.Below.Name
323 }
324 if l.State() == rebase.Ready {
325 ready = true
326 } else {
327 fp.Reasons = append(fp.Reasons, stateLine(l))
328 }
329 fp.Layers = append(fp.Layers, lp)
330 }
331 switch {
332 case !ready:
333 fp.Action = leave
334 return fp
335 case f.FastForwards():
336 fp.Action, fp.Reasons = current, []string{"it already descends from " + rebase.Target + "'s tip"}
337 return fp
338 }
339 if err := f.Check(); err != nil {
340 fp.Reasons = append(fp.Reasons, err.Error())
341 }
342
343 m := membersOf(f)
344 for _, r := range requests {
345 by, err := Relate(r, m, p.Tip, is)
346 if err != nil {
347 fp.Requests = append(fp.Requests, RequestPlan{Name: r.Name, Head: r.Head, By: []string{}, Why: err.Error()})
348 fp.Reasons = append(fp.Reasons, fmt.Sprintf("request %s: whether it is related cannot be determined: %v", r.Name, err))
349 continue
350 }
351 if by == nil {
352 continue
353 }
354 o, found := s.OutcomeOf(r.Name)
355 rp := RequestPlan{Name: r.Name, Head: r.Head, By: by}
356 if found {
357 rp.Decision = o.Decision
358 }
359 rp.Current, rp.Releases, rp.Why = Currency(o, found, r.Head, p.Tip, p.Evidence)
360 switch {
361 case !rp.Releases:
362 fp.Reasons = append(fp.Reasons, fmt.Sprintf("request %s might still land: %s", r.Name, rp.Why))
363 case o.Decision == "reject":
364 fp.Notes = append(fp.Notes, fmt.Sprintf("request %s was rejected at this head, tip and evidence", r.Name))
365 }
366 fp.Requests = append(fp.Requests, rp)
367 }
368 sortRequests(fp.Requests)
369
370 for i, l := range f.Layers {
371 if l.ID == "" || l.Record == nil {
372 continue
373 }
374 cp := CapacityOf(l.Record, principal, p.Cap, nextSize(l.Name, l.Record, principal))
375 fp.Layers[i].Capacity = cp
376 fp.Reasons = append(fp.Reasons, cp.Over...)
377 }
378 fp.Action = restack
379 if len(fp.Reasons) > 0 {
380 fp.Action = hold
381 }
382 return fp
383}
384
385func printPlan(w io.Writer, p *Plan) {
386 fmt.Fprintf(w, "%s at %s, evidence %s, at most %d automatic versions a change\n", p.Target, short(p.Tip), p.Evidence, p.Cap)
387 if len(p.Families) == 0 {
388 fmt.Fprintln(w, "no change to restack")
389 }
390 for _, f := range p.Families {
391 fmt.Fprintf(w, "\n%s: %s\n", f.Layers[0].Name, f.Action)
392 for _, l := range f.Layers {
393 fmt.Fprintf(w, " %-24s %-10s %s", l.Name, l.State, short(l.Head))
394 if l.Below != "" {
395 fmt.Fprintf(w, " on %s", l.Below)
396 }
397 if c := l.Capacity; c != nil {
398 fmt.Fprintf(w, "; %d/%d automatic, %d/%d versions, update %d/%d, %d/%d bytes",
399 c.Uploads, c.Cap, c.Versions, c.MaxVersions, c.Seq, c.MaxSeq, c.Bytes, c.MaxBytes)
400 }
401 fmt.Fprintln(w)
402 }
403 for _, r := range f.Requests {
404 fmt.Fprintf(w, " request %s at %s, by %s: %s\n", r.Name, short(r.Head), strings.Join(r.By, ", "), r.Why)
405 }
406 for _, why := range f.Reasons {
407 fmt.Fprintf(w, " - %s\n", why)
408 }
409 for _, n := range f.Notes {
410 fmt.Fprintf(w, " note: %s\n", n)
411 }
412 }
413}