gunk-dev/the-valley

main.go

sourcef703cb5df113main's published tip history
27.3 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// `valley-restacker once --report-only` reads one snapshot of origin and
6// says which families it would restack, which it would hold and why, and
7// what capacity allows. For each family it would restack or hold, it
8// builds every write a pass would make, in its scratch repository, and
9// shows them: the one branch push, each change's next version and each
10// recorded change's report (build.go). It decides the journal of an
11// earlier operation, if the state directory holds one, as recovery would
12// (recover.go). It pushes nothing, and writes no journal.
13//
14// It talks to origin only over git, as a client, from a scratch repository
15// under its state directory. Hooks and external filters are off there:
16// the scratch repository's hooks path is /dev/null, and git reads neither
17// the system's nor the user's configuration, nor any the environment
18// injects, so no filter driver is defined. No git variable that points git
19// at another repository, program or configuration reaches anything a pass
20// runs (passes). A service that needs ssh settings passes them in
21// GIT_SSH_COMMAND. The scratch repository commits under the identity its
22// flags give, and never under one inherited from the environment, whether
23// as an identity variable or as configuration.
24//
25// A pass holds a lock on its state directory from start to end, so a
26// second pass on the same directory fails while one runs. The directory
27// belongs to one repository, target and principal, the first a pass used
28// it for, and a pass for any other is refused. Every git, cue and attest a
29// pass runs is killed, with what it started, once the pass's --timeout
30// passes. A pass whose output nobody reads ends then too, and lets go of
31// the lock. A message of its own that nobody reads, such as the error it
32// ends with, is given up on after a few seconds.
33package main
34
35import (
36 "bytes"
37 "context"
38 "encoding/json"
39 "errors"
40 "flag"
41 "fmt"
42 "io"
43 "os"
44 "os/exec"
45 "os/signal"
46 "path/filepath"
47 "strings"
48 "syscall"
49 "time"
50
51 "the-valley/change"
52 "the-valley/composed"
53 "the-valley/rebase"
54)
55
56const usage = `valley-restacker: rebase ready changes onto main when main moves.
57
58usage: valley-restacker once --report-only [flags]
59
60 once --report-only
61 read one snapshot of origin and print what a pass would do: each
62 family, restack or hold with the reason, its capacity, the
63 integration requests it considered, and the writes a pass would
64 make for it, built in the scratch repository and not pushed: the
65 branch push, each change's next version, and each change's
66 report. If the state directory holds a journal of an earlier
67 operation, print what recovery decides of each write it names.
68 Pushes nothing, and writes no journal.
69
70flags:
71 --repo URL origin: the repository the restacker serves (required)
72 --target NAME the target changes are rebased onto (only main)
73 --state DIR where the scratch repository lives (required). A pass
74 locks it, and it belongs to the first repository,
75 target and principal a pass used it for
76 --principal NAME the principal the restacker pushes as (required)
77 --commit-name NAME the name the restacker commits under (default: the
78 principal)
79 --commit-email EMAIL the email it commits under
80 (default: restacker@the-valley.invalid)
81 --timeout DURATION the longest a pass may run, writing its output
82 included; what it runs is killed then (default 10m)
83 --known-signers FILE verifier keys, for landings proved by integrator evidence
84 --integrator-name N the name the integrator signs under
85 --attest PATH the attest helper that checks a note (default: attest on PATH)
86 --instance-repo URL the repository carrying the group's floor
87 --instance-ref REF the ref whose tip carries the floor (refs/heads/main)
88 --instance-policy DIR the floor's directory in that tip (policy/instance)
89 --instance DIR a materialized floor, for a host that serves none
90 --project-policy DIR the project layer, in the target tip (policy/project)
91 --schema FILE the verification schema (VALLEY_VERIFICATION_SCHEMA)
92 --json print the plan as JSON
93`
94
95func main() {
96 if len(os.Args) < 2 {
97 say(os.Stderr, usage)
98 os.Exit(2)
99 }
100 switch os.Args[1] {
101 case "once":
102 // An interrupt or a stop ends the pass as its timeout does: what it
103 // runs is killed, and the lock on its state is let go.
104 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
105 err := once(ctx, os.Args[2:], os.Stdout, os.Stderr)
106 stop()
107 if err != nil {
108 say(os.Stderr, fmt.Sprintf("valley-restacker: %v\n", err))
109 os.Exit(1)
110 }
111 case "help", "-h", "--help":
112 say(os.Stdout, usage)
113 default:
114 say(os.Stderr, fmt.Sprintf("valley-restacker: unknown command %q\n\n%s", os.Args[1], usage))
115 os.Exit(2)
116 }
117}
118
119// sayBound is the longest the process waits to write a message of its
120// own, such as the error it ends with.
121const sayBound = 5 * time.Second
122
123// say writes a message of the process's own, and gives up after sayBound.
124// A stderr nobody reads would otherwise hold the process after its pass
125// has ended and let go of its lock. The write given up on ends with the
126// process.
127func say(w io.Writer, message string) {
128 ctx, cancel := context.WithTimeout(context.Background(), sayBound)
129 defer cancel()
130 _ = writeOut(ctx, w, []byte(message))
131}
132
133// config is a pass's configuration, from flags.
134type config struct {
135 repo, target, state, principal string
136 commitName, commitEmail string
137 timeout time.Duration
138 verify rebase.Verifier
139 floor composed.Floor
140 instanceRepo, projectPolicy string
141 schema, cue string
142 json bool
143}
144
145// defaultEmail is the email the restacker commits under unless
146// --commit-email names another. The .invalid domain is reserved, so the
147// address names no mailbox, as the integrator's does not.
148const defaultEmail = "restacker@the-valley.invalid"
149
150func once(ctx context.Context, args []string, out, errOut io.Writer) error {
151 // What the pass runs inherits no git variable that points git
152 // elsewhere or gives it configuration (passes).
153 controlEnvironment()
154 fs := flag.NewFlagSet("valley-restacker once", flag.ContinueOnError)
155 fs.SetOutput(io.Discard)
156 fs.Usage = func() { say(errOut, usage) }
157 var c config
158 reportOnly := fs.Bool("report-only", false, "")
159 fs.StringVar(&c.repo, "repo", "", "")
160 fs.StringVar(&c.target, "target", rebase.Target, "")
161 fs.StringVar(&c.state, "state", "", "")
162 fs.StringVar(&c.principal, "principal", "", "")
163 fs.StringVar(&c.commitName, "commit-name", "", "")
164 fs.StringVar(&c.commitEmail, "commit-email", defaultEmail, "")
165 fs.DurationVar(&c.timeout, "timeout", 10*time.Minute, "")
166 fs.StringVar(&c.verify.Keys, "known-signers", "", "")
167 fs.StringVar(&c.verify.Signer, "integrator-name", "", "")
168 fs.StringVar(&c.verify.Attest, "attest", "", "")
169 fs.StringVar(&c.instanceRepo, "instance-repo", "", "")
170 fs.StringVar(&c.floor.Ref, "instance-ref", "refs/heads/main", "")
171 fs.StringVar(&c.floor.Dir, "instance-policy", "policy/instance", "")
172 fs.StringVar(&c.floor.Path, "instance", "", "")
173 fs.StringVar(&c.projectPolicy, "project-policy", "policy/project", "")
174 fs.StringVar(&c.schema, "schema", os.Getenv("VALLEY_VERIFICATION_SCHEMA"), "")
175 fs.BoolVar(&c.json, "json", false, "")
176 if err := fs.Parse(args); err != nil {
177 return err
178 }
179 switch {
180 case fs.NArg() > 0:
181 return fmt.Errorf("unexpected argument %q", fs.Arg(0))
182 case !*reportOnly:
183 return errors.New("once needs --report-only: this restacker plans and does not yet push")
184 case c.target != rebase.Target:
185 return fmt.Errorf("--target %s: a change may name only %s as its target", c.target, rebase.Target)
186 }
187 for _, f := range []struct{ flag, value string }{
188 {"--repo", c.repo}, {"--state", c.state}, {"--principal", c.principal}, {"--schema", c.schema},
189 } {
190 if f.value == "" {
191 return fmt.Errorf("%s is required", f.flag)
192 }
193 }
194 if !change.ValidPrincipal(c.principal) {
195 return fmt.Errorf("--principal %q is not a principal", c.principal)
196 }
197 if c.commitName == "" {
198 c.commitName = c.principal
199 }
200 if err := checkIdentity(c.commitName, c.commitEmail); err != nil {
201 return err
202 }
203 if c.timeout <= 0 {
204 return fmt.Errorf("--timeout %v: a pass needs some time to run", c.timeout)
205 }
206 // The floor comes from the instance repository's tip, or from a
207 // directory on disk, and never from both, as for the integrator.
208 if (c.instanceRepo == "") == (c.floor.Path == "") {
209 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")
210 }
211 if c.verify.Attest == "" {
212 c.verify.Attest, _ = exec.LookPath("attest")
213 }
214 var err error
215 if c.cue, err = exec.LookPath("cue"); err != nil {
216 return errors.New("cue is not on the path; the restacker composes the policy with it")
217 }
218 release, err := lockState(c.state)
219 if err != nil {
220 return err
221 }
222 defer release()
223 if err := bindState(c.state, binding{Repository: c.repo, Target: c.target, Principal: c.principal}); err != nil {
224 return err
225 }
226 ctx, cancel := context.WithTimeout(ctx, c.timeout)
227 defer cancel()
228 g, err := scratchRepo(ctx, c)
229 if err != nil {
230 return timedOut(ctx, c, err)
231 }
232 g.Stderr = errOut
233 p, err := planOnce(ctx, g, c)
234 if err != nil {
235 return timedOut(ctx, c, err)
236 }
237 var plan bytes.Buffer
238 if c.json {
239 enc := json.NewEncoder(&plan)
240 enc.SetIndent("", " ")
241 if err := enc.Encode(p); err != nil {
242 return err
243 }
244 } else {
245 printPlan(&plan, p)
246 }
247 if err := writeOut(ctx, out, plan.Bytes()); err != nil {
248 return timedOut(ctx, c, err)
249 }
250 return nil
251}
252
253// writeOut writes data to out, and gives up once ctx is done. A reader
254// that stops reading holds the write, and would otherwise hold the pass,
255// and the lock on its state, past its --timeout. The write given up on
256// ends with the process.
257func writeOut(ctx context.Context, out io.Writer, data []byte) error {
258 done := make(chan error, 1)
259 go func() {
260 _, err := out.Write(data)
261 done <- err
262 }()
263 select {
264 case err := <-done:
265 return err
266 case <-ctx.Done():
267 return fmt.Errorf("the plan was not written: %w", ctx.Err())
268 }
269}
270
271// timedOut says so when a pass failed because it ran past its timeout.
272func timedOut(ctx context.Context, c config, err error) error {
273 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
274 return fmt.Errorf("the pass ran past its --timeout of %v: %w", c.timeout, err)
275 }
276 return err
277}
278
279// checkIdentity refuses a name or an email git cannot commit under: an
280// empty one, or one with a control character or an angle bracket, which
281// would end the name or the email early in a commit's header.
282func checkIdentity(name, email string) error {
283 for _, f := range []struct{ flag, value string }{{"--commit-name", name}, {"--commit-email", email}} {
284 if strings.TrimSpace(f.value) == "" || strings.ContainsAny(f.value, "<>") ||
285 strings.ContainsFunc(f.value, func(r rune) bool { return r < 0x20 || r == 0x7f }) {
286 return fmt.Errorf("%s %q: a commit's name and email are not empty and hold no angle bracket or control character", f.flag, f.value)
287 }
288 }
289 return nil
290}
291
292// What a pass passes on to the programs it runs. A git variable can point
293// git at another repository (GIT_DIR, GIT_WORK_TREE, GIT_COMMON_DIR,
294// GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY, GIT_ALTERNATE_OBJECT_DIRECTORIES,
295// GIT_NAMESPACE, GIT_GRAFT_FILE, GIT_REPLACE_REF_BASE), at other programs
296// (GIT_EXEC_PATH, GIT_TEMPLATE_DIR), at other attributes (GIT_ATTR_SOURCE)
297// or at another format (GIT_DEFAULT_HASH). It can inject configuration
298// that beats the repository's own: GIT_CONFIG_COUNT with GIT_CONFIG_KEY_<n>
299// and GIT_CONFIG_VALUE_<n>, and GIT_CONFIG_PARAMETERS, so an inherited
300// author.name would beat user.name and an inherited core.hooksPath would
301// turn hooks back on. The other GIT_CONFIG* variables name configuration
302// files. And GIT_AUTHOR_*, GIT_COMMITTER_* and EMAIL give an identity
303// ahead of the configuration. So a pass passes on no GIT_* variable but
304// the ones that say how to reach origin over ssh, and no EMAIL. It drops
305// them from its own environment as it starts (controlEnvironment), so
306// cue, attest and the git that composes the policy run without them too.
307var passedOn = map[string]bool{"GIT_SSH": true, "GIT_SSH_COMMAND": true, "GIT_SSH_VARIANT": true}
308
309// passes reports whether a pass passes on the environment variable named.
310func passes(name string) bool {
311 switch {
312 case name == "EMAIL":
313 return false
314 case strings.HasPrefix(name, "GIT_"):
315 return passedOn[name]
316 }
317 return true
318}
319
320// gitSettings are what a pass sets for every git it runs, scratch
321// repository or not: no system or user configuration, no system
322// attributes, and no question asked at a terminal.
323var gitSettings = [][2]string{
324 {"GIT_CONFIG_NOSYSTEM", "1"},
325 {"GIT_CONFIG_GLOBAL", "/dev/null"},
326 {"GIT_ATTR_NOSYSTEM", "1"},
327 {"GIT_TERMINAL_PROMPT", "0"},
328}
329
330// controlEnvironment leaves the process's own environment holding only
331// what a pass passes on, and gitSettings.
332func controlEnvironment() {
333 for _, kv := range os.Environ() {
334 if name, _, _ := strings.Cut(kv, "="); !passes(name) {
335 os.Unsetenv(name)
336 }
337 }
338 for _, kv := range gitSettings {
339 os.Setenv(kv[0], kv[1])
340 }
341}
342
343// scratchRepo makes, or reuses, the repository a pass reads origin into,
344// and returns git run in it with hooks and configured filters off,
345// committing under the restacker's identity. git there reads no
346// configuration but the repository's, and is given its author and
347// committer explicitly. A commit it rebases keeps its own author: a
348// rebase takes the author from the commit it picks. git there is
349// unattended: it never asks a question, and every git it runs is killed
350// whole once ctx is done.
351//
352// The repository has a work tree, though nothing is ever checked out in
353// it: attest, which digests a version's tree and verifies the
354// integrator's transfer statements, reads only a repository with a work
355// tree.
356func scratchRepo(ctx context.Context, c config) (rebase.Git, error) {
357 dir := filepath.Join(c.state, "scratch")
358 var env []string
359 for _, kv := range os.Environ() {
360 if name, _, _ := strings.Cut(kv, "="); passes(name) {
361 env = append(env, kv)
362 }
363 }
364 for _, kv := range gitSettings {
365 env = append(env, kv[0]+"="+kv[1])
366 }
367 env = append(env,
368 "GIT_AUTHOR_NAME="+c.commitName,
369 "GIT_AUTHOR_EMAIL="+c.commitEmail,
370 "GIT_COMMITTER_NAME="+c.commitName,
371 "GIT_COMMITTER_EMAIL="+c.commitEmail,
372 )
373 g := rebase.Git{Dir: dir, Env: env, Stderr: os.Stderr, Unattended: true}
374 if _, err := os.Stat(filepath.Join(dir, ".git", "HEAD")); err != nil {
375 if err := os.MkdirAll(dir, 0o700); err != nil {
376 return g, err
377 }
378 if err := run(ctx, g, "init", "--quiet"); err != nil {
379 return g, err
380 }
381 }
382 // user.useConfigOnly stops git guessing an identity from the host's
383 // name and the user's account. core.attributesFile is set, since git
384 // otherwise reads the user's own attributes file under
385 // XDG_CONFIG_HOME or HOME whatever configuration it reads, and an
386 // attribute such as merge=union there would change how a rebase
387 // merges. core.fsync makes each object and ref a pass writes durable
388 // before git reports it written, as a journal of writes relies on. The
389 // state directory is bound to one repository (bindState), so origin's
390 // URL is the same every pass.
391 for _, kv := range [][2]string{
392 {"core.hooksPath", "/dev/null"},
393 {"core.fsmonitor", "false"},
394 {"core.attributesFile", "/dev/null"},
395 {"core.fsync", "objects,reference"},
396 {"user.name", c.commitName},
397 {"user.email", c.commitEmail},
398 {"user.useConfigOnly", "true"},
399 {"remote.origin.url", c.repo},
400 } {
401 if err := run(ctx, g, "config", kv[0], kv[1]); err != nil {
402 return g, err
403 }
404 }
405 return g, nil
406}
407
408func run(ctx context.Context, g rebase.Git, args ...string) error {
409 _, err := gitOut(ctx, g, args...)
410 return err
411}
412
413// gitOut runs git as the rebase engine runs it (rebase.Git.Command): killed
414// with what it started once ctx is done, and with the wait for its output
415// bounded.
416func gitOut(ctx context.Context, g rebase.Git, args ...string) (string, error) {
417 cmd := g.Command(ctx, args...)
418 var stderr strings.Builder
419 cmd.Stderr = &stderr
420 b, err := cmd.Output()
421 switch {
422 case ctx.Err() != nil:
423 return "", fmt.Errorf("git %s did not finish: %w", strings.Join(args, " "), ctx.Err())
424 case err != nil && !errors.Is(err, exec.ErrWaitDelay):
425 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))
426 }
427 return string(b), nil
428}
429
430// ancestry is merge-base --is-ancestor, telling "no" (exit 1) apart from a
431// question git could not answer.
432func ancestry(ctx context.Context, g rebase.Git) Ancestry {
433 return func(a, b string) (bool, error) {
434 err := g.Command(ctx, "merge-base", "--is-ancestor", a, b).Run()
435 var exit *exec.ExitError
436 switch {
437 case err == nil || errors.Is(err, exec.ErrWaitDelay):
438 return true, nil
439 case errors.As(err, &exit) && exit.ExitCode() == 1:
440 return false, nil
441 }
442 return false, fmt.Errorf("could not tell whether %s is in %s", short(a), short(b))
443 }
444}
445
446// incoming reads, once for each head asked about, the commits it reaches
447// that tip does not. A head that is not a commit, or is missing, is an
448// error, asked about again as the same error.
449func incoming(ctx context.Context, g rebase.Git, tip string) Incoming {
450 type read struct {
451 commits map[string]bool
452 err error
453 }
454 seen := map[string]read{}
455 return func(head string) (map[string]bool, error) {
456 if r, ok := seen[head]; ok {
457 return r.commits, r.err
458 }
459 var r read
460 out, err := gitOut(ctx, g, "rev-list", head+"^{commit}", "--not", tip)
461 if err != nil {
462 r.err = fmt.Errorf("could not read the commits %s would bring to %s", short(head), rebase.Target)
463 } else {
464 r.commits = map[string]bool{}
465 for _, c := range strings.Fields(out) {
466 r.commits[c] = true
467 }
468 }
469 if ctx.Err() == nil {
470 seen[head] = r
471 }
472 return r.commits, r.err
473 }
474}
475
476// policyCap composes the policy at the target tip and reads the cap on
477// automatic versions: the floor from the instance repository's tip, read
478// over git into the scratch repository, or from --instance; the project
479// layer from the tip.
480func policyCap(ctx context.Context, g rebase.Git, c config, tip string) (int, error) {
481 floor := c.floor
482 if c.instanceRepo != "" {
483 out, err := gitOut(ctx, g, "ls-remote", c.instanceRepo, floor.Ref)
484 if ctx.Err() != nil {
485 return 0, err
486 }
487 oid, _, _ := strings.Cut(out, "\t")
488 if err != nil || !rebase.IsObjectID(oid) {
489 return 0, fmt.Errorf("no instance policy layer: %s has no %s: %s", c.instanceRepo, floor.Ref, composed.Floorless)
490 }
491 if err := run(ctx, g, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", c.instanceRepo, oid); err != nil {
492 return 0, err
493 }
494 floor.Repo, floor.Ref = g.Dir, oid
495 }
496 instance, done, err := floor.Open(ctx, "valley-restacker-floor")
497 if err != nil {
498 return 0, err
499 }
500 defer done()
501 project, _, doneProject, err := composed.Project(ctx, g.Dir, tip, c.projectPolicy, "valley-restacker-project")
502 if err != nil {
503 return 0, err
504 }
505 defer doneProject()
506 pol, err := composed.Compose(ctx, c.cue, c.schema, instance, project)
507 if err != nil {
508 return 0, err
509 }
510 return CapOf(pol.MaxAutomaticVersions)
511}
512
513// planOnce reads one snapshot and the cap at its tip, decides the journal
514// in the state directory if there is one, plans every family, and builds
515// the writes a pass would make. It pushes nothing, writes no journal, and
516// lets go of what it prepared.
517func planOnce(ctx context.Context, g rebase.Git, c config) (*Plan, error) {
518 s, err := rebase.ReadSnapshot(ctx, g, c.verify)
519 if err != nil {
520 return nil, err
521 }
522 if s.Tip == "" {
523 return nil, fmt.Errorf("origin has no %s", rebase.Target)
524 }
525 cap, err := policyCap(ctx, g, c, s.Tip)
526 if err != nil {
527 return nil, err
528 }
529 p, err := plan(ctx, g, c, s, cap)
530 if err != nil {
531 return nil, err
532 }
533 // --report-only: what is built is shown, and neither kept nor pushed.
534 out, err := build(ctx, g, s, p, c.binding(), p.Operation)
535 if err != nil {
536 return nil, err
537 }
538 out.releasePrepared(ctx, g)
539 return p, nil
540}
541
542// binding is what a pass's state directory and journal belong to.
543func (c config) binding() binding {
544 return binding{Repository: c.repo, Target: c.target, Principal: c.principal}
545}
546
547// plan decides the journal in the state directory, if there is one, and
548// plans every family in the snapshot, with the cap given.
549func plan(ctx context.Context, g rebase.Git, c config, s *rebase.Snapshot, cap int) (*Plan, error) {
550 var attestations []string
551 var requests []Request
552 for ref, oid := range s.Refs {
553 switch {
554 case strings.HasPrefix(ref, rebase.AttestationRefs):
555 attestations = append(attestations, ref+" "+oid)
556 case strings.HasPrefix(ref, rebase.RequestPrefix):
557 requests = append(requests, Request{Name: strings.TrimPrefix(ref, rebase.RequestPrefix), Head: oid})
558 }
559 }
560 p := &Plan{
561 Target: rebase.Target, Tip: s.Tip, Evidence: change.EvidenceFingerprint(attestations), Cap: cap,
562 Operation: newOperation(time.Now()),
563 }
564
565 // The snapshot lists request heads and does not fetch them. They are
566 // fetched here, before any ancestry is read, all at once and then one
567 // by one when that fails, so one head origin cannot serve leaves the
568 // others readable.
569 var heads []string
570 for _, r := range requests {
571 heads = append(heads, r.Head)
572 }
573 if rebase.Fetch(ctx, g, heads...) != nil {
574 for _, h := range heads {
575 _ = rebase.Fetch(ctx, g, h)
576 }
577 }
578 in := incoming(ctx, g, s.Tip)
579
580 j, err := loadJournal(c.state, c.binding())
581 switch {
582 case err != nil:
583 p.Recovery = &Recovery{Journal: filepath.Join(c.state, journalFile), Error: err.Error(), Decisions: []Decision{}}
584 case j != nil:
585 p.Recovery = decide(j, reading{
586 s: s, requests: requests, evidence: p.Evidence, in: in, is: ancestry(ctx, g),
587 have: func(oid string) bool { return run(ctx, g, "cat-file", "-e", oid) == nil },
588 landed: s.IsLanded,
589 })
590 p.Recovery.Journal = filepath.Join(c.state, journalFile)
591 }
592
593 seen := map[string]bool{}
594 for _, n := range s.Changes {
595 if seen[n.ID] || !s.Unlanded(n) {
596 continue
597 }
598 f, err := rebase.Capture(s, rebase.Selection{ID: n.ID, Whole: true})
599 if err != nil {
600 return nil, err
601 }
602 for _, l := range f.Layers {
603 if l.ID != "" {
604 seen[l.ID] = true
605 }
606 }
607 p.Families = append(p.Families, judge(f, s, c.principal, p, requests, in))
608 p.families = append(p.families, f)
609 }
610 return p, nil
611}
612
613// judge decides what a pass would do with one family.
614func judge(f *rebase.Family, s *rebase.Snapshot, principal string, p *Plan, requests []Request, in Incoming) FamilyPlan {
615 fp := FamilyPlan{Reasons: []string{}, Notes: []string{}, Requests: []RequestPlan{}}
616 ready := false
617 for _, l := range f.Layers {
618 lp := LayerPlan{Name: l.Name, ID: l.ID, Branch: l.Branch, Head: l.Head, State: string(l.State())}
619 if l.Below != nil {
620 lp.Below = l.Below.Name
621 }
622 if l.State() == rebase.Ready {
623 ready = true
624 } else {
625 fp.Reasons = append(fp.Reasons, stateLine(l))
626 }
627 fp.Layers = append(fp.Layers, lp)
628 }
629 switch {
630 case !ready:
631 fp.Action = leave
632 return fp
633 case f.FastForwards():
634 fp.Action, fp.Reasons = current, []string{"it already descends from " + rebase.Target + "'s tip"}
635 return fp
636 }
637 if err := f.Check(); err != nil {
638 fp.Reasons = append(fp.Reasons, err.Error())
639 }
640
641 m := membersOf(f)
642 for _, r := range requests {
643 by, err := Relate(r, m, in)
644 if err != nil {
645 fp.Requests = append(fp.Requests, RequestPlan{Name: r.Name, Head: r.Head, By: []string{}, Why: err.Error()})
646 fp.Reasons = append(fp.Reasons, fmt.Sprintf("request %s: whether it is related cannot be determined: %v", r.Name, err))
647 continue
648 }
649 if by == nil {
650 continue
651 }
652 o, found := s.OutcomeOf(r.Name)
653 rp := RequestPlan{Name: r.Name, Head: r.Head, By: by}
654 if found {
655 rp.Decision = o.Decision
656 }
657 rp.Current, rp.Releases, rp.Why = Currency(o, found, r.Head, p.Tip, p.Evidence)
658 switch {
659 case !rp.Releases:
660 fp.Reasons = append(fp.Reasons, fmt.Sprintf("request %s might still land: %s", r.Name, rp.Why))
661 case o.Decision == "reject":
662 fp.Notes = append(fp.Notes, fmt.Sprintf("request %s was rejected at this head, tip and evidence", r.Name))
663 }
664 fp.Requests = append(fp.Requests, rp)
665 }
666 sortRequests(fp.Requests)
667
668 for i, l := range f.Layers {
669 if l.ID == "" || l.Record == nil {
670 continue
671 }
672 cp := CapacityOf(l.Record, principal, p.Cap, nextSize(l.Name, l.Record, principal))
673 fp.Layers[i].Capacity = cp
674 fp.Reasons = append(fp.Reasons, cp.Over...)
675 }
676 fp.Action = restack
677 if len(fp.Reasons) > 0 {
678 fp.Action = hold
679 }
680 return fp
681}
682
683func printPlan(w io.Writer, p *Plan) {
684 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)
685 if r := p.Recovery; r != nil {
686 printRecovery(w, r)
687 }
688 if len(p.Families) == 0 {
689 fmt.Fprintln(w, "no change to restack")
690 }
691 for _, f := range p.Families {
692 fmt.Fprintf(w, "\n%s: %s\n", f.Layers[0].Name, f.Action)
693 for _, l := range f.Layers {
694 fmt.Fprintf(w, " %-24s %-10s %s", l.Name, l.State, short(l.Head))
695 if l.Below != "" {
696 fmt.Fprintf(w, " on %s", l.Below)
697 }
698 if c := l.Capacity; c != nil {
699 fmt.Fprintf(w, "; %d/%d automatic, %d/%d versions, update %d/%d, %d/%d bytes",
700 c.Uploads, c.Cap, c.Versions, c.MaxVersions, c.Seq, c.MaxSeq, c.Bytes, c.MaxBytes)
701 }
702 fmt.Fprintln(w)
703 }
704 for _, r := range f.Requests {
705 fmt.Fprintf(w, " request %s at %s, by %s: %s\n", r.Name, short(r.Head), strings.Join(r.By, ", "), r.Why)
706 }
707 for _, why := range f.Reasons {
708 fmt.Fprintf(w, " - %s\n", why)
709 }
710 for _, n := range f.Notes {
711 fmt.Fprintf(w, " note: %s\n", n)
712 }
713 if f.Writes != nil {
714 printWrites(w, f.Writes)
715 }
716 }
717}
718
719// printWrites prints what a pass would push for a family.
720func printWrites(w io.Writer, ws *Writes) {
721 fmt.Fprintf(w, " would write, as %s:\n", ws.Result)
722 for _, b := range ws.Branches {
723 fmt.Fprintf(w, " push %s %s -> %s\n", b.Branch, short(b.Old), short(b.New))
724 }
725 for _, v := range ws.Versions {
726 fmt.Fprintf(w, " add %s v%d at %s: record %s, leased on %s\n", v.ID, v.Version, short(v.Head), short(v.Record), short(v.Lease))
727 }
728 for _, r := range ws.Reports {
729 switch {
730 case r.Error != "":
731 fmt.Fprintf(w, " report %s: none fits: %s\n", r.ID, r.Error)
732 case r.Unchanged:
733 fmt.Fprintf(w, " report %s %s: not written, as the current report says the same\n", r.ID, r.Result)
734 default:
735 lease := "none"
736 if r.Lease != "" {
737 lease = short(r.Lease)
738 }
739 fmt.Fprintf(w, " report %s %s: %s, replacing %s\n", r.ID, r.Result, short(r.Commit), lease)
740 }
741 if len(r.Omitted) > 0 {
742 fmt.Fprintf(w, " leaves out %s\n", strings.Join(r.Omitted, ", "))
743 }
744 }
745}
746
747// printRecovery prints what recovery decided of the journal.
748func printRecovery(w io.Writer, r *Recovery) {
749 if r.Error != "" {
750 fmt.Fprintf(w, "recovery: %s\n", r.Error)
751 return
752 }
753 state := "settled"
754 if !r.Settled {
755 state = "not settled"
756 }
757 fmt.Fprintf(w, "recovery: %s, operation %s, %s; nothing is pushed in --report-only\n", r.Journal, r.Operation, state)
758 for _, d := range r.Decisions {
759 what := d.Write
760 if d.ID != "" {
761 what += " " + d.ID
762 }
763 action := d.Action
764 switch {
765 case d.Terminal:
766 action += " (terminal)"
767 case d.Final:
768 action += " (final)"
769 }
770 fmt.Fprintf(w, " family %d %s: %s: %s\n", d.Family, what, action, d.Why)
771 }
772}