|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 OR ISC |
| 3 | + |
| 4 | +""" |
| 5 | +The apply command: cherry-picks the fix onto one local branch per affected branch |
| 6 | +Nothing is pushed and no pull request is opened, the branches are yours to review |
| 7 | +""" |
| 8 | + |
| 9 | +from util.config import AFFECTED, RUN_FILE, UNSURE, BackportError |
| 10 | +from util.git import ( |
| 11 | + WORKTREE_ROOT, |
| 12 | + abort_cherry_pick, |
| 13 | + add_worktree, |
| 14 | + branch_exists, |
| 15 | + cherry_pick, |
| 16 | + cherry_pick_was_empty, |
| 17 | + commit_exists, |
| 18 | + remove_worktree, |
| 19 | +) |
| 20 | +from util.render import ask_yn |
| 21 | + |
| 22 | +import json |
| 23 | +from typing import Dict, List, Optional, Tuple |
| 24 | + |
| 25 | +# What happened to one branch, for the closing report |
| 26 | +PICKED = "picked" |
| 27 | +CONFLICT = "conflict" |
| 28 | +EMPTY = "empty" |
| 29 | +SKIPPED = "skipped" |
| 30 | + |
| 31 | + |
| 32 | +def load_run() -> dict: |
| 33 | + """ |
| 34 | + The run analyze saved, as {generated_at, fix, base, branches, verdicts} |
| 35 | + Written by save_run in util/config.py, where the fields are spelled out |
| 36 | +
|
| 37 | + Raises rather than returning a partial answer, in all three cases where acting on |
| 38 | + the run would mean guessing: there is no run, the file cannot be read, or the fix |
| 39 | + it names is no longer in this checkout |
| 40 | + """ |
| 41 | + try: |
| 42 | + run = json.loads(RUN_FILE.read_text(encoding="utf-8")) |
| 43 | + except FileNotFoundError: |
| 44 | + raise BackportError( |
| 45 | + "no saved analyze run to apply.\n Run 'backport analyze' first." |
| 46 | + ) |
| 47 | + except json.JSONDecodeError as exc: |
| 48 | + raise BackportError(f"{RUN_FILE} is not valid JSON: {exc}") |
| 49 | + |
| 50 | + # These two are the whole input: which commit to pick, and onto which branches |
| 51 | + for key in ("fix", "verdicts"): |
| 52 | + if key not in run: |
| 53 | + raise BackportError(f"{RUN_FILE} has no '{key}'. Re-run analyze.") |
| 54 | + |
| 55 | + # Analyzing a range squashes it into a commit nothing points at, so git can collect |
| 56 | + # it between analyze and apply |
| 57 | + if not commit_exists(run["fix"]): |
| 58 | + raise BackportError( |
| 59 | + f"the analyzed fix {run['fix'][:10]} is not in this checkout any more.\n" |
| 60 | + " Re-run analyze." |
| 61 | + ) |
| 62 | + return run |
| 63 | + |
| 64 | + |
| 65 | +def backport_branch(fix: str, branch: str) -> str: |
| 66 | + """The name of the local branch a backport lands on""" |
| 67 | + return f"backport-{branch}-{fix[:10]}" |
| 68 | + |
| 69 | + |
| 70 | +def pick_targets(verdicts: Dict[str, str], only: Optional[str]) -> List[str]: |
| 71 | + """ |
| 72 | + Which release branches to cherry-pick onto |
| 73 | + Returns the affected ones, or just the named branch. Unsure branches are left |
| 74 | + out: analyze could not settle them, so a cherry-pick would be a guess |
| 75 | + """ |
| 76 | + if only: |
| 77 | + if only not in verdicts: |
| 78 | + known = ", ".join(sorted(verdicts)) |
| 79 | + raise BackportError(f"'{only}' was not in the analyze run.\n Had: {known}") |
| 80 | + return [only] |
| 81 | + return [b for b, state in verdicts.items() if state == AFFECTED] |
| 82 | + |
| 83 | + |
| 84 | +def backport_one(fix: str, branch: str) -> Tuple[str, List[str]]: |
| 85 | + """ |
| 86 | + Cherry-picks the fix onto one release branch in its own worktree |
| 87 | + Returns (outcome, conflicted files). A clean pick leaves the branch and removes |
| 88 | + the worktree; a conflict keeps the worktree so it can be resolved in place |
| 89 | + """ |
| 90 | + local = backport_branch(fix, branch) |
| 91 | + if branch_exists(local): |
| 92 | + return SKIPPED, [] |
| 93 | + |
| 94 | + path = WORKTREE_ROOT / local |
| 95 | + add_worktree(path, local, f"origin/{branch}") |
| 96 | + applied, conflicts = cherry_pick(path, fix) |
| 97 | + |
| 98 | + if applied: |
| 99 | + remove_worktree(path) |
| 100 | + return PICKED, [] |
| 101 | + if not conflicts and cherry_pick_was_empty(path): |
| 102 | + # The fix produced no change here, so this branch already carries it |
| 103 | + abort_cherry_pick(path) |
| 104 | + remove_worktree(path) |
| 105 | + return EMPTY, [] |
| 106 | + return CONFLICT, conflicts |
| 107 | + |
| 108 | + |
| 109 | +def cmd_apply(args) -> int: |
| 110 | + """ |
| 111 | + Cherry-picks the analyzed fix onto every affected branch |
| 112 | + Returns 0 when every branch applied cleanly or was skipped, 1 when any conflicted |
| 113 | + """ |
| 114 | + run = load_run() |
| 115 | + fix, verdicts = run["fix"], run["verdicts"] |
| 116 | + targets = pick_targets(verdicts, args.branch) |
| 117 | + |
| 118 | + if not targets: |
| 119 | + print("No affected branches in the last analyze run, nothing to apply.") |
| 120 | + return 0 |
| 121 | + |
| 122 | + unsure = [b for b, state in verdicts.items() if state == UNSURE] |
| 123 | + print(f"Fix {fix[:10]}, analyzed {run.get('generated_at', 'at an unknown time')}") |
| 124 | + print(f"Backporting onto {len(targets)} branch(es): {', '.join(targets)}") |
| 125 | + if unsure: |
| 126 | + print( |
| 127 | + f"Leaving out {len(unsure)} branch(es) analyze could not settle: " |
| 128 | + f"{', '.join(unsure)}" |
| 129 | + ) |
| 130 | + if not args.yes and not ask_yn("Create these local branches?"): |
| 131 | + print("Aborted. Nothing was created.") |
| 132 | + return 0 |
| 133 | + |
| 134 | + results = {} |
| 135 | + for branch in targets: |
| 136 | + outcome, conflicts = backport_one(fix, branch) |
| 137 | + results[branch] = (outcome, conflicts) |
| 138 | + local = backport_branch(fix, branch) |
| 139 | + if outcome == PICKED: |
| 140 | + print(f" {branch}: applied, on {local}") |
| 141 | + elif outcome == SKIPPED: |
| 142 | + print(f" {branch}: skipped, {local} already exists") |
| 143 | + elif outcome == EMPTY: |
| 144 | + print(f" {branch}: nothing to do, the change is already there") |
| 145 | + else: |
| 146 | + print(f" {branch}: CONFLICT in {len(conflicts)} file(s)") |
| 147 | + for f in conflicts: |
| 148 | + print(f" {f}") |
| 149 | + print(f" resolve in {WORKTREE_ROOT / local}") |
| 150 | + |
| 151 | + conflicted = [b for b, (o, _) in results.items() if o == CONFLICT] |
| 152 | + print() |
| 153 | + print(f"{len(results) - len(conflicted)} of {len(results)} applied cleanly") |
| 154 | + if conflicted: |
| 155 | + print( |
| 156 | + "Resolve each conflict in the worktree named above, then " |
| 157 | + "'git cherry-pick --continue' there." |
| 158 | + ) |
| 159 | + print("Nothing was pushed. Review each branch before you open a pull request.") |
| 160 | + return 1 if conflicted else 0 |
0 commit comments