-
Notifications
You must be signed in to change notification settings - Fork 220
Add 'Backport Pending' label whenever a PR merges with master #888
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
NickDris
merged 5 commits into
elastic:master
from
NickDris:backport/add-backport-pending-label
Oct 16, 2025
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
667efc4
Add 'Backport Pending' label whenever a PR merges with master
NickDris b1cc505
Switch to BACKPORT_TOKEN and remove unintended import
NickDris 9a98964
Switch to the existing label
NickDris d8e964e
Remove 'PR merged' checks
NickDris 393eca8
Put BACKPORT_TOKEN in the workflow level env
NickDris File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| import json | ||
| import os | ||
| import re | ||
| import sys | ||
| import urllib.error | ||
| import urllib.request | ||
| from dataclasses import dataclass | ||
| from typing import List | ||
|
|
||
| VERSION_LABEL_RE = re.compile(r"^v\d{1,2}$|(^v\d{1,2}\.\d{1,2}$)") | ||
| PENDING_LABEL = "backport pending" | ||
| PENDING_LABEL_COLOR = "fff2bf" | ||
|
|
||
|
|
||
| @dataclass | ||
| class PRInfo: | ||
| number: int | ||
| labels: List[str] | ||
|
|
||
|
|
||
| def load_event() -> dict: | ||
| path = os.environ.get("GITHUB_EVENT_PATH") | ||
| if not path or not os.path.exists(path): | ||
| print("::warning::GITHUB_EVENT_PATH not set or file missing; nothing to do", file=sys.stderr) | ||
| return {} | ||
| with open(path, "r", encoding="utf-8") as f: | ||
| return json.load(f) | ||
|
|
||
|
|
||
| def extract_pr(event: dict) -> PRInfo | None: | ||
| pr = event.get("pull_request") | ||
| if not pr: | ||
| return None | ||
| labels = [lbl.get("name", "") for lbl in pr.get("labels", [])] | ||
| return PRInfo(number=pr["number"], labels=labels) | ||
|
|
||
|
|
||
| def needs_pending_label(info: PRInfo) -> bool: | ||
| has_version_label = any(VERSION_LABEL_RE.match(l) for l in info.labels) | ||
| has_pending = PENDING_LABEL in info.labels | ||
| return not (has_version_label and has_pending) | ||
|
|
||
|
|
||
| def add_label(pr_number: int, label: str) -> None: | ||
| repo = os.environ.get("GITHUB_REPOSITORY") | ||
| token = os.environ.get("BACKPORT_TOKEN") | ||
| if not repo or not token: | ||
| print("::error::Missing GITHUB_REPOSITORY or BACKPORT_TOKEN", file=sys.stderr) | ||
| sys.exit(1) | ||
| owner, repo_name = repo.split("/", 1) | ||
| # First ensure the label exists (create or update color/description) | ||
| ensure_label(owner, repo_name, token) | ||
| url = f"https://api.github.com/repos/{owner}/{repo_name}/issues/{pr_number}/labels" | ||
| body = json.dumps({"labels": [label]}).encode() | ||
| # POST adds label(s) keeping old ones | ||
| req = urllib.request.Request(url, data=body, method="POST") | ||
| req.add_header("Authorization", f"Bearer {token}") | ||
| req.add_header("Accept", "application/vnd.github+json") | ||
| try: | ||
| with urllib.request.urlopen(req) as resp: | ||
| if resp.status not in (200, 201): | ||
| print(f"::error::Failed to add label: HTTP {resp.status}", file=sys.stderr) | ||
| sys.exit(1) | ||
| print(f"Added label '{label}' to PR #{pr_number}") | ||
| except urllib.error.HTTPError as e: | ||
| print(f"::error::HTTP error adding label: {e.code} {e.reason}", file=sys.stderr) | ||
| sys.exit(1) | ||
| except Exception as e: | ||
| print(f"::error::Unexpected error adding label: {e}", file=sys.stderr) | ||
| sys.exit(1) | ||
|
|
||
|
|
||
| def ensure_label(owner: str, repo_name: str, token: str) -> None: | ||
| """Create the Backport Pending label if it does not already exist.""" | ||
| label_api = f"https://api.github.com/repos/{owner}/{repo_name}/labels/{PENDING_LABEL.replace(' ', '%20')}" | ||
| get_req = urllib.request.Request(label_api, method="GET") | ||
| get_req.add_header("Authorization", f"Bearer {token}") | ||
| get_req.add_header("Accept", "application/vnd.github+json") | ||
| try: | ||
| with urllib.request.urlopen(get_req) as resp: | ||
| if resp.status == 200: | ||
| return | ||
| except urllib.error.HTTPError as e: | ||
| print(f"::warning::Failed to check label existence ({e.code})") | ||
| return | ||
| create_api = f"https://api.github.com/repos/{owner}/{repo_name}/labels" | ||
| body = json.dumps({"name": PENDING_LABEL, "color": PENDING_LABEL_COLOR}).encode() | ||
| req = urllib.request.Request(create_api, data=body, method="POST") | ||
| req.add_header("Authorization", f"Bearer {token}") | ||
| req.add_header("Accept", "application/vnd.github+json") | ||
| try: | ||
| with urllib.request.urlopen(req) as resp: | ||
| if resp.status not in (200, 201): | ||
| print(f"::warning::Failed to create label (status {resp.status})") | ||
| except Exception as e: | ||
| print(f"::warning::Error creating label: {e}") | ||
|
|
||
|
|
||
| """ | ||
| Label a PR with 'Backport pending' if it has no version label. | ||
|
|
||
| Expected environment: | ||
| GITHUB_EVENT_PATH: Path to the event JSON (GitHub sets this automatically) | ||
| GITHUB_REPOSITORY: owner/repo | ||
| BACKPORT_TOKEN: token with repo:issues scope (use BACKPORT_TOKEN or a PAT) | ||
|
|
||
| This script is idempotent: if the PR already has a version label (vX.Y) or already | ||
| has the 'Backport Pending' label, it exits without error. | ||
| """ | ||
|
|
||
|
|
||
| def main() -> int: | ||
| event = load_event() | ||
| if not event: | ||
| return 0 | ||
| info = extract_pr(event) | ||
| if not info: | ||
| print("No pull_request object in event; skipping") | ||
| return 0 | ||
| if needs_pending_label(info): | ||
| add_label(info.number, PENDING_LABEL) | ||
| else: | ||
| print("No label needed (either PR has version label or already pending)") | ||
| return 0 | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| raise SystemExit(main()) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.