Add Gitea badges workflow and scripts for awarding badges based on user activity
This commit is contained in:
1 parent
c0a1d50c9d
commit
3a5ec76030
5 files changed
+414
No files matched your search
@@ -0,0 +1,31 @@
|
||||
name: Gitea badges
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "30 * * * *" # every hour, minute 30
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dry_run:
|
||||
description: "Chỉ in kế hoạch, không gán/gỡ badge"
|
||||
type: boolean
|
||||
default: false
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- scripts/gitea-badges/**
|
||||
- .github/workflows/gitea-badges.yaml
|
||||
|
||||
jobs:
|
||||
award:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Award badges
|
||||
env:
|
||||
GITEA_URL: ${{ vars.GITEA_URL || github.server_url }}
|
||||
BADGE_TOKEN: ${{ secrets.BADGE_ADMIN_TOKEN }}
|
||||
# push -> dry-run để review thay đổi config; schedule -> chạy thật
|
||||
DRY_RUN: ${{ github.event_name == 'push' && 'true' || github.event.inputs.dry_run || 'false' }}
|
||||
run: python3 scripts/gitea-badges/award_badges.py --config scripts/gitea-badges/badges.json
|
||||
Whitespace-only changes.
@@ -0,0 +1,37 @@
|
||||
# Gitea badges
|
||||
|
||||
Gán badge cho user trên toàn instance `git.sothink.vn` dựa trên hoạt động ở **mọi repo**.
|
||||
Workflow `.github/workflows/gitea-badges.yaml` chạy mỗi giờ, quét toàn bộ repo bằng token
|
||||
site-admin, rồi đồng bộ badge qua `POST/DELETE /api/v1/admin/users/{user}/badges`.
|
||||
|
||||
## Điều kiện
|
||||
|
||||
| Badge | Metric | Cách tính |
|
||||
|---|---|---|
|
||||
| YOLO | `yolo` | Người merge một PR không có review `APPROVED` (không bị dismiss) |
|
||||
| Quickdraw | `quickdraw` | Người close issue/PR trong ≤ 300s kể từ lúc tạo (lấy từ timeline, fallback người tạo) |
|
||||
| Starstruck (0/5/10/20) | `max_stars` | Số sao cao nhất trên một repo **do user sở hữu**, không phải fork |
|
||||
| Pair-Extraordinaire (1/5/10/20) | `coauthored_commits` | Số commit trong PR đã merge có trailer `Co-authored-by:` trỏ tới email của user |
|
||||
| Pull-Shark (5/10/50/100) | `merged_prs` | Số PR đã merge do user mở |
|
||||
| Sponsor, Galaxy-Brain | — | `manual: true`, Gitea không có Sponsors/Discussions → script không đụng tới |
|
||||
|
||||
`tier_mode: highest` = mỗi nhóm chỉ giữ tier cao nhất (giống GitHub); `all` = giữ cả tier thấp.
|
||||
`revoke: true` = gỡ badge (managed) khi user không còn đủ điều kiện.
|
||||
`exclude_users` = bot (Renovate…) không bao giờ được tính.
|
||||
|
||||
## Cài đặt
|
||||
|
||||
1. Badge phải có **slug** đúng với giá trị `slug` trong `badges.json` (đang dùng cột Name: `Pull-Shark-Gold`…).
|
||||
2. Tạo PAT của một tài khoản **site admin** với scope: `read:repository`, `read:issue`, `read:user`, `write:admin`.
|
||||
3. Thêm secret `BADGE_ADMIN_TOKEN` cho repo này (Settings → Actions → Secrets).
|
||||
4. (Tuỳ chọn) variable `GITEA_URL` nếu runner phải gọi API qua URL khác `github.server_url`.
|
||||
5. Chạy tay *Gitea badges* với `dry_run = true` để xem kế hoạch, rồi để schedule tự chạy.
|
||||
|
||||
Push thay đổi vào `scripts/gitea-badges/**` sẽ tự chạy ở chế độ dry-run.
|
||||
|
||||
## Test local
|
||||
|
||||
```bash
|
||||
GITEA_URL=https://git.sothink.vn BADGE_TOKEN=xxx DRY_RUN=true \
|
||||
python3 scripts/gitea-badges/award_badges.py --config scripts/gitea-badges/badges.json
|
||||
```
|
||||
@@ -0,0 +1,278 @@
|
||||
#!/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
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from collections import Counter, defaultdict
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime
|
||||
|
||||
PAGE = 50
|
||||
COAUTHOR_RE = re.compile(r"^\s*co-authored-by:\s*.*?<([^>]+)>\s*$", re.I | re.M)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- API
|
||||
class Gitea:
|
||||
def __init__(self, url, token):
|
||||
self.base = url.rstrip("/") + "/api/v1"
|
||||
self.token = token
|
||||
|
||||
def call(self, method, path, params=None, body=None):
|
||||
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")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
raw = r.read()
|
||||
return json.loads(raw) if raw else None
|
||||
except urllib.error.HTTPError as e:
|
||||
msg = e.read().decode(errors="replace")[:300]
|
||||
raise RuntimeError(f"{method} {path} -> HTTP {e.code}: {msg}") from None
|
||||
|
||||
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
|
||||
|
||||
|
||||
def closer_of(api, owner, repo, number, fallback):
|
||||
"""Who closed/merged the issue/PR (from timeline); fallback to the poster."""
|
||||
try:
|
||||
last = None
|
||||
for ev in api.paged(f"/repos/{owner}/{repo}/issues/{number}/timeline"):
|
||||
if ev.get("type") in ("close", "merge_pull") and ev.get("user"):
|
||||
last = ev["user"]["login"]
|
||||
return last or fallback
|
||||
except RuntimeError:
|
||||
return fallback
|
||||
|
||||
|
||||
def scan_repo(api, repo, cfg, users, email_map, stats):
|
||||
owner, name = repo["owner"]["login"], repo["name"]
|
||||
quick = cfg["quickdraw_seconds"]
|
||||
local_merged, local_coauth = Counter(), Counter()
|
||||
local_yolo, local_quick = set(), set()
|
||||
|
||||
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
|
||||
|
||||
# Pull requests
|
||||
if repo.get("has_pull_requests", True) and not repo.get("mirror"):
|
||||
for pr in api.paged(f"/repos/{owner}/{name}/pulls", state="closed"):
|
||||
poster = (pr.get("user") or {}).get("login")
|
||||
if is_quick(pr):
|
||||
who = closer_of(api, owner, name, pr["number"], poster)
|
||||
if who:
|
||||
local_quick.add(who)
|
||||
if not pr.get("merged"):
|
||||
continue
|
||||
if poster:
|
||||
local_merged[poster] += 1
|
||||
|
||||
merger = (pr.get("merged_by") or {}).get("login")
|
||||
if merger and merger not in stats.yolo and merger not in local_yolo:
|
||||
reviews = api.get(f"/repos/{owner}/{name}/pulls/{pr['number']}/reviews") or []
|
||||
approved = any(r.get("state") == "APPROVED" and not r.get("dismissed")
|
||||
for r in reviews)
|
||||
if not approved:
|
||||
local_yolo.add(merger)
|
||||
|
||||
if cfg.get("scan_coauthors", True):
|
||||
for c in api.paged(f"/repos/{owner}/{name}/pulls/{pr['number']}/commits",
|
||||
stat="false", verification="false", files="false"):
|
||||
msg = (c.get("commit") or {}).get("message", "")
|
||||
seen = set()
|
||||
for email in COAUTHOR_RE.findall(msg):
|
||||
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 api.paged(f"/repos/{owner}/{name}/issues", state="closed", type="issues"):
|
||||
if is_quick(iss):
|
||||
poster = (iss.get("user") or {}).get("login")
|
||||
who = closer_of(api, owner, name, iss["number"], 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
|
||||
|
||||
|
||||
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 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 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)
|
||||
|
||||
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)
|
||||
|
||||
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))
|
||||
|
||||
errors = []
|
||||
with ThreadPoolExecutor(max_workers=cfg.get("workers", 6)) as pool:
|
||||
futs = {pool.submit(scan_repo, api, r, cfg, users, email_map, stats): r["full_name"]
|
||||
for r in repos}
|
||||
for f, name in futs.items():
|
||||
try:
|
||||
f.result()
|
||||
except Exception as e: # keep going; report at the end
|
||||
errors.append(f"{name}: {e}")
|
||||
|
||||
# Drop excluded bots from awarded sets (e.g. renovate as merger)
|
||||
stats.yolo -= exclude
|
||||
stats.quickdraw -= exclude
|
||||
|
||||
# Reconcile
|
||||
revoke = cfg.get("revoke", True)
|
||||
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 = {b["slug"] for b in (api.get(f"/admin/users/{login}/badges") or [])}
|
||||
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}")
|
||||
if errors:
|
||||
print("errors:\n " + "\n ".join(errors))
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"tier_mode": "highest",
|
||||
"revoke": true,
|
||||
"quickdraw_seconds": 300,
|
||||
"scan_coauthors": true,
|
||||
"workers": 6,
|
||||
"noreply_domain": "noreply.git.sothink.vn",
|
||||
"exclude_users": ["renovate", "renovate-bot", "gitea-actions"],
|
||||
"families": [
|
||||
{
|
||||
"name": "YOLO",
|
||||
"metric": "yolo",
|
||||
"tiers": [{ "slug": "YOLO", "min": 1 }]
|
||||
},
|
||||
{
|
||||
"name": "Quickdraw",
|
||||
"metric": "quickdraw",
|
||||
"tiers": [{ "slug": "Quickdraw", "min": 1 }]
|
||||
},
|
||||
{
|
||||
"name": "Starstruck",
|
||||
"metric": "max_stars",
|
||||
"tiers": [
|
||||
{ "slug": "Starstruck", "min": 0 },
|
||||
{ "slug": "Starstruck-Bronze", "min": 5 },
|
||||
{ "slug": "Starstruck-Silver", "min": 10 },
|
||||
{ "slug": "Starstruck-Gold", "min": 20 }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Pair Extraordinaire",
|
||||
"metric": "coauthored_commits",
|
||||
"tiers": [
|
||||
{ "slug": "Pair-Extraordinaire", "min": 1 },
|
||||
{ "slug": "Pair-Extraordinaire-Bronze", "min": 5 },
|
||||
{ "slug": "Pair-Extraordinaire-Silver", "min": 10 },
|
||||
{ "slug": "Pair-Extraordinaire-Gold", "min": 20 }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Pull Shark",
|
||||
"metric": "merged_prs",
|
||||
"tiers": [
|
||||
{ "slug": "Pull-Shark", "min": 5 },
|
||||
{ "slug": "Pull-Shark-Bronze", "min": 10 },
|
||||
{ "slug": "Pull-Shark-Silver", "min": 50 },
|
||||
{ "slug": "Pull-Shark-Gold", "min": 100 }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Sponsor",
|
||||
"manual": true,
|
||||
"note": "Gitea has no sponsorship feature - award manually",
|
||||
"tiers": [{ "slug": "Sponsor", "min": 1 }]
|
||||
},
|
||||
{
|
||||
"name": "Galaxy Brain",
|
||||
"manual": true,
|
||||
"note": "Gitea has no Discussions - award manually",
|
||||
"tiers": [
|
||||
{ "slug": "Galaxy-Brain", "min": 1 },
|
||||
{ "slug": "Galaxy-Brain-Bronze", "min": 5 },
|
||||
{ "slug": "Galaxy-Brain-Silver", "min": 10 },
|
||||
{ "slug": "Galaxy-Brain-Gold", "min": 20 }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user