-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch_plugin_contributors.py
More file actions
196 lines (158 loc) · 6.44 KB
/
fetch_plugin_contributors.py
File metadata and controls
196 lines (158 loc) · 6.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#!/usr/bin/env python3
"""Fetch plugin repos and aggregate contributors into a local JSON file."""
import argparse
import asyncio
import json
import os
import re
import time
from typing import Dict, Iterable, List, Optional, Tuple
import aiohttp
from tqdm import tqdm
PLUGINS_API = "https://api.soulter.top/astrbot/plugins"
GITHUB_API = "https://api.github.com/repos/{owner}/{repo}/contributors"
PER_PAGE = 100
OUT_FILE = "plugins-contributors.json"
def parse_repo_info(plugin: Dict) -> Optional[Dict[str, str]]:
repo_field = (
plugin.get("repo")
or plugin.get("repository")
or plugin.get("github")
or plugin.get("url")
or ""
)
if not repo_field:
return None
if "github.com" in repo_field:
match = re.search(r"github.com/([\w.-]+)/([\w.-]+)", repo_field, re.I)
if match:
return {"owner": match.group(1), "name": match.group(2)}
parts = repo_field.split("/")
if len(parts) == 2:
return {"owner": parts[0], "name": parts[1]}
return None
def normalize_plugins_payload(payload) -> Iterable[Dict]:
if isinstance(payload, dict):
return payload.values()
if isinstance(payload, list):
return payload
return []
async def fetch_json(session: aiohttp.ClientSession, url: str) -> Optional[object]:
async with session.get(url, timeout=aiohttp.ClientTimeout(total=30)) as resp:
if resp.status == 200:
return await resp.json()
return None
async def fetch_contributors(
session: aiohttp.ClientSession,
repo: Dict[str, str],
sem: asyncio.Semaphore,
retries: int,
) -> Tuple[Dict[str, str], Optional[List[Dict]], Optional[str]]:
base_url = GITHUB_API.format(owner=repo["owner"], repo=repo["name"])
contributors: List[Dict] = []
page = 1
while True:
page_url = f"{base_url}?per_page={PER_PAGE}&page={page}"
page_loaded = False
for attempt in range(retries + 1):
try:
async with sem:
async with session.get(
page_url, timeout=aiohttp.ClientTimeout(total=30)
) as resp:
if resp.status == 200:
data = await resp.json()
if not data:
return repo, contributors, None
contributors.extend(data)
page_loaded = True
if len(data) < PER_PAGE:
return repo, contributors, None
page += 1
break
if resp.status in (403, 429) and attempt < retries:
print(
f"Rate limited when fetching {repo['owner']}/{repo['name']} page {page}, "
f"retrying... (attempt {attempt + 1})"
)
await asyncio.sleep(1.5 + attempt)
continue
return repo, None, f"{resp.status}"
except asyncio.TimeoutError:
if attempt < retries:
await asyncio.sleep(1.0 + attempt)
continue
return repo, None, "timeout"
except aiohttp.ClientError as exc:
return repo, None, str(exc)
if not page_loaded:
return repo, None, "unknown"
async def main_async(concurrency: int, retries: int, token: Optional[str]) -> None:
headers = {"User-Agent": "astrbot-contributors-script"}
if token:
headers["Authorization"] = f"Bearer {token}"
async with aiohttp.ClientSession(headers=headers) as session:
plugins_payload = await fetch_json(session, PLUGINS_API)
if plugins_payload is None:
raise RuntimeError("Failed to fetch plugin list.")
repos = []
for plugin in normalize_plugins_payload(plugins_payload):
info = parse_repo_info(plugin)
if info:
repos.append(info)
repos = list({(r["owner"], r["name"]): r for r in repos}.values())
sem = asyncio.Semaphore(concurrency)
tasks = [
fetch_contributors(session, repo, sem=sem, retries=retries) for repo in repos
]
contributors_map: Dict[str, Dict] = {}
skipped = []
with tqdm(total=len(tasks), desc="Fetching contributors") as pbar:
for coro in asyncio.as_completed(tasks):
repo, contributors, error = await coro
pbar.update(1)
if not contributors:
skipped.append({"repo": repo, "error": error})
continue
for c in contributors:
key = c.get("login") or c.get("name")
if not key:
continue
existing = contributors_map.get(key, {})
contributors_map[key] = {
**c,
"contributions": existing.get("contributions", 0)
+ c.get("contributions", 0),
}
print(contributors_map)
output = {
"generated_at": int(time.time()),
"repo_count": len(repos),
"contributor_count": len(contributors_map),
"contributors": sorted(
contributors_map.values(),
key=lambda x: x.get("contributions", 0),
reverse=True,
),
"skipped": skipped,
}
with open(OUT_FILE, "w", encoding="utf-8") as f:
json.dump(output, f, ensure_ascii=False, indent=2)
print(
f"Saved {output['contributor_count']} contributors from "
f"{output['repo_count']} repos -> {OUT_FILE}\n"
f"Skipped {len(skipped)} repos."
)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--concurrency", type=int, default=50)
parser.add_argument("--retries", type=int, default=2)
parser.add_argument("--token-file", type=str, default=".github_token")
args = parser.parse_args()
token = None
if args.token_file and os.path.exists(args.token_file):
with open(args.token_file, "r", encoding="utf-8") as f:
token = f.read().strip() or None
asyncio.run(main_async(args.concurrency, args.retries, token))
if __name__ == "__main__":
main()