gunk-dev/the-valley

main.go

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