#!/usr/bin/env python3 """Removes feature branches that nobody has touched for 30 days. A branch is removed when all of this is true: - its name starts with one of PRUNE_PREFIXES (default `feature/,fix/`): production, develop and the release branches are never touched; - its last commit is older than PRUNE_DAYS (default 30); - no pull request from it is open (an open pull request is work in progress, however quiet). A branch that had a pull request can be brought back from that pull request in Gitea ("Restore branch"), and a merged one is in its target anyway. DRY_RUN=1 only says what would be removed. Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may delete branches), and optionally PRUNE_DAYS, PRUNE_PREFIXES, DRY_RUN. Standard library only. """ import json import os import sys import urllib.error import urllib.parse import urllib.request from datetime import datetime, timedelta, timezone URL = os.environ.get("GT_URL", "").rstrip("/") OWNER = os.environ.get("GT_OWNER", "") REPO = os.environ.get("GT_REPO", "") TOKEN = os.environ.get("GT_TOKEN", "") DAYS = int(os.environ.get("PRUNE_DAYS") or 30) PREFIXES = tuple(p.strip() for p in (os.environ.get("PRUNE_PREFIXES") or "feature/,fix/").split(",") if p.strip()) DRY_RUN = os.environ.get("DRY_RUN", "").strip().lower() in ("1", "true", "yes") NEVER = ("production", "develop") def api(method, path): request = urllib.request.Request( f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}", method=method, headers={"Authorization": f"token {TOKEN}"}, ) try: with urllib.request.urlopen(request, timeout=30) as response: text = response.read().decode() except urllib.error.HTTPError as e: sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}") return json.loads(text) if text else None def pages(path): """Every item of a paged list.""" page, found = 1, [] while True: items = api("GET", f"{path}{'&' if '?' in path else '?'}page={page}&limit=50") or [] found += items if len(items) < 50: return found page += 1 def stale(branches, open_heads, now): """The names to remove, with how many days they were quiet.""" limit = now - timedelta(days=DAYS) names = [] for branch in branches: name = branch["name"] if name in NEVER or name.startswith("release/") or not name.startswith(PREFIXES) or name in open_heads: continue moment = datetime.fromisoformat(branch["commit"]["timestamp"].replace("Z", "+00:00")) if moment < limit: names.append((name, (now - moment).days)) return names def main(): if not (URL and OWNER and REPO and TOKEN): sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.") open_heads = {(pull.get("head") or {}).get("ref") for pull in pages("pulls?state=open")} old = stale(pages("branches"), open_heads, datetime.now(timezone.utc)) if not old: print(f"No {'/'.join(p.rstrip('/') for p in PREFIXES)} branch has been quiet for {DAYS} days.") return for name, days in old: if DRY_RUN: print(f"Would remove {name} (quiet for {days} days).") else: api("DELETE", "branches/" + urllib.parse.quote(name, safe="")) print(f"Removed {name} (quiet for {days} days).") if __name__ == "__main__": main()