Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ event to the router of each enabled feature, in the order of

| Feature | What it does |
| ----------- | ---------------------------------------------------------------------------- |
| `backport` | `needs backport to X.Y` labels, the `[X.Y]` title status, copies labels to backports |
| `backport` | `needs backport to X.Y` labels, the `needs backport to bugfix branches` and `needs backport to security branches` meta labels, the `[X.Y]` title status, copies labels to backports |
| `close_pr` | Closes PRs that merge a maintenance branch into `main` |
| `filepaths` | `docs` and `tests` labels based on the files changed |
| `gh_issue` | The `bedevere/issue-number` status for `gh-NNNNN` in the title |
Expand Down Expand Up @@ -137,6 +137,15 @@ If the GitHub issue referenced in the PR title is labeled `type-feature`,
the same label is added to the PR
- ### Copies main labels to backport
Copies labels from main PRs to backport PRs
- ### Expands meta backport labels on merge
When a PR is merged, replaces `needs backport to bugfix branches` and
`needs backport to security branches` with the matching
`needs backport to X.Y` labels, so the branches are chosen at merge time
rather than when the PR was labelled. "Bugfix" covers branches in bugfix or
prerelease status and "security" covers security-only branches, as listed in
the [release cycle API](https://peps.python.org/api/release-cycle.json);
a security fix needs both labels. Adding a meta label to an already merged PR
expands it straight away.

## PR State Machine

Expand Down
112 changes: 112 additions & 0 deletions bedevere/backport.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

import functools
import re
import sys

import aiohttp
import cachetools
import gidgethub.routing

from . import util
Expand All @@ -29,6 +32,23 @@
"https://devguide.python.org/getting-started/git-boot-camp/#backport-pr"
)

RELEASE_CYCLE_URL = "https://peps.python.org/api/release-cycle.json"
# Meta labels, and the release-cycle statuses of the branches they stand for.
META_BACKPORT_LABELS = {
"needs backport to bugfix branches": frozenset({"bugfix", "prerelease"}),
"needs backport to security branches": frozenset({"security"}),
}
UNRESOLVED_META_LABEL_MESSAGE = (
"Could not look up which branches {labels} currently "
f"means (from {RELEASE_CYCLE_URL}). "
"Add the `needs backport to X.Y` labels by hand, "
"or remove and re-add the label to try again."
)

_release_cycle_cache = cachetools.TTLCache(maxsize=1, ttl=600)
# The last successful lookup, used when a refresh fails.
_last_good_release_cycle = {}


async def _copy_over_labels(gh, original_issue, backport_issue):
"""Copy over relevant labels from the original PR to the backport PR."""
Expand Down Expand Up @@ -75,6 +95,98 @@ async def manage_labels(event, gh, *args, **kwargs):
await _copy_over_labels(gh, original_issue, backport_issue)


async def _branches_by_status(session):
"""Return the release cycle as {status: [branch, ...]}, newest first.

Return None if it cannot be fetched and no earlier copy is available.
"""
try:
return _release_cycle_cache["branches"]
except KeyError:
pass

try:
async with session.get(
RELEASE_CYCLE_URL, timeout=aiohttp.ClientTimeout(total=10)
) as response:
response.raise_for_status()
release_cycle = await response.json()

branches = {}
for release in release_cycle.values():
branches.setdefault(release["status"], []).append(release["branch"])
except Exception as exc:
print(f"Failed to read {RELEASE_CYCLE_URL}: {exc!r}", file=sys.stderr)
return _last_good_release_cycle.get("branches")

_release_cycle_cache["branches"] = branches
_last_good_release_cycle["branches"] = branches
return branches


async def _expand_meta_labels(gh, session, pull_request, meta_labels):
"""Swap meta backport labels for the "needs backport to X.Y" labels."""
issue = await util.issue_for_PR(gh, pull_request)
labels = util.labels(issue)
meta_labels = sorted(labels.intersection(meta_labels))
if not meta_labels:
return

branches_by_status = await _branches_by_status(session)
if branches_by_status is None:
message = UNRESOLVED_META_LABEL_MESSAGE.format(
labels=" and ".join(f"`{label}`" for label in meta_labels)
)
await gh.post(issue["comments_url"], data={"body": message})
return

base_branch = pull_request["base"]["ref"]
statuses = frozenset().union(*(META_BACKPORT_LABELS[m] for m in meta_labels))
backport_labels = []
for status, branches in branches_by_status.items():
if status not in statuses:
continue

for branch in branches:
backport_label = BACKPORT_LABEL.format(branch=branch)
if (
is_maintenance_branch(branch)
and branch != base_branch
and backport_label not in labels
):
backport_labels.append(backport_label)

# Add before removing, so a failure in between leaves the meta label on.
if backport_labels:
await gh.post(issue["labels_url"], data=backport_labels)
for meta_label in meta_labels:
await gh.delete(issue["labels_url"], {"name": meta_label})


@router.register("pull_request", action="closed")
async def expand_meta_labels_on_merge(event, gh, *args, session=None, **kwargs):
"""Expand the meta backport labels when a PR is merged."""
pull_request = event.data["pull_request"]
if not pull_request["merged"]:
return

meta_labels = util.labels(pull_request).intersection(META_BACKPORT_LABELS)
if meta_labels:
await _expand_meta_labels(gh, session, pull_request, meta_labels)


@router.register("pull_request", action="labeled")
async def expand_meta_label_after_merge(event, gh, *args, session=None, **kwargs):
"""Expand a meta backport label added to an already merged PR.

On an open PR the label is left alone until the PR is merged.
"""
pull_request = event.data["pull_request"]
label = util.label_name(event.data)
if label in META_BACKPORT_LABELS and pull_request["merged"]:
await _expand_meta_labels(gh, session, pull_request, {label})


def is_maintenance_branch(ref):
"""
Return True if the ref refers to a maintenance branch.
Expand Down
Loading