diff options
| author | Sarah Boyce <42296566+sarahboyce@users.noreply.github.com> | 2026-10-19 12:47:44 +0200 |
|---|---|---|
| committer | Sarah Boyce <42296566+sarahboyce@users.noreply.github.com> | 2026-10-20 08:59:06 +0200 |
| commit | 2a7992385f9164f4d69f79013c82a9f62cad9934 (patch) | |
| tree | 5c19571c809a189cdfb156a96bb51fc032c2e4be /scripts/github.py | |
| parent | c6ebf51871fa149e88f39ea44aaf700590366607 (diff) | |
Refs #37426 -- Moved scripts GitHub API helpers to a shared module for reuse.
Diffstat (limited to 'scripts/github.py')
| -rw-r--r-- | scripts/github.py | 76 |
1 files changed, 76 insertions, 0 deletions
diff --git a/scripts/github.py b/scripts/github.py new file mode 100644 index 0000000000..c1866b65b5 --- /dev/null +++ b/scripts/github.py @@ -0,0 +1,76 @@ +import json +import urllib.parse +import urllib.request +from datetime import datetime, timedelta, timezone +from http import HTTPStatus + +GITHUB_PER_PAGE = 100 +URLOPEN_TIMEOUT_SECONDS = 15 + + +def github_request(method, path, token, repo, data=None, params=None): + """Make an authenticated GitHub API request.""" + url = f"https://api.github.com/repos/{repo}{path}" + if params: + encoded_params = urllib.parse.urlencode(params) + url = f"{url}?{encoded_params}" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + } + body = None + if data is not None: + body = json.dumps(data).encode() + headers["Content-Type"] = "application/json" + req = urllib.request.Request(url, data=body, headers=headers, method=method) + with urllib.request.urlopen(req, timeout=URLOPEN_TIMEOUT_SECONDS) as response: + if response.status != HTTPStatus.NO_CONTENT: + return json.loads(response.read()) + + +def get_recent_commit_count(pr_author, repo, token, since_days, max_count): + """Return the number of recent commits by the author, up to max_count.""" + if not pr_author: + return 0 + + params = {"author": pr_author, "per_page": max_count, "sha": "main"} + if since_days is not None: + params["since"] = ( + datetime.now(timezone.utc) - timedelta(days=since_days) + ).strftime("%Y-%m-%dT%H:%M:%SZ") + results = github_request( + "GET", + "/commits", + token, + repo, + params=params, + ) + return len(results) + + +def github_results(path, repo, token, params=None): + """Yield all results from a paginated GitHub list endpoint.""" + params = dict(params or {}) + page = 1 + while True: + results = github_request( + "GET", + path, + token, + repo, + params={**params, "per_page": GITHUB_PER_PAGE, "page": page}, + ) + yield from results + if len(results) < GITHUB_PER_PAGE: + return + page += 1 + + +def get_comment_ids_containing_marker(pr_number, repo, token, marker): + return [ + comment["id"] + for comment in github_results(f"/issues/{pr_number}/comments", repo, token) + if marker in (comment["body"] or "") + and comment["user"]["login"] == "github-actions[bot]" + ] |
