Fix checkout in jobs without git (export-ignore); prune quiet feature branches after 30 days
This commit is contained in:
1 parent
86ecde31ea
commit
eb93e890d6
9 files changed
+159
-3
No files matched your search
@@ -0,0 +1,93 @@
|
||||
#!/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()
|
||||
@@ -3,9 +3,11 @@
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import check_flow # noqa: E402
|
||||
import prune_branches # noqa: E402
|
||||
import semver # noqa: E402
|
||||
|
||||
TAGS = ["v0.1.0", "v0.2.0", "v0.10.0", "not-a-version"]
|
||||
@@ -70,5 +72,30 @@ class Flow(unittest.TestCase):
|
||||
self.assertEqual(self.check("production", "release/v0.1.0", tags=[], changelog="## v0.1.0 - x\n\n- a\n"), [])
|
||||
|
||||
|
||||
class Prune(unittest.TestCase):
|
||||
NOW = datetime(2026, 12, 4, tzinfo=timezone.utc)
|
||||
|
||||
def branch(self, name, day):
|
||||
return {"name": name, "commit": {"timestamp": f"{day}T10:00:00Z"}}
|
||||
|
||||
def names(self, branches, open_heads=()):
|
||||
return [name for name, _ in prune_branches.stale(branches, set(open_heads), self.NOW)]
|
||||
|
||||
def test_removes_only_quiet_feature_and_fix_branches(self):
|
||||
branches = [
|
||||
self.branch("feature/old", "2026-10-01"), self.branch("fix/old", "2026-11-01"),
|
||||
self.branch("feature/new", "2026-11-20"), self.branch("feature/edge", "2026-11-05"),
|
||||
]
|
||||
self.assertEqual(self.names(branches), ["feature/old", "fix/old"])
|
||||
|
||||
def test_never_removes_the_long_lived_branches(self):
|
||||
old = "2025-01-01"
|
||||
branches = [self.branch(n, old) for n in ("production", "develop", "release/v0.1.0", "renovate/x", "other")]
|
||||
self.assertEqual(self.names(branches), [])
|
||||
|
||||
def test_keeps_a_branch_with_an_open_pull_request(self):
|
||||
self.assertEqual(self.names([self.branch("feature/old", "2026-01-01")], open_heads=["feature/old"]), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -116,12 +116,14 @@ jobs:
|
||||
trivy fs --no-progress --scanners vuln,secret,misconfig --severity HIGH,CRITICAL --exit-code 1 --skip-dirs vendor .
|
||||
|
||||
# Pull requests to a release branch merge by themselves when the check below is green.
|
||||
# Every job that checks out runs in an image with git: without git the checkout is the archive of the
|
||||
# repository, which leaves out what .gitattributes export-ignores (.gitea/ with these scripts).
|
||||
release-automerge:
|
||||
runs-on: docker
|
||||
needs: pr-ci
|
||||
if: startsWith(github.base_ref, 'release/') && needs.pr-ci.result == 'success'
|
||||
container:
|
||||
image: python:3.12-alpine
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
name: Prune branches
|
||||
|
||||
# Every night: remove feature/* and fix/* branches that nobody touched for 30 days and that have no
|
||||
# open pull request. production, develop and the release branches are never removed.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '15 4 * * *'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dry_run:
|
||||
description: 'Only say what would be removed (1) or remove it (0)'
|
||||
default: '1'
|
||||
|
||||
jobs:
|
||||
prune:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: remove quiet branches
|
||||
run: python3 .gitea/scripts/prune_branches.py
|
||||
env:
|
||||
GT_URL: https://git.iriks.casa
|
||||
GT_OWNER: iriks-it
|
||||
GT_REPO: laravel-manager
|
||||
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
|
||||
DRY_RUN: ${{ inputs.dry_run }}
|
||||
@@ -56,7 +56,7 @@ jobs:
|
||||
runs-on: docker
|
||||
needs: tag
|
||||
container:
|
||||
image: python:3.12-alpine
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
start:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: python:3.12-alpine
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
Reference in new issue
Block a user