| 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, nor any the environment |
| 13 | // injects, so no filter driver is defined. A service that needs ssh |
| 14 | // settings passes them in GIT_SSH_COMMAND. The scratch repository commits |
| 15 | // under the identity its flags give, and never under one inherited from |
| 16 | // the environment, whether as an identity variable or as configuration. |
| 17 | // |
| 18 | // A pass holds a lock on its state directory from start to end, so a |
| 19 | // second pass on the same directory fails while one runs. The directory |
| 20 | // belongs to one repository, target and principal, the first a pass used |
| 21 | // it for, and a pass for any other is refused. Every git, cue and attest a |
| 22 | // pass runs is killed, with what it started, once the pass's --timeout |
| 23 | // passes. A pass whose output nobody reads ends then too, and lets go of |
| 24 | // the lock. |
| 25 | package main |
| 26 | |
| 27 | import ( |
| 28 | "bytes" |
| 29 | "context" |
| 30 | "encoding/json" |
| 31 | "errors" |
| 32 | "flag" |
| 33 | "fmt" |
| 34 | "io" |
| 35 | "os" |
| 36 | "os/exec" |
| 37 | "os/signal" |
| 38 | "path/filepath" |
| 39 | "strings" |
| 40 | "syscall" |
| 41 | "time" |
| 42 | |
| 43 | "the-valley/change" |
| 44 | "the-valley/composed" |
| 45 | "the-valley/rebase" |
| 46 | ) |
| 47 | |
| 48 | const usage = `valley-restacker: rebase ready changes onto main when main moves. |
| 49 | |
| 50 | usage: valley-restacker once --report-only [flags] |
| 51 | |
| 52 | once --report-only |
| 53 | read one snapshot of origin and print what a pass would do: each |
| 54 | family, restack or hold with the reason, its capacity, and the |
| 55 | integration requests it considered. Pushes nothing. |
| 56 | |
| 57 | flags: |
| 58 | --repo URL origin: the repository the restacker serves (required) |
| 59 | --target NAME the target changes are rebased onto (only main) |
| 60 | --state DIR where the scratch repository lives (required). A pass |
| 61 | locks it, and it belongs to the first repository, |
| 62 | target and principal a pass used it for |
| 63 | --principal NAME the principal the restacker pushes as (required) |
| 64 | --commit-name NAME the name the restacker commits under (default: the |
| 65 | principal) |
| 66 | --commit-email EMAIL the email it commits under |
| 67 | (default: restacker@the-valley.invalid) |
| 68 | --timeout DURATION the longest a pass may run, writing its output |
| 69 | included; what it runs is killed then (default 10m) |
| 70 | --known-signers FILE verifier keys, for landings proved by integrator evidence |
| 71 | --integrator-name N the name the integrator signs under |
| 72 | --attest PATH the attest helper that checks a note (default: attest on PATH) |
| 73 | --instance-repo URL the repository carrying the group's floor |
| 74 | --instance-ref REF the ref whose tip carries the floor (refs/heads/main) |
| 75 | --instance-policy DIR the floor's directory in that tip (policy/instance) |
| 76 | --instance DIR a materialized floor, for a host that serves none |
| 77 | --project-policy DIR the project layer, in the target tip (policy/project) |
| 78 | --schema FILE the verification schema (VALLEY_VERIFICATION_SCHEMA) |
| 79 | --json print the plan as JSON |
| 80 | ` |
| 81 | |
| 82 | func main() { |
| 83 | if len(os.Args) < 2 { |
| 84 | fmt.Fprint(os.Stderr, usage) |
| 85 | os.Exit(2) |
| 86 | } |
| 87 | switch os.Args[1] { |
| 88 | case "once": |
| 89 | // An interrupt or a stop ends the pass as its timeout does: what it |
| 90 | // runs is killed, and the lock on its state is let go. |
| 91 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 92 | err := once(ctx, os.Args[2:], os.Stdout) |
| 93 | stop() |
| 94 | if err != nil { |
| 95 | fmt.Fprintf(os.Stderr, "valley-restacker: %v\n", err) |
| 96 | os.Exit(1) |
| 97 | } |
| 98 | case "help", "-h", "--help": |
| 99 | fmt.Print(usage) |
| 100 | default: |
| 101 | fmt.Fprintf(os.Stderr, "valley-restacker: unknown command %q\n\n%s", os.Args[1], usage) |
| 102 | os.Exit(2) |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | // config is a pass's configuration, from flags. |
| 107 | type config struct { |
| 108 | repo, target, state, principal string |
| 109 | commitName, commitEmail string |
| 110 | timeout time.Duration |
| 111 | verify rebase.Verifier |
| 112 | floor composed.Floor |
| 113 | instanceRepo, projectPolicy string |
| 114 | schema, cue string |
| 115 | json bool |
| 116 | } |
| 117 | |
| 118 | // defaultEmail is the email the restacker commits under unless |
| 119 | // --commit-email names another. The .invalid domain is reserved, so the |
| 120 | // address names no mailbox, as the integrator's does not. |
| 121 | const defaultEmail = "restacker@the-valley.invalid" |
| 122 | |
| 123 | func once(ctx context.Context, args []string, out io.Writer) error { |
| 124 | fs := flag.NewFlagSet("valley-restacker once", flag.ContinueOnError) |
| 125 | fs.Usage = func() { fmt.Fprint(os.Stderr, usage) } |
| 126 | var c config |
| 127 | reportOnly := fs.Bool("report-only", false, "") |
| 128 | fs.StringVar(&c.repo, "repo", "", "") |
| 129 | fs.StringVar(&c.target, "target", rebase.Target, "") |
| 130 | fs.StringVar(&c.state, "state", "", "") |
| 131 | fs.StringVar(&c.principal, "principal", "", "") |
| 132 | fs.StringVar(&c.commitName, "commit-name", "", "") |
| 133 | fs.StringVar(&c.commitEmail, "commit-email", defaultEmail, "") |
| 134 | fs.DurationVar(&c.timeout, "timeout", 10*time.Minute, "") |
| 135 | fs.StringVar(&c.verify.Keys, "known-signers", "", "") |
| 136 | fs.StringVar(&c.verify.Signer, "integrator-name", "", "") |
| 137 | fs.StringVar(&c.verify.Attest, "attest", "", "") |
| 138 | fs.StringVar(&c.instanceRepo, "instance-repo", "", "") |
| 139 | fs.StringVar(&c.floor.Ref, "instance-ref", "refs/heads/main", "") |
| 140 | fs.StringVar(&c.floor.Dir, "instance-policy", "policy/instance", "") |
| 141 | fs.StringVar(&c.floor.Path, "instance", "", "") |
| 142 | fs.StringVar(&c.projectPolicy, "project-policy", "policy/project", "") |
| 143 | fs.StringVar(&c.schema, "schema", os.Getenv("VALLEY_VERIFICATION_SCHEMA"), "") |
| 144 | fs.BoolVar(&c.json, "json", false, "") |
| 145 | if err := fs.Parse(args); err != nil { |
| 146 | return err |
| 147 | } |
| 148 | switch { |
| 149 | case fs.NArg() > 0: |
| 150 | return fmt.Errorf("unexpected argument %q", fs.Arg(0)) |
| 151 | case !*reportOnly: |
| 152 | return errors.New("once needs --report-only: this restacker plans and does not yet push") |
| 153 | case c.target != rebase.Target: |
| 154 | return fmt.Errorf("--target %s: a change may name only %s as its target", c.target, rebase.Target) |
| 155 | } |
| 156 | for _, f := range []struct{ flag, value string }{ |
| 157 | {"--repo", c.repo}, {"--state", c.state}, {"--principal", c.principal}, {"--schema", c.schema}, |
| 158 | } { |
| 159 | if f.value == "" { |
| 160 | return fmt.Errorf("%s is required", f.flag) |
| 161 | } |
| 162 | } |
| 163 | if !change.ValidPrincipal(c.principal) { |
| 164 | return fmt.Errorf("--principal %q is not a principal", c.principal) |
| 165 | } |
| 166 | if c.commitName == "" { |
| 167 | c.commitName = c.principal |
| 168 | } |
| 169 | if err := checkIdentity(c.commitName, c.commitEmail); err != nil { |
| 170 | return err |
| 171 | } |
| 172 | if c.timeout <= 0 { |
| 173 | return fmt.Errorf("--timeout %v: a pass needs some time to run", c.timeout) |
| 174 | } |
| 175 | // The floor comes from the instance repository's tip, or from a |
| 176 | // directory on disk, and never from both, as for the integrator. |
| 177 | if (c.instanceRepo == "") == (c.floor.Path == "") { |
| 178 | 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") |
| 179 | } |
| 180 | if c.verify.Attest == "" { |
| 181 | c.verify.Attest, _ = exec.LookPath("attest") |
| 182 | } |
| 183 | var err error |
| 184 | if c.cue, err = exec.LookPath("cue"); err != nil { |
| 185 | return errors.New("cue is not on the path; the restacker composes the policy with it") |
| 186 | } |
| 187 | release, err := lockState(c.state) |
| 188 | if err != nil { |
| 189 | return err |
| 190 | } |
| 191 | defer release() |
| 192 | if err := bindState(c.state, binding{Repository: c.repo, Target: c.target, Principal: c.principal}); err != nil { |
| 193 | return err |
| 194 | } |
| 195 | ctx, cancel := context.WithTimeout(ctx, c.timeout) |
| 196 | defer cancel() |
| 197 | g, err := scratchRepo(ctx, c) |
| 198 | if err != nil { |
| 199 | return timedOut(ctx, c, err) |
| 200 | } |
| 201 | p, err := planOnce(ctx, g, c) |
| 202 | if err != nil { |
| 203 | return timedOut(ctx, c, err) |
| 204 | } |
| 205 | var plan bytes.Buffer |
| 206 | if c.json { |
| 207 | enc := json.NewEncoder(&plan) |
| 208 | enc.SetIndent("", " ") |
| 209 | if err := enc.Encode(p); err != nil { |
| 210 | return err |
| 211 | } |
| 212 | } else { |
| 213 | printPlan(&plan, p) |
| 214 | } |
| 215 | if err := writeOut(ctx, out, plan.Bytes()); err != nil { |
| 216 | return timedOut(ctx, c, err) |
| 217 | } |
| 218 | return nil |
| 219 | } |
| 220 | |
| 221 | // writeOut writes data to out, and gives up once ctx is done. A reader |
| 222 | // that stops reading holds the write, and would otherwise hold the pass, |
| 223 | // and the lock on its state, past its --timeout. The write given up on |
| 224 | // ends with the process. |
| 225 | func writeOut(ctx context.Context, out io.Writer, data []byte) error { |
| 226 | done := make(chan error, 1) |
| 227 | go func() { |
| 228 | _, err := out.Write(data) |
| 229 | done <- err |
| 230 | }() |
| 231 | select { |
| 232 | case err := <-done: |
| 233 | return err |
| 234 | case <-ctx.Done(): |
| 235 | return fmt.Errorf("the plan was not written: %w", ctx.Err()) |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | // timedOut says so when a pass failed because it ran past its timeout. |
| 240 | func timedOut(ctx context.Context, c config, err error) error { |
| 241 | if errors.Is(ctx.Err(), context.DeadlineExceeded) { |
| 242 | return fmt.Errorf("the pass ran past its --timeout of %v: %w", c.timeout, err) |
| 243 | } |
| 244 | return err |
| 245 | } |
| 246 | |
| 247 | // checkIdentity refuses a name or an email git cannot commit under: an |
| 248 | // empty one, or one with a control character or an angle bracket, which |
| 249 | // would end the name or the email early in a commit's header. |
| 250 | func checkIdentity(name, email string) error { |
| 251 | for _, f := range []struct{ flag, value string }{{"--commit-name", name}, {"--commit-email", email}} { |
| 252 | if strings.TrimSpace(f.value) == "" || strings.ContainsAny(f.value, "<>") || |
| 253 | strings.ContainsFunc(f.value, func(r rune) bool { return r < 0x20 || r == 0x7f }) { |
| 254 | 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) |
| 255 | } |
| 256 | } |
| 257 | return nil |
| 258 | } |
| 259 | |
| 260 | // identityVariables are the environment variables git reads an author or a |
| 261 | // committer from ahead of its configuration. The scratch repository's git |
| 262 | // never inherits them: it is given its own author and committer, the |
| 263 | // identity its flags give. |
| 264 | var identityVariables = map[string]bool{ |
| 265 | "GIT_AUTHOR_NAME": true, "GIT_AUTHOR_EMAIL": true, "GIT_AUTHOR_DATE": true, |
| 266 | "GIT_COMMITTER_NAME": true, "GIT_COMMITTER_EMAIL": true, "GIT_COMMITTER_DATE": true, |
| 267 | "EMAIL": true, |
| 268 | } |
| 269 | |
| 270 | // injectsConfiguration reports whether git reads configuration from the |
| 271 | // environment variable named. GIT_CONFIG_COUNT with GIT_CONFIG_KEY_<n> and |
| 272 | // GIT_CONFIG_VALUE_<n>, and GIT_CONFIG_PARAMETERS, add configuration that |
| 273 | // beats the repository's own: an inherited author.name would beat |
| 274 | // user.name, and an inherited core.hooksPath would turn hooks back on. The |
| 275 | // others name configuration files. The scratch repository's git inherits |
| 276 | // none of them. |
| 277 | func injectsConfiguration(name string) bool { |
| 278 | return strings.HasPrefix(name, "GIT_CONFIG") |
| 279 | } |
| 280 | |
| 281 | // scratchRepo makes, or reuses, the repository a pass reads origin into, |
| 282 | // and returns git run in it with hooks and configured filters off, |
| 283 | // committing under the restacker's identity. git there reads no |
| 284 | // configuration but the repository's, and is given its author and |
| 285 | // committer explicitly. A commit it rebases keeps its own author: a |
| 286 | // rebase takes the author from the commit it picks. git there is |
| 287 | // unattended: it never asks a question, and every git it runs is killed |
| 288 | // whole once ctx is done. |
| 289 | // |
| 290 | // The repository has a work tree, though nothing is ever checked out in |
| 291 | // it: attest, which digests a version's tree and verifies the |
| 292 | // integrator's transfer statements, reads only a repository with a work |
| 293 | // tree. |
| 294 | func scratchRepo(ctx context.Context, c config) (rebase.Git, error) { |
| 295 | dir := filepath.Join(c.state, "scratch") |
| 296 | var env []string |
| 297 | for _, kv := range os.Environ() { |
| 298 | if name, _, _ := strings.Cut(kv, "="); !identityVariables[name] && !injectsConfiguration(name) { |
| 299 | env = append(env, kv) |
| 300 | } |
| 301 | } |
| 302 | env = append(env, |
| 303 | "GIT_CONFIG_NOSYSTEM=1", |
| 304 | "GIT_CONFIG_GLOBAL=/dev/null", |
| 305 | "GIT_ATTR_NOSYSTEM=1", |
| 306 | "GIT_TERMINAL_PROMPT=0", |
| 307 | "GIT_AUTHOR_NAME="+c.commitName, |
| 308 | "GIT_AUTHOR_EMAIL="+c.commitEmail, |
| 309 | "GIT_COMMITTER_NAME="+c.commitName, |
| 310 | "GIT_COMMITTER_EMAIL="+c.commitEmail, |
| 311 | ) |
| 312 | g := rebase.Git{Dir: dir, Env: env, Stderr: os.Stderr, Unattended: true} |
| 313 | if _, err := os.Stat(filepath.Join(dir, ".git", "HEAD")); err != nil { |
| 314 | if err := os.MkdirAll(dir, 0o700); err != nil { |
| 315 | return g, err |
| 316 | } |
| 317 | if err := run(ctx, g, "init", "--quiet"); err != nil { |
| 318 | return g, err |
| 319 | } |
| 320 | } |
| 321 | // user.useConfigOnly stops git guessing an identity from the host's |
| 322 | // name and the user's account. The state directory is bound to one |
| 323 | // repository (bindState), so origin's URL is the same every pass. |
| 324 | for _, kv := range [][2]string{ |
| 325 | {"core.hooksPath", "/dev/null"}, |
| 326 | {"core.fsmonitor", "false"}, |
| 327 | {"user.name", c.commitName}, |
| 328 | {"user.email", c.commitEmail}, |
| 329 | {"user.useConfigOnly", "true"}, |
| 330 | {"remote.origin.url", c.repo}, |
| 331 | } { |
| 332 | if err := run(ctx, g, "config", kv[0], kv[1]); err != nil { |
| 333 | return g, err |
| 334 | } |
| 335 | } |
| 336 | return g, nil |
| 337 | } |
| 338 | |
| 339 | func run(ctx context.Context, g rebase.Git, args ...string) error { |
| 340 | _, err := gitOut(ctx, g, args...) |
| 341 | return err |
| 342 | } |
| 343 | |
| 344 | // gitOut runs git as the rebase engine runs it (rebase.Git.Command): killed |
| 345 | // with what it started once ctx is done, and with the wait for its output |
| 346 | // bounded. |
| 347 | func gitOut(ctx context.Context, g rebase.Git, args ...string) (string, error) { |
| 348 | cmd := g.Command(ctx, args...) |
| 349 | var stderr strings.Builder |
| 350 | cmd.Stderr = &stderr |
| 351 | b, err := cmd.Output() |
| 352 | switch { |
| 353 | case ctx.Err() != nil: |
| 354 | return "", fmt.Errorf("git %s did not finish: %w", strings.Join(args, " "), ctx.Err()) |
| 355 | case err != nil && !errors.Is(err, exec.ErrWaitDelay): |
| 356 | return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(stderr.String())) |
| 357 | } |
| 358 | return string(b), nil |
| 359 | } |
| 360 | |
| 361 | // ancestry is merge-base --is-ancestor, telling "no" (exit 1) apart from a |
| 362 | // question git could not answer. |
| 363 | func ancestry(ctx context.Context, g rebase.Git) Ancestry { |
| 364 | return func(a, b string) (bool, error) { |
| 365 | err := g.Command(ctx, "merge-base", "--is-ancestor", a, b).Run() |
| 366 | var exit *exec.ExitError |
| 367 | switch { |
| 368 | case err == nil || errors.Is(err, exec.ErrWaitDelay): |
| 369 | return true, nil |
| 370 | case errors.As(err, &exit) && exit.ExitCode() == 1: |
| 371 | return false, nil |
| 372 | } |
| 373 | return false, fmt.Errorf("could not tell whether %s is in %s", short(a), short(b)) |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | // policyCap composes the policy at the target tip and reads the cap on |
| 378 | // automatic versions: the floor from the instance repository's tip, read |
| 379 | // over git into the scratch repository, or from --instance; the project |
| 380 | // layer from the tip. |
| 381 | func policyCap(ctx context.Context, g rebase.Git, c config, tip string) (int, error) { |
| 382 | floor := c.floor |
| 383 | if c.instanceRepo != "" { |
| 384 | out, err := gitOut(ctx, g, "ls-remote", c.instanceRepo, floor.Ref) |
| 385 | if ctx.Err() != nil { |
| 386 | return 0, err |
| 387 | } |
| 388 | oid, _, _ := strings.Cut(out, "\t") |
| 389 | if err != nil || !rebase.IsObjectID(oid) { |
| 390 | return 0, fmt.Errorf("no instance policy layer: %s has no %s: %s", c.instanceRepo, floor.Ref, composed.Floorless) |
| 391 | } |
| 392 | if err := run(ctx, g, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", c.instanceRepo, oid); err != nil { |
| 393 | return 0, err |
| 394 | } |
| 395 | floor.Repo, floor.Ref = g.Dir, oid |
| 396 | } |
| 397 | instance, done, err := floor.Open(ctx, "valley-restacker-floor") |
| 398 | if err != nil { |
| 399 | return 0, err |
| 400 | } |
| 401 | defer done() |
| 402 | project, _, doneProject, err := composed.Project(ctx, g.Dir, tip, c.projectPolicy, "valley-restacker-project") |
| 403 | if err != nil { |
| 404 | return 0, err |
| 405 | } |
| 406 | defer doneProject() |
| 407 | pol, err := composed.Compose(ctx, c.cue, c.schema, instance, project) |
| 408 | if err != nil { |
| 409 | return 0, err |
| 410 | } |
| 411 | return CapOf(pol.MaxAutomaticVersions) |
| 412 | } |
| 413 | |
| 414 | // planOnce reads one snapshot and plans every family in it. |
| 415 | func planOnce(ctx context.Context, g rebase.Git, c config) (*Plan, error) { |
| 416 | s, err := rebase.ReadSnapshot(ctx, g, c.verify) |
| 417 | if err != nil { |
| 418 | return nil, err |
| 419 | } |
| 420 | if s.Tip == "" { |
| 421 | return nil, fmt.Errorf("origin has no %s", rebase.Target) |
| 422 | } |
| 423 | cap, err := policyCap(ctx, g, c, s.Tip) |
| 424 | if err != nil { |
| 425 | return nil, err |
| 426 | } |
| 427 | var attestations []string |
| 428 | var requests []Request |
| 429 | for ref, oid := range s.Refs { |
| 430 | switch { |
| 431 | case strings.HasPrefix(ref, rebase.AttestationRefs): |
| 432 | attestations = append(attestations, ref+" "+oid) |
| 433 | case strings.HasPrefix(ref, rebase.RequestPrefix): |
| 434 | requests = append(requests, Request{Name: strings.TrimPrefix(ref, rebase.RequestPrefix), Head: oid}) |
| 435 | } |
| 436 | } |
| 437 | p := &Plan{Target: rebase.Target, Tip: s.Tip, Evidence: change.EvidenceFingerprint(attestations), Cap: cap} |
| 438 | |
| 439 | // The snapshot lists request heads and does not fetch them. They are |
| 440 | // fetched here, before any ancestry is read, all at once and then one |
| 441 | // by one when that fails, so one head origin cannot serve leaves the |
| 442 | // others readable. |
| 443 | var heads []string |
| 444 | for _, r := range requests { |
| 445 | heads = append(heads, r.Head) |
| 446 | } |
| 447 | if rebase.Fetch(ctx, g, heads...) != nil { |
| 448 | for _, h := range heads { |
| 449 | _ = rebase.Fetch(ctx, g, h) |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | seen := map[string]bool{} |
| 454 | for _, n := range s.Changes { |
| 455 | if seen[n.ID] || !s.Unlanded(n) { |
| 456 | continue |
| 457 | } |
| 458 | f, err := rebase.Capture(s, rebase.Selection{ID: n.ID, Whole: true}) |
| 459 | if err != nil { |
| 460 | return nil, err |
| 461 | } |
| 462 | for _, l := range f.Layers { |
| 463 | if l.ID != "" { |
| 464 | seen[l.ID] = true |
| 465 | } |
| 466 | } |
| 467 | p.Families = append(p.Families, judge(f, s, c.principal, p, requests, ancestry(ctx, g))) |
| 468 | } |
| 469 | return p, nil |
| 470 | } |
| 471 | |
| 472 | // judge decides what a pass would do with one family. |
| 473 | func judge(f *rebase.Family, s *rebase.Snapshot, principal string, p *Plan, requests []Request, is Ancestry) FamilyPlan { |
| 474 | fp := FamilyPlan{Reasons: []string{}, Notes: []string{}, Requests: []RequestPlan{}} |
| 475 | ready := false |
| 476 | for _, l := range f.Layers { |
| 477 | lp := LayerPlan{Name: l.Name, ID: l.ID, Branch: l.Branch, Head: l.Head, State: string(l.State())} |
| 478 | if l.Below != nil { |
| 479 | lp.Below = l.Below.Name |
| 480 | } |
| 481 | if l.State() == rebase.Ready { |
| 482 | ready = true |
| 483 | } else { |
| 484 | fp.Reasons = append(fp.Reasons, stateLine(l)) |
| 485 | } |
| 486 | fp.Layers = append(fp.Layers, lp) |
| 487 | } |
| 488 | switch { |
| 489 | case !ready: |
| 490 | fp.Action = leave |
| 491 | return fp |
| 492 | case f.FastForwards(): |
| 493 | fp.Action, fp.Reasons = current, []string{"it already descends from " + rebase.Target + "'s tip"} |
| 494 | return fp |
| 495 | } |
| 496 | if err := f.Check(); err != nil { |
| 497 | fp.Reasons = append(fp.Reasons, err.Error()) |
| 498 | } |
| 499 | |
| 500 | m := membersOf(f) |
| 501 | for _, r := range requests { |
| 502 | by, err := Relate(r, m, p.Tip, is) |
| 503 | if err != nil { |
| 504 | fp.Requests = append(fp.Requests, RequestPlan{Name: r.Name, Head: r.Head, By: []string{}, Why: err.Error()}) |
| 505 | fp.Reasons = append(fp.Reasons, fmt.Sprintf("request %s: whether it is related cannot be determined: %v", r.Name, err)) |
| 506 | continue |
| 507 | } |
| 508 | if by == nil { |
| 509 | continue |
| 510 | } |
| 511 | o, found := s.OutcomeOf(r.Name) |
| 512 | rp := RequestPlan{Name: r.Name, Head: r.Head, By: by} |
| 513 | if found { |
| 514 | rp.Decision = o.Decision |
| 515 | } |
| 516 | rp.Current, rp.Releases, rp.Why = Currency(o, found, r.Head, p.Tip, p.Evidence) |
| 517 | switch { |
| 518 | case !rp.Releases: |
| 519 | fp.Reasons = append(fp.Reasons, fmt.Sprintf("request %s might still land: %s", r.Name, rp.Why)) |
| 520 | case o.Decision == "reject": |
| 521 | fp.Notes = append(fp.Notes, fmt.Sprintf("request %s was rejected at this head, tip and evidence", r.Name)) |
| 522 | } |
| 523 | fp.Requests = append(fp.Requests, rp) |
| 524 | } |
| 525 | sortRequests(fp.Requests) |
| 526 | |
| 527 | for i, l := range f.Layers { |
| 528 | if l.ID == "" || l.Record == nil { |
| 529 | continue |
| 530 | } |
| 531 | cp := CapacityOf(l.Record, principal, p.Cap, nextSize(l.Name, l.Record, principal)) |
| 532 | fp.Layers[i].Capacity = cp |
| 533 | fp.Reasons = append(fp.Reasons, cp.Over...) |
| 534 | } |
| 535 | fp.Action = restack |
| 536 | if len(fp.Reasons) > 0 { |
| 537 | fp.Action = hold |
| 538 | } |
| 539 | return fp |
| 540 | } |
| 541 | |
| 542 | func printPlan(w io.Writer, p *Plan) { |
| 543 | 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) |
| 544 | if len(p.Families) == 0 { |
| 545 | fmt.Fprintln(w, "no change to restack") |
| 546 | } |
| 547 | for _, f := range p.Families { |
| 548 | fmt.Fprintf(w, "\n%s: %s\n", f.Layers[0].Name, f.Action) |
| 549 | for _, l := range f.Layers { |
| 550 | fmt.Fprintf(w, " %-24s %-10s %s", l.Name, l.State, short(l.Head)) |
| 551 | if l.Below != "" { |
| 552 | fmt.Fprintf(w, " on %s", l.Below) |
| 553 | } |
| 554 | if c := l.Capacity; c != nil { |
| 555 | fmt.Fprintf(w, "; %d/%d automatic, %d/%d versions, update %d/%d, %d/%d bytes", |
| 556 | c.Uploads, c.Cap, c.Versions, c.MaxVersions, c.Seq, c.MaxSeq, c.Bytes, c.MaxBytes) |
| 557 | } |
| 558 | fmt.Fprintln(w) |
| 559 | } |
| 560 | for _, r := range f.Requests { |
| 561 | fmt.Fprintf(w, " request %s at %s, by %s: %s\n", r.Name, short(r.Head), strings.Join(r.By, ", "), r.Why) |
| 562 | } |
| 563 | for _, why := range f.Reasons { |
| 564 | fmt.Fprintf(w, " - %s\n", why) |
| 565 | } |
| 566 | for _, n := range f.Notes { |
| 567 | fmt.Fprintf(w, " note: %s\n", n) |
| 568 | } |
| 569 | } |
| 570 | } |