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