gunk-dev/the-valley

main.go

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