Fix checkout in jobs without git (export-ignore); prune quiet feature branches after 30 days
PR CI / pr-ci (pull_request) Skipped
PR CI / pr-ci (pull_request) Skipped
This commit is contained in:
1 parent
86ecde31ea
commit
eb93e890d6
9 files changed
+159
-3
No files matched your search
@@ -3,6 +3,8 @@
|
|||||||
|
|
||||||
# What stays in the repository but is not part of the package that Composer installs (Packagist builds
|
# What stays in the repository but is not part of the package that Composer installs (Packagist builds
|
||||||
# the dist archive from `git archive`, which leaves these out).
|
# the dist archive from `git archive`, which leaves these out).
|
||||||
|
# Because of that, every CI job that checks out must run in an image with git (webdevops/php has it):
|
||||||
|
# without git, actions/checkout downloads that same archive and the .gitea/ scripts are missing.
|
||||||
/.gitattributes export-ignore
|
/.gitattributes export-ignore
|
||||||
/.gitea export-ignore
|
/.gitea export-ignore
|
||||||
/.gitignore export-ignore
|
/.gitignore export-ignore
|
||||||
|
|||||||
@@ -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 os
|
||||||
import sys
|
import sys
|
||||||
import unittest
|
import unittest
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
import check_flow # noqa: E402
|
import check_flow # noqa: E402
|
||||||
|
import prune_branches # noqa: E402
|
||||||
import semver # noqa: E402
|
import semver # noqa: E402
|
||||||
|
|
||||||
TAGS = ["v0.1.0", "v0.2.0", "v0.10.0", "not-a-version"]
|
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"), [])
|
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__":
|
if __name__ == "__main__":
|
||||||
unittest.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 .
|
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.
|
# 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:
|
release-automerge:
|
||||||
runs-on: docker
|
runs-on: docker
|
||||||
needs: pr-ci
|
needs: pr-ci
|
||||||
if: startsWith(github.base_ref, 'release/') && needs.pr-ci.result == 'success'
|
if: startsWith(github.base_ref, 'release/') && needs.pr-ci.result == 'success'
|
||||||
container:
|
container:
|
||||||
image: python:3.12-alpine
|
image: webdevops/php:8.4
|
||||||
steps:
|
steps:
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v4
|
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
|
runs-on: docker
|
||||||
needs: tag
|
needs: tag
|
||||||
container:
|
container:
|
||||||
image: python:3.12-alpine
|
image: webdevops/php:8.4
|
||||||
steps:
|
steps:
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ jobs:
|
|||||||
start:
|
start:
|
||||||
runs-on: docker
|
runs-on: docker
|
||||||
container:
|
container:
|
||||||
image: python:3.12-alpine
|
image: webdevops/php:8.4
|
||||||
steps:
|
steps:
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|||||||
@@ -114,6 +114,7 @@ Nobody opens a pull request to `develop`, and `production` and the release branc
|
|||||||
| Pull request to a release branch or to production | *flow* (right branches, version above the latest tag, changelog section, tests of these scripts), *ledger* (`TOKENS.md`), *test* (Pint, Pest with the newest and the oldest dependencies, `composer validate`), *security* (`composer audit`, Trivy on the dependencies, secrets and settings). The check `PR CI / pr-ci` is green when all are. |
|
| Pull request to a release branch or to production | *flow* (right branches, version above the latest tag, changelog section, tests of these scripts), *ledger* (`TOKENS.md`), *test* (Pint, Pest with the newest and the oldest dependencies, `composer validate`), *security* (`composer audit`, Trivy on the dependencies, secrets and settings). The check `PR CI / pr-ci` is green when all are. |
|
||||||
| Push to production | verify (Pest, audit), tag and release, Packagist, sync develop |
|
| Push to production | verify (Pest, audit), tag and release, Packagist, sync develop |
|
||||||
| Every Monday | `composer audit` and Trivy on production |
|
| Every Monday | `composer audit` and Trivy on production |
|
||||||
|
| Every night | *Prune branches*: removes `feature/*` and `fix/*` branches whose last commit is over 30 days old and that have no open pull request (a branch of a pull request can be restored from it in Gitea) |
|
||||||
|
|
||||||
Secrets of the repository for this: `DEPLOY_TOKEN` (the organisation has it), and `PACKAGIST_USERNAME` and
|
Secrets of the repository for this: `DEPLOY_TOKEN` (the organisation has it), and `PACKAGIST_USERNAME` and
|
||||||
`PACKAGIST_TOKEN` once the package is submitted on packagist.org (until then that step only says so).
|
`PACKAGIST_TOKEN` once the package is submitted on packagist.org (until then that step only says so).
|
||||||
|
|||||||
@@ -8,3 +8,4 @@ Per stuk werk een rij; zie `dev/token-usage.py`.
|
|||||||
| 2026-12-04 | Posts overgezet: berichten met concepten, inplannen, categorieën en tags | - | claude-sonnet-5-5 | 9 | 19.897 | 20 | 35.420 | 1.584.858 | 0,03 |
|
| 2026-12-04 | Posts overgezet: berichten met concepten, inplannen, categorieën en tags | - | claude-sonnet-5-5 | 9 | 19.897 | 20 | 35.420 | 1.584.858 | 0,03 |
|
||||||
| 2026-12-04 | Token-script telt de tokens van helper-agents mee in de rij, per model | - | claude-sonnet-5-5 | 16 | 27.013 | 36 | 45.155 | 2.982.056 | 0,06 |
|
| 2026-12-04 | Token-script telt de tokens van helper-agents mee in de rij, per model | - | claude-sonnet-5-5 | 16 | 27.013 | 36 | 45.155 | 2.982.056 | 0,06 |
|
||||||
| 2026-12-04 | CI en releaseproces opgezet: releasebranch, tag, Packagist, sync naar develop, tests, audit en Trivy | - | claude-sonnet-5-5 | 14 | 31.242 | 30 | 48.735 | 3.520.606 | 0,09 |
|
| 2026-12-04 | CI en releaseproces opgezet: releasebranch, tag, Packagist, sync naar develop, tests, audit en Trivy | - | claude-sonnet-5-5 | 14 | 31.242 | 30 | 48.735 | 3.520.606 | 0,09 |
|
||||||
|
| 2026-12-04 | Opstart van de release gerepareerd en oude featurebranches na 30 dagen automatisch opruimen | - | claude-sonnet-5-5 | 14 | 14.499 | 32 | 14.175 | 4.138.947 | 0,08 |
|
||||||
Reference in new issue
Block a user