diff options
| author | OreoFR <29048345+OreoFR@users.noreply.github.com> | 2026-12-02 06:30:45 +0100 |
|---|---|---|
| committer | OreoFR <29048345+OreoFR@users.noreply.github.com> | 2026-12-02 06:30:45 +0100 |
| commit | 87ef95670073384f0460402b81ea01ce53e0c1a8 (patch) | |
| tree | 31cc1a1795f669272035b0523a576ac4f1a81bf1 /scripts/export_github_metadata.py | |
| parent | 591bd23a71b6df6ed8b7f50fe073fef628e869d7 (diff) | |
| parent | 8422def759cda12c89f918438eeb8d53dd5972a6 (diff) | |
Merge remote-tracking branch 'origin/main' into pr2756fix
Diffstat (limited to 'scripts/export_github_metadata.py')
| -rw-r--r-- | scripts/export_github_metadata.py | 127 |
1 files changed, 127 insertions, 0 deletions
diff --git a/scripts/export_github_metadata.py b/scripts/export_github_metadata.py new file mode 100644 index 000000000..8e2056811 --- /dev/null +++ b/scripts/export_github_metadata.py | |||
| @@ -0,0 +1,127 @@ | |||
| 1 | #!/usr/bin/env python3 | ||
| 2 | """Export public GitHub issue and pull-request metadata without cloning a repository. | ||
| 3 | |||
| 4 | Only public GitHub REST endpoints are queried. No repository source or assets are fetched. | ||
| 5 | """ | ||
| 6 | import argparse | ||
| 7 | import json | ||
| 8 | import os | ||
| 9 | import sys | ||
| 10 | import time | ||
| 11 | import urllib.error | ||
| 12 | import urllib.parse | ||
| 13 | import urllib.request | ||
| 14 | from pathlib import Path | ||
| 15 | |||
| 16 | API = "https://api.github.com" | ||
| 17 | FIELDS = ("id", "number", "html_url", "state", "title", "body", "created_at", "updated_at", "closed_at") | ||
| 18 | COMMENT_FIELDS = ("id", "html_url", "created_at", "updated_at", "body") | ||
| 19 | REVIEW_FIELDS = ("id", "html_url", "state", "submitted_at", "body") | ||
| 20 | |||
| 21 | |||
| 22 | def select(record, fields): | ||
| 23 | result = {key: record.get(key) for key in fields} | ||
| 24 | user = record.get("user") | ||
| 25 | result["author"] = user.get("login") if isinstance(user, dict) else None | ||
| 26 | return result | ||
| 27 | |||
| 28 | |||
| 29 | def fetch_json(url, token=None, retries=3): | ||
| 30 | headers = {"Accept": "application/vnd.github+json", "User-Agent": "leonida-public-metadata-export", | ||
| 31 | "X-GitHub-Api-Version": "2022-11-28"} | ||
| 32 | if token: | ||
| 33 | headers["Authorization"] = "Bearer " + token | ||
| 34 | for attempt in range(retries + 1): | ||
| 35 | try: | ||
| 36 | request = urllib.request.Request(url, headers=headers) | ||
| 37 | with urllib.request.urlopen(request, timeout=30) as response: | ||
| 38 | return json.load(response) | ||
| 39 | except urllib.error.HTTPError as error: | ||
| 40 | remaining = error.headers.get("X-RateLimit-Remaining") | ||
| 41 | reset = error.headers.get("X-RateLimit-Reset") | ||
| 42 | retry_after = error.headers.get("Retry-After") | ||
| 43 | limited = error.code in (429, 502, 503, 504) or (error.code == 403 and remaining == "0") | ||
| 44 | if not limited or attempt == retries: | ||
| 45 | raise | ||
| 46 | if retry_after: | ||
| 47 | delay = max(1, min(60, int(float(retry_after)))) | ||
| 48 | elif remaining == "0" and reset: | ||
| 49 | delay = max(1, min(60, int(reset) - int(time.time()) + 1)) | ||
| 50 | else: | ||
| 51 | delay = min(2 ** attempt, 30) | ||
| 52 | time.sleep(delay) | ||
| 53 | raise RuntimeError("unreachable") | ||
| 54 | |||
| 55 | |||
| 56 | def pages(endpoint, token=None): | ||
| 57 | page = 1 | ||
| 58 | while True: | ||
| 59 | separator = "&" if "?" in endpoint else "?" | ||
| 60 | url = f"{API}{endpoint}{separator}per_page=100&page={page}" | ||
| 61 | records = fetch_json(url, token) | ||
| 62 | if not isinstance(records, list): | ||
| 63 | raise ValueError(f"Expected list at {url}") | ||
| 64 | yield from records | ||
| 65 | if len(records) < 100: | ||
| 66 | break | ||
| 67 | page += 1 | ||
| 68 | |||
| 69 | |||
| 70 | def export(repo, token=None): | ||
| 71 | owner, name = repo.split("/", 1) | ||
| 72 | if not owner or not name or "/" in name: | ||
| 73 | raise ValueError("Repository must be owner/name") | ||
| 74 | base = "/repos/" + urllib.parse.quote(owner, safe="") + "/" + urllib.parse.quote(name, safe="") | ||
| 75 | issues, pulls = [], [] | ||
| 76 | for item in pages(base + "/issues?state=all", token): | ||
| 77 | number = item["number"] | ||
| 78 | entry = select(item, FIELDS) | ||
| 79 | entry["comments"] = [select(c, COMMENT_FIELDS) for c in pages(base + f"/issues/{number}/comments", token)] | ||
| 80 | if "pull_request" in item: | ||
| 81 | entry["reviews"] = [select(r, REVIEW_FIELDS) for r in pages(base + f"/pulls/{number}/reviews", token)] | ||
| 82 | pulls.append(entry) | ||
| 83 | else: | ||
| 84 | issues.append(entry) | ||
| 85 | for collection in (issues, pulls): | ||
| 86 | if len({item["id"] for item in collection}) != len(collection): | ||
| 87 | raise ValueError("Duplicate record IDs detected; export incomplete") | ||
| 88 | return {"repository": repo, "issues": issues, "pull_requests": pulls, | ||
| 89 | "counts": {"issues": len(issues), "pull_requests": len(pulls), | ||
| 90 | "comments": sum(len(i["comments"]) for i in issues + pulls), | ||
| 91 | "reviews": sum(len(i.get("reviews", [])) for i in pulls)}, | ||
| 92 | "scope": "public GitHub API; PR issue comments and PR reviews; no private or deleted records"} | ||
| 93 | |||
| 94 | |||
| 95 | def main(): | ||
| 96 | parser = argparse.ArgumentParser(description=__doc__) | ||
| 97 | parser.add_argument("repository", help="owner/name") | ||
| 98 | parser.add_argument("--output", type=Path, required=True) | ||
| 99 | args = parser.parse_args() | ||
| 100 | try: | ||
| 101 | # Unauthenticated requests prevent exporting a private repository using a | ||
| 102 | # token inherited from the environment. | ||
| 103 | data = export(args.repository) | ||
| 104 | # Atomic replacement: API errors never leave a partial output presented as complete. | ||
| 105 | target = args.output | ||
| 106 | target.parent.mkdir(parents=True, exist_ok=True) | ||
| 107 | temp = target.with_name(target.name + ".tmp") | ||
| 108 | try: | ||
| 109 | with temp.open("w", encoding="utf-8", newline="\n") as stream: | ||
| 110 | stream.write(json.dumps(data, indent=2, ensure_ascii=False) + "\n") | ||
| 111 | temp.replace(target) | ||
| 112 | finally: | ||
| 113 | temp.unlink(missing_ok=True) | ||
| 114 | print(json.dumps(data["counts"], sort_keys=True)) | ||
| 115 | except (ValueError, OSError, urllib.error.URLError, KeyError) as error: | ||
| 116 | print(f"Export failed (no complete output written): {error}", file=sys.stderr) | ||
| 117 | return 1 | ||
| 118 | return 0 | ||
| 119 | |||
| 120 | |||
| 121 | if __name__ == "__main__": | ||
| 122 | try: | ||
| 123 | sys.stdout.reconfigure(errors="replace") | ||
| 124 | except (AttributeError, ValueError, OSError): | ||
| 125 | pass | ||
| 126 | sys.exit(main()) | ||
| 127 | |||