Datasets:
File size: 3,461 Bytes
bbfe90a | 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 | #!/usr/bin/env python
"""Audit Ruby repo licences; waits for rate-limit reset instead of failing."""
import json
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from urllib.parse import urlparse
import requests
HERE = Path(__file__).resolve().parent
OUT = HERE / "repo_licenses.jsonl"
REPOS = [l.strip() for l in (HERE / "repos.txt").read_text().splitlines() if l.strip()]
def token():
line = [l for l in (Path.home() / ".git-credentials").read_text(errors="ignore").splitlines()
if "github.com" in l][0]
p = urlparse(line)
return p.password or p.username
S = requests.Session()
S.headers.update({
"Authorization": f"Bearer {token()}",
"Accept": "application/vnd.github+json",
"User-Agent": "csn-ruby-license-audit",
})
class Limiter:
def __init__(self, rate):
self.rate = rate
self.next = time.time()
self.lock = threading.Lock()
def wait(self):
with self.lock:
now = time.time()
t = max(self.next, now)
self.next = t + 1.0 / self.rate
if t > now:
time.sleep(t - now)
LIM = Limiter(8.0)
WRITE = threading.Lock()
TODAY = time.strftime("%Y-%m-%d")
def audit(repo):
url = f"https://api.github.com/repos/{repo}/license"
while True:
LIM.wait()
try:
r = S.get(url, timeout=30)
except requests.RequestException:
time.sleep(5)
continue
if r.status_code == 200:
j = r.json()
lic = j.get("license") or {}
return {"repo": repo, "status": "ok", "spdx": lic.get("spdx_id"),
"name": lic.get("name"), "license_url": j.get("html_url"),
"checked_at": TODAY}
if r.status_code == 404:
return {"repo": repo, "status": "no_license", "spdx": None,
"name": None, "license_url": None, "checked_at": TODAY}
if r.status_code in (403, 429):
retry = r.headers.get("Retry-After")
reset = r.headers.get("X-RateLimit-Reset")
if retry:
wait = float(retry)
elif reset:
wait = max(1.0, float(reset) - time.time())
else:
wait = 60.0
print(f"rate limited; sleeping {wait:.0f}s", flush=True)
time.sleep(min(wait + 5, 3600.0))
continue
return {"repo": repo, "status": f"http_{r.status_code}", "spdx": None,
"name": None, "license_url": None, "checked_at": TODAY}
def main():
done = set()
if OUT.exists():
for line in OUT.open(encoding="utf-8"):
try:
done.add(json.loads(line)["repo"])
except Exception:
pass
todo = [r for r in REPOS if r not in done]
print(f"repos={len(REPOS)} done={len(done)} todo={len(todo)}", flush=True)
with OUT.open("a", encoding="utf-8") as f, ThreadPoolExecutor(max_workers=8) as ex:
futs = {ex.submit(audit, r): r for r in todo}
for i, fut in enumerate(as_completed(futs), 1):
rec = fut.result()
with WRITE:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
f.flush()
if i % 250 == 0:
print(f"{i}/{len(todo)}", flush=True)
print("audit done", flush=True)
if __name__ == "__main__":
main()
|