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