mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 09:08:38 +00:00
The Needs rebase label workflow asked for every open pull request by number, once per attempt. The workflow's token gets 1,000 requests an hour for the whole repository, shared by every run, so with several hundred open runs failed with HTTP 403 "API rate limit exceeded for installation" and labels went stale. A run over every open pull request now reads number, mergeable and labels through the GraphQL API, 100 per request: 3 requests per attempt for 210 open. Since a listing is cheap, its attempts are 60 seconds apart: the three waits give GitHub about the minutes a pass of one request per pull request used to, to compute the merges a push to main reset. What the tool decides and writes is unchanged; --pr still asks for each number, 10 seconds apart. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
191 lines
8.7 KiB
Python
191 lines
8.7 KiB
Python
"""Label the open pull requests that conflict with their base branch `needs rebase`, and unlabel them once they merge.
|
|
|
|
python -I tools/pr_conflict_label.py --repo OWNER/NAME [--pr N] [--dry-run]
|
|
|
|
`.github/workflows/conflict-label.yml` runs this on every push to `main` (a merge can make other pull requests
|
|
conflict) and hourly (a rebase can clear a conflict, and GitHub may not have finished computing a merge). It has no
|
|
per-pull-request trigger: one run per push to every pull request flooded the repository's runners. Every pull request gets reviewed by hand; the label lets a reviewer skip
|
|
the ones that cannot be merged as they stand and tells their authors to rebase.
|
|
|
|
GitHub computes `mergeable` in the background and answers `null` until it has, so a pull request whose answer is
|
|
still unknown is asked again a few times and otherwise left as it is for the next run. A run over every open pull
|
|
request reads them 100 per request through the GraphQL API: the workflow's token gets 1,000 requests an hour for the
|
|
whole repository, and one request per open pull request on every attempt of every run spent them with several hundred
|
|
open, so runs failed with HTTP 403 and the other workflows had none left. A listing is cheap, so its attempts are
|
|
LIST_WAIT seconds apart: three waits give GitHub about the minutes a pass of one request per pull request used to,
|
|
to compute the merges a push to `main` reset. `--pr` still asks for each one by number.
|
|
Only the GitHub API is read and written: no pull request code is checked out or run. The token comes from `GITHUB_TOKEN` (or `GH_TOKEN`); `--dry-run` prints the changes and writes nothing.
|
|
Standard library only; no game files.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import os
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
LABEL = "needs rebase"
|
|
LABEL_COLOR = "d93f0b"
|
|
LABEL_DESCRIPTION = "Conflicts with the base branch: rebase it on main"
|
|
API = "https://api.github.com"
|
|
# Every open pull request, 100 per request: its number, GitHub's merge answer and its labels.
|
|
PULLS_QUERY = """query($owner: String!, $name: String!, $after: String) {
|
|
repository(owner: $owner, name: $name) {
|
|
pullRequests(states: OPEN, first: 100, after: $after) {
|
|
pageInfo { hasNextPage endCursor }
|
|
nodes { number mergeable labels(first: 100) { nodes { name } } }
|
|
}
|
|
}
|
|
}"""
|
|
MERGEABLE = {"MERGEABLE": True, "CONFLICTING": False} # "UNKNOWN": not computed yet
|
|
LIST_WAIT = 60.0 # seconds between the attempts of a run over every open pull request
|
|
|
|
|
|
class ApiError(Exception):
|
|
def __init__(self, status, message):
|
|
super().__init__(f"HTTP {status}: {message}")
|
|
self.status = status
|
|
|
|
|
|
def github_api(token):
|
|
"""A function (method, path, body=None) -> parsed JSON (or None) that calls the GitHub API with `token`: REST,
|
|
and GraphQL at `/graphql`."""
|
|
def call(method, path, body=None):
|
|
data = None if body is None else json.dumps(body).encode("utf-8")
|
|
req = urllib.request.Request(API + path, data=data, method=method, headers={
|
|
"Accept": "application/vnd.github+json",
|
|
"Authorization": f"Bearer {token}",
|
|
"User-Agent": "pr-conflict-label",
|
|
"X-GitHub-Api-Version": "2022-11-28",
|
|
})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
raw = resp.read()
|
|
except urllib.error.HTTPError as e:
|
|
raise ApiError(e.code, e.read().decode("utf-8", "replace")[:300]) from None
|
|
return json.loads(raw) if raw else None
|
|
return call
|
|
|
|
|
|
def decide(mergeable, labeled):
|
|
"""'add', 'remove' or None for a pull request whose `mergeable` is True, False or None (not computed yet)."""
|
|
if mergeable is False and not labeled:
|
|
return "add"
|
|
if mergeable is True and labeled:
|
|
return "remove"
|
|
return None
|
|
|
|
|
|
def open_pulls(api, repo):
|
|
"""{number: (mergeable, labeled)} for every open pull request, read 100 per request. `mergeable` is True, False
|
|
or None (not computed yet)."""
|
|
owner, _, name = repo.partition("/")
|
|
pulls, after = {}, None
|
|
while True:
|
|
answer = api("POST", "/graphql", {"query": PULLS_QUERY,
|
|
"variables": {"owner": owner, "name": name, "after": after}})
|
|
if answer.get("errors") or not (answer.get("data") or {}).get("repository"):
|
|
raise ApiError(200, json.dumps(answer.get("errors"))[:300]) # GraphQL reports its errors in the body
|
|
page = answer["data"]["repository"]["pullRequests"]
|
|
for node in page["nodes"]:
|
|
labeled = any(label.get("name") == LABEL for label in node["labels"]["nodes"])
|
|
pulls[node["number"]] = (MERGEABLE.get(node["mergeable"]), labeled)
|
|
if not page["pageInfo"]["hasNextPage"]:
|
|
return pulls
|
|
after = page["pageInfo"]["endCursor"]
|
|
|
|
|
|
def ensure_label(api, repo):
|
|
try:
|
|
api("POST", f"/repos/{repo}/labels",
|
|
{"name": LABEL, "color": LABEL_COLOR, "description": LABEL_DESCRIPTION})
|
|
except ApiError as e:
|
|
if e.status != 422: # 422: the label exists already
|
|
raise
|
|
|
|
|
|
def apply(api, repo, number, action):
|
|
if action == "add":
|
|
api("POST", f"/repos/{repo}/issues/{number}/labels", {"labels": [LABEL]})
|
|
else:
|
|
try:
|
|
api("DELETE", f"/repos/{repo}/issues/{number}/labels/{urllib.parse.quote(LABEL, safe='')}")
|
|
except ApiError as e:
|
|
if e.status != 404: # 404: someone removed it in between
|
|
raise
|
|
|
|
|
|
def run(api, repo, numbers, dry_run=False, attempts=4, wait=None, sleep=time.sleep, out=print, pulls=None):
|
|
"""Label or unlabel each pull request of `numbers`. Returns {'add': [...], 'remove': [...], 'unknown': [...]}.
|
|
|
|
`pulls` is what open_pulls() answered when `numbers` are all the open pull requests: each attempt then reads
|
|
them again in pages instead of one request per pull request, LIST_WAIT seconds after the last one (10 seconds
|
|
between attempts that ask by number, unless `wait` says otherwise)."""
|
|
if wait is None:
|
|
wait = 10.0 if pulls is None else LIST_WAIT
|
|
done = {"add": [], "remove": [], "unknown": []}
|
|
pending = list(numbers)
|
|
label_ready = dry_run
|
|
for attempt in range(attempts):
|
|
if attempt:
|
|
sleep(wait) # asking for a pull request starts GitHub's merge computation; give it time
|
|
unknown = []
|
|
if pulls is not None and attempt:
|
|
pulls = open_pulls(api, repo)
|
|
for number in pending:
|
|
if pulls is None:
|
|
pr = api("GET", f"/repos/{repo}/pulls/{number}")
|
|
if pr.get("state") != "open":
|
|
continue
|
|
mergeable = pr.get("mergeable")
|
|
labeled = any(label.get("name") == LABEL for label in pr.get("labels", []))
|
|
elif number in pulls:
|
|
mergeable, labeled = pulls[number]
|
|
else:
|
|
continue # closed or merged since it was listed
|
|
if mergeable is None:
|
|
unknown.append(number)
|
|
continue
|
|
action = decide(mergeable, labeled)
|
|
if action is None:
|
|
continue
|
|
out(f"#{number}: {action} '{LABEL}'" + (" (dry run)" if dry_run else ""))
|
|
if not dry_run:
|
|
if action == "add" and not label_ready:
|
|
ensure_label(api, repo)
|
|
label_ready = True
|
|
apply(api, repo, number, action)
|
|
done[action].append(number)
|
|
pending = unknown
|
|
if not pending:
|
|
break
|
|
done["unknown"] = pending
|
|
if pending:
|
|
out("mergeable not computed yet, left for the next run: " + " ".join(f"#{n}" for n in pending))
|
|
return done
|
|
|
|
|
|
def main(argv=None):
|
|
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
|
ap.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY"), help="OWNER/NAME")
|
|
ap.add_argument("--pr", type=int, action="append", help="only this pull request (repeatable)")
|
|
ap.add_argument("--dry-run", action="store_true", help="print the changes, write nothing")
|
|
args = ap.parse_args(argv)
|
|
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
|
|
if not args.repo or not token:
|
|
ap.error("needs --repo (or GITHUB_REPOSITORY) and GITHUB_TOKEN (or GH_TOKEN)")
|
|
api = github_api(token)
|
|
pulls = None if args.pr else open_pulls(api, args.repo)
|
|
numbers = args.pr or sorted(pulls)
|
|
done = run(api, args.repo, numbers, dry_run=args.dry_run, pulls=pulls)
|
|
print(f"{len(numbers)} checked: {len(done['add'])} labeled, {len(done['remove'])} unlabeled, "
|
|
f"{len(done['unknown'])} not computed yet")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.stdout.reconfigure(errors="replace")
|
|
sys.exit(main())
|