Code Issues Pull Requests Actions Packages Projects Releases 15 Wiki Activity Security Code Quality
Files
global-workflow/scripts/gitea-badges/award_badges.py
T
2026-11-19 12:07:05 +07:00

528 lines
21 KiB
Python

#!/usr/bin/env python3
"""
Award Gitea user badges instance-wide, based on activity across all repositories.
Runs from a single scheduled Gitea Actions workflow with a site-admin token.
Stdlib only (no pip install needed on the runner).
Env:
GITEA_URL e.g. https://git.sothink.vn
BADGE_TOKEN site-admin PAT (scopes: read:repository, read:issue, read:user, write:admin)
DRY_RUN "true" -> only print the plan, do not change badges
Optional cache on S3 (RustFS). Facts about closed PRs/issues are stored so each run
only calls the API for PRs/issues that are new or changed since the last run:
CACHE_S3_ENDPOINT e.g. https://rustfs.sothink.vn
CACHE_S3_BUCKET bucket name
CACHE_S3_KEY object key (default: gitea-badges/cache.json.gz)
CACHE_S3_REGION default: us-east-1
AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY
CACHE_REBUILD "true" -> ignore the stored cache, rescan everything, save fresh
Without CACHE_S3_ENDPOINT/BUCKET/keys the script runs a full scan (no cache).
"""
import argparse
import http.client
import json
import os
import re
import socket
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from s3cache import S3Object
PAGE = 50
CACHE_VERSION = 3
COAUTHOR_RE = re.compile(r"^\s*co-authored-by:\s*.*?<([^>]+)>\s*$", re.I | re.M)
# --------------------------------------------------------------------------- API
class ApiError(RuntimeError):
def __init__(self, msg, code=None):
super().__init__(msg)
self.code = code
class Gitea:
RETRY_CODES = {429, 500, 502, 503, 504}
def __init__(self, url, token, timeout=120, retries=3, slow=15):
self.base = url.rstrip("/") + "/api/v1"
self.token = token
self.timeout = timeout
self.retries = retries
self.slow = slow # log requests slower than this (seconds)
self.timings = [] # (seconds, "GET /path?query", outcome)
self.requests = 0
self._lock = threading.Lock()
def call(self, method, path, params=None, body=None):
with self._lock:
self.requests += 1
url = self.base + path
if params:
url += "?" + urllib.parse.urlencode(params)
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Authorization", f"token {self.token}")
req.add_header("Accept", "application/json")
if data is not None:
req.add_header("Content-Type", "application/json")
label = f"{method} {path}" + (f"?{urllib.parse.urlencode(params)}" if params else "")
for attempt in range(1, self.retries + 1):
t = time.monotonic()
outcome = "ok"
try:
with urllib.request.urlopen(req, timeout=self.timeout) as r:
raw = r.read()
return json.loads(raw) if raw else None
except urllib.error.HTTPError as e:
outcome = f"HTTP {e.code}"
msg = e.read().decode(errors="replace")[:300]
err = ApiError(f"{method} {path} -> HTTP {e.code}: {msg}", e.code)
if e.code not in self.RETRY_CODES or method != "GET":
raise err from None
except (OSError, http.client.HTTPException) as e: # timeouts, resets, URLError
outcome = f"{type(e).__name__}: {e}"
read_timeout = isinstance(e, socket.timeout) and getattr(e, "errno", None) is None
err = ApiError(f"{label} -> {type(e).__name__}: {e} "
f"(after {time.monotonic() - t:.0f}s, attempt {attempt}/{self.retries})",
"timeout" if read_timeout else None)
if method != "GET" or read_timeout:
raise err from None
finally:
dt = time.monotonic() - t
with self._lock:
self.timings.append((dt, label, outcome))
if dt >= self.slow:
print(f"slow: {dt:6.1f}s {outcome:<10.40} {label}", flush=True)
if attempt < self.retries:
time.sleep(2 * attempt)
with self._lock:
self.requests += 1
raise err
def get(self, path, **params):
return self.call("GET", path, params)
def paged(self, path, key=None, **params):
page = 1
while True:
res = self.get(path, page=page, limit=PAGE, **params)
items = res.get(key, []) if key else (res or [])
yield from items
if len(items) < PAGE:
return
page += 1
def ts(s):
if not s:
return None
return datetime.fromisoformat(s.replace("Z", "+00:00"))
# ------------------------------------------------------------------ collection
class Stats:
def __init__(self):
self.lock = threading.Lock()
self.max_stars = {} # login -> max stars on an owned (non-fork) repo
self.merged_prs = Counter() # login -> merged PRs opened
self.coauthored = Counter() # login -> co-authored commits on merged PRs
self.yolo = set() # merged a PR without an approving review
self.quickdraw = set() # closed an issue/PR within N seconds of opening
self.cache_hits = 0 # merged/quick PRs + quick issues served from cache
self.cache_misses = 0
self.skipped = set() # "owner/repo (pulls|issues: HTTP 404)"
self.partial = [] # per-PR fetch failures (data retried next run)
def timeline_of(api, owner, repo, number):
"""(closer, merger) from the issue/PR timeline — DB only, no git work.
"" when the event is absent, None on API error."""
try:
closer = merger = ""
for ev in api.paged(f"/repos/{owner}/{repo}/issues/{number}/timeline"):
login = (ev.get("user") or {}).get("login")
if not login:
continue
if ev.get("type") in ("close", "merge_pull"):
closer = login
if ev.get("type") == "merge_pull":
merger = login
return closer, merger
except RuntimeError:
return None, None
def scan_repo(api, repo, cfg, users, email_map, stats, old):
"""Scan one repo. `old` is this repo's cache entry from the last run (or None).
Cache entry layout (keys kept short, the file is gzipped JSON):
prs[number] = {"f": [closed_at, merged], "mb": merger, "ok": approved?,
"co": [[emails]...], "q": closer}
issues[number] = {"f": closed_at, "q": closer}
"f" is the fingerprint: if closed_at/merged changed (reopened, re-closed) the entry is
discarded and refetched. Only PRs/issues that are merged or quickdraw-relevant are stored,
and only those still present in the current "closed" listing are written back.
Gitea endpoints that run git (/pulls, /pulls/{n}, /pulls/{n}/commits) can take minutes on
big repos, so: PRs are listed via /issues?type=pulls, merger/closer come from the timeline
(DB only), and only the co-author scan touches /pulls/{n}/commits. A failure on a single PR
is recorded in stats.partial and left out of the cache, so the next run retries just that PR.
A disabled issues/PR unit (HTTP 403/404 on the listing) is skipped, not an error.
"""
owner, name = repo["owner"]["login"], repo["name"]
quick = cfg["quickdraw_seconds"]
scan_co = cfg.get("scan_coauthors", True)
old = old or {}
old_prs, old_iss = old.get("prs", {}), old.get("issues", {})
new_prs, new_iss = {}, {}
local_merged, local_coauth = Counter(), Counter()
local_yolo, local_quick = set(), set()
hits = misses = 0
def is_quick(item):
c, d = ts(item.get("created_at")), ts(item.get("closed_at"))
return c and d and 0 <= (d - c).total_seconds() <= quick
def entry_for(cache, number, fp):
nonlocal hits, misses
e = cache.get(number)
if e is not None and e.get("f") == fp:
hits += 1
return e
misses += 1
return {"f": fp}
partial = []
def soft(number, what, err):
partial.append(f"{repo['full_name']}#{number} {what}: {err}")
def timeline(entry, number, need_merger):
"""Fill entry["q"] / entry["mb"] from the timeline if missing. False on error."""
if "q" in entry and ("mb" in entry or not need_merger):
return True
closer, merger = timeline_of(api, owner, name, number)
if closer is None:
soft(number, "timeline", "API error")
return False
entry["q"] = closer
if need_merger:
entry["mb"] = merger
return True
def listing(kind):
try:
yield from api.paged(f"/repos/{owner}/{name}/issues", state="closed", type=kind)
except ApiError as e:
if e.code in (403, 404): # unit disabled / external tracker
with stats.lock:
stats.skipped.add(f"{repo['full_name']} ({kind}: HTTP {e.code})")
return
raise
# Pull requests
if repo.get("has_pull_requests", True) and not repo.get("mirror"):
for pr in listing("pulls"):
meta = pr.get("pull_request") or {}
merged, quickpr = bool(meta.get("merged") or meta.get("merged_at")), is_quick(pr)
if not merged and not quickpr:
continue
num = str(pr["number"])
poster = (pr.get("user") or {}).get("login")
e = entry_for(old_prs, num, [pr.get("closed_at"), merged])
new_prs[num] = e
n = pr["number"]
have_tl = timeline(e, n, need_merger=merged)
if quickpr:
who = (e.get("q") or poster) if have_tl else poster
if who:
local_quick.add(who)
if not merged:
continue
if poster:
local_merged[poster] += 1
merger = e.get("mb") or ""
if merger:
if "ok" not in e:
try:
reviews = api.get(f"/repos/{owner}/{name}/pulls/{n}/reviews") or []
e["ok"] = any(r.get("state") == "APPROVED" and not r.get("dismissed")
for r in reviews)
except ApiError as err:
if err.code == 404: # PR unit gone (archived repo)
e["ok"] = True
else:
soft(n, "reviews", err)
if e.get("ok") is False:
local_yolo.add(merger)
if scan_co:
if "co" not in e:
try:
co = []
for c in api.paged(f"/repos/{owner}/{name}/pulls/{n}/commits",
stat="false", verification="false", files="false"):
found = COAUTHOR_RE.findall((c.get("commit") or {}).get("message", ""))
if found:
co.append(found)
e["co"] = co
except ApiError as err:
if err.code == 404: # head ref / PR unit gone
e["co"] = []
else:
soft(n, "commits", err)
for emails in e.get("co", []):
seen = set()
for email in emails:
login = resolve_email(email, email_map, users, cfg)
if login and login not in seen:
seen.add(login)
local_coauth[login] += 1
# Issues (Quickdraw)
if repo.get("has_issues", True) and not repo.get("mirror"):
for iss in listing("issues"):
if not is_quick(iss):
continue
num = str(iss["number"])
poster = (iss.get("user") or {}).get("login")
e = entry_for(old_iss, num, iss.get("closed_at"))
new_iss[num] = e
who = (e.get("q") or poster) if timeline(e, iss["number"], False) else poster
if who:
local_quick.add(who)
with stats.lock:
stats.merged_prs.update(local_merged)
stats.coauthored.update(local_coauth)
stats.yolo |= local_yolo
stats.quickdraw |= local_quick
stats.cache_hits += hits
stats.cache_misses += misses
stats.partial.extend(partial)
return {"name": repo["full_name"], "prs": new_prs, "issues": new_iss}
def resolve_email(email, email_map, users, cfg):
email = email.strip().lower()
if email in email_map:
return email_map[email]
local, _, domain = email.partition("@")
# Gitea "keep email private" addresses: <login>@<NO_REPLY_ADDRESS>
nr = (cfg.get("noreply_domain") or "").lower()
if (nr and domain == nr) or domain.startswith("noreply."):
login = local.split("+")[-1]
if login in users:
return login
return None
# --------------------------------------------------------------------- badges
def badge_slug(b):
"""Gitea's /admin/users/{u}/badges returns the raw DB model (no json tags),
so keys are "Slug"/"ID"/... — accept both spellings to be safe."""
return b.get("slug") or b.get("Slug")
def metric_values(stats, login):
return {
"max_stars": stats.max_stars.get(login, -1), # -1 => owns no repo
"merged_prs": stats.merged_prs.get(login, 0),
"coauthored_commits": stats.coauthored.get(login, 0),
"yolo": 1 if login in stats.yolo else 0,
"quickdraw": 1 if login in stats.quickdraw else 0,
}
def desired_badges(values, families, tier_mode):
want = set()
for fam in families:
if fam.get("manual"):
continue
v = values.get(fam["metric"], 0)
reached = [t for t in sorted(fam["tiers"], key=lambda t: t["min"]) if v >= t["min"]]
if not reached:
continue
if tier_mode == "all":
want.update(t["slug"] for t in reached)
else:
want.add(reached[-1]["slug"])
return want
def open_cache():
"""S3Object for the cache, or None if not configured."""
env = os.environ.get
endpoint, bucket = env("CACHE_S3_ENDPOINT"), env("CACHE_S3_BUCKET")
ak, sk = env("AWS_ACCESS_KEY_ID"), env("AWS_SECRET_ACCESS_KEY")
if not (endpoint and bucket and ak and sk):
print("cache: disabled (CACHE_S3_ENDPOINT/CACHE_S3_BUCKET/AWS_* not set)")
return None
return S3Object(endpoint, bucket, env("CACHE_S3_KEY") or "gitea-badges/cache.json.gz",
ak, sk, env("CACHE_S3_REGION") or "us-east-1")
def load_cache(store, cfg):
empty = {"version": CACHE_VERSION, "repos": {}}
if store is None:
return empty
if os.environ.get("CACHE_REBUILD", "false").lower() in ("1", "true", "yes"):
print("cache: rebuild requested, ignoring stored cache")
return empty
try:
data = store.load_json()
except Exception as e: # never fail the run because of the cache
print(f"warn: cache load failed ({e}); full scan")
return empty
if data is None:
print(f"cache: {store.label} not found; full scan")
return empty
# Facts depend on these settings; if they change, rebuild.
sig = {"quickdraw_seconds": cfg["quickdraw_seconds"]}
if data.get("version") != CACHE_VERSION or data.get("settings") != sig:
print("cache: version/settings changed; full scan")
return empty
print(f"cache: loaded {len(data.get('repos', {}))} repos from {store.label}")
return data
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--config", required=True)
args = ap.parse_args()
cfg = json.load(open(args.config))
cfg.setdefault("quickdraw_seconds", 300)
t0 = time.monotonic()
url = os.environ.get("GITEA_URL") or sys.exit("GITEA_URL is required")
token = os.environ.get("BADGE_TOKEN") or sys.exit("BADGE_TOKEN is required")
dry = os.environ.get("DRY_RUN", "false").lower() in ("1", "true", "yes")
api = Gitea(url, token, timeout=cfg.get("timeout", 120), retries=cfg.get("retries", 3),
slow=cfg.get("slow_log_seconds", 15))
exclude = {u.lower() for u in cfg.get("exclude_users", [])}
families = cfg["families"]
managed = {t["slug"] for f in families if not f.get("manual") for t in f["tiers"]}
# Users + e-mail map
users = {}
for u in api.paged("/admin/users"):
if u["login"].lower() in exclude:
continue
users[u["login"]] = u
email_map = {u["email"].lower(): login for login, u in users.items() if u.get("email")}
try:
for e in api.paged("/admin/emails"):
login = e.get("username") or e.get("user_name")
if login in users:
email_map[e["email"].lower()] = login
except RuntimeError as err:
print(f"warn: /admin/emails unavailable ({err}); using primary e-mails only")
print(f"users: {len(users)}")
# Repos
repos = list(api.paged("/repos/search", key="data", private="true"))
print(f"repos: {len(repos)}")
stats = Stats()
for r in repos:
owner = r["owner"]["login"]
if owner in users and not r.get("fork"):
stats.max_stars[owner] = max(stats.max_stars.get(owner, -1), r.get("stars_count", 0))
store = open_cache()
cache = load_cache(store, cfg)
old_repos = cache.get("repos", {})
new_repos = {}
errors = []
with ThreadPoolExecutor(max_workers=cfg.get("workers", 6)) as pool:
futs = {pool.submit(scan_repo, api, r, cfg, users, email_map, stats,
old_repos.get(str(r["id"]))): r
for r in repos}
for f, r in futs.items():
rid = str(r["id"])
try:
new_repos[rid] = f.result()
except Exception as e: # keep going; report at the end
errors.append(f"{r['full_name']}: {e}")
if rid in old_repos: # keep last good data for this repo
new_repos[rid] = old_repos[rid]
t_scan = time.monotonic() - t0
print(f"scan: {t_scan:.1f}s, {api.requests} API requests, "
f"cache hits {stats.cache_hits} / misses {stats.cache_misses}")
if stats.partial:
print(f"partial: {len(stats.partial)} PR/issue fetch(es) failed (retried next run):")
for line in stats.partial[:30]:
print(f" {line}")
if len(stats.partial) > 30:
print(f" ... {len(stats.partial) - 30} more")
if stats.skipped:
print("skipped (issues/PR unit disabled or unavailable): " + ", ".join(sorted(stats.skipped)))
top = sorted(api.timings, reverse=True)[:10]
if top and top[0][0] >= 1:
print("slowest requests:")
for dt, label, outcome in top:
print(f" {dt:6.1f}s {outcome:<10.40} {label}")
if store is not None:
try:
size = store.save_json({"version": CACHE_VERSION,
"settings": {"quickdraw_seconds": cfg["quickdraw_seconds"]},
"updated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"repos": new_repos})
print(f"cache: saved {len(new_repos)} repos ({size} bytes) to {store.label}")
except Exception as e:
print(f"warn: cache save failed ({e})")
# Drop excluded bots from awarded sets (e.g. renovate as merger)
stats.yolo -= exclude
stats.quickdraw -= exclude
# Reconcile
revoke = cfg.get("revoke", True)
if (errors or stats.partial) and revoke:
# Missing data => metrics are undercounted => revoking would remove badges wrongly.
print(f"warn: {len(errors)} repo(s) failed, {len(stats.partial)} partial; "
"skipping revocations this run (adds only)")
revoke = False
tier_mode = cfg.get("tier_mode", "highest")
changes = 0
for login in sorted(users):
want = desired_badges(metric_values(stats, login), families, tier_mode)
have = {badge_slug(b) for b in (api.get(f"/admin/users/{login}/badges") or [])} - {None}
add = sorted(want - have)
rm = sorted((have & managed) - want) if revoke else []
if not add and not rm:
continue
changes += 1
print(f"{login}: +{add or '-'} -{rm or '-'} {metric_values(stats, login)}")
if dry:
continue
if add:
api.call("POST", f"/admin/users/{login}/badges", body={"badge_slugs": add})
if rm:
api.call("DELETE", f"/admin/users/{login}/badges", body={"badge_slugs": rm})
print(f"{'[dry-run] ' if dry else ''}users changed: {changes} "
f"(total {time.monotonic() - t0:.1f}s, {api.requests} API requests)")
if errors:
print("errors:\n " + "\n ".join(errors))
sys.exit(1)
if __name__ == "__main__":
main()