From 4bec9dfb752b9a5fb3c87381e421e89aa9920803 Mon Sep 17 00:00:00 2001 From: Matthijs Iriks Date: Fri, 4 Dec 2026 02:59:20 +0100 Subject: [PATCH] Weekly workflow that widens dependency constraints --- .gitea/scripts/test_scripts.py | 32 +++++ .gitea/scripts/update_dependencies.py | 187 ++++++++++++++++++++++++++ .gitea/workflows/dependencies.yml | 36 +++++ CHANGELOG.md | 1 + README.md | 1 + TOKENS.md | 1 + 6 files changed, 258 insertions(+) create mode 100755 .gitea/scripts/update_dependencies.py create mode 100644 .gitea/workflows/dependencies.yml diff --git a/.gitea/scripts/test_scripts.py b/.gitea/scripts/test_scripts.py index fd00a1c..0d14c0d 100644 --- a/.gitea/scripts/test_scripts.py +++ b/.gitea/scripts/test_scripts.py @@ -10,6 +10,7 @@ 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 update_dependencies # noqa: E402 import semver # noqa: E402 TAGS = ["v0.1.0", "v0.2.0", "v0.10.0", "not-a-version"] @@ -134,5 +135,36 @@ class HermesTokens(unittest.TestCase): self.assertTrue(self.hermes.lines(per_model, "Work", "2026-12-04", "", None)[0].endswith("| 4.000 | |")) +class DependencyUpdates(unittest.TestCase): + def test_only_a_release_above_the_latest_tag_is_open(self): + branches = ["develop", "production", "release/v0.1.0", "release/v0.2.0", "release/v0.3.0", "feature/x"] + self.assertEqual(update_dependencies.open_release(branches, ["v0.1.0", "v0.2.0"]), "release/v0.3.0") + self.assertIsNone(update_dependencies.open_release(branches, ["v0.3.0"])) + self.assertEqual(update_dependencies.open_release(["release/v0.1.0"], []), "release/v0.1.0") + + def test_widening_adds_the_new_major_once(self): + self.assertEqual(update_dependencies.widen("^13.0", "14.2.1"), "^13.0||^14.0") + self.assertEqual(update_dependencies.widen("^12.0 || ^13.0", "14.0.0"), "^12.0 || ^13.0||^14.0") + self.assertIsNone(update_dependencies.widen("^13.0||^14.0", "14.2.1")) + self.assertEqual(update_dependencies.widen("^0.5", "0.6.3"), "^0.5||^0.6") + + def test_odd_constraints_are_left_to_a_person(self): + for odd in (">=1.0", "dev-main", "*", "1.2.*"): + self.assertIsNone(update_dependencies.widen(odd, "9.0.0")) + + def test_only_what_is_outside_the_constraint_changes(self): + composer = {"require": {"a/a": "^1.0", "b/b": "^2.0"}, "require-dev": {"c/c": "^3.0"}} + outdated = [ + {"name": "a/a", "latest": "2.0.0", "latest-status": "update-possible"}, + {"name": "b/b", "latest": "2.4.0", "latest-status": "semver-safe-update"}, + {"name": "c/c", "latest": "4.1.0", "latest-status": "update-possible"}, + ] + changes = update_dependencies.widened(composer, outdated) + self.assertEqual(sorted(changes), ["a/a", "c/c"]) + self.assertEqual(composer["require"]["a/a"], "^1.0||^2.0") + self.assertEqual(composer["require"]["b/b"], "^2.0") + self.assertEqual(composer["require-dev"]["c/c"], "^3.0||^4.0") + + if __name__ == "__main__": unittest.main() diff --git a/.gitea/scripts/update_dependencies.py b/.gitea/scripts/update_dependencies.py new file mode 100755 index 0000000..9d93eed --- /dev/null +++ b/.gitea/scripts/update_dependencies.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +"""Weekly dependency update for a library: widens the version constraints of composer.json. + +A package has no composer.lock, so there is nothing to bump: what can go stale is the range of +versions it accepts. When a direct dependency has a release outside its constraint (a new major, +say Laravel 14), the constraint is widened to accept it as well (`^13.0||^14.0`) and a pull request +is opened to the open release branch (`release/vX.Y.Z` above the latest tag). PR CI then tests the +new version; the pull request merges by itself when everything is green, and stays open when +it is not, so a red pull request is the signal that the package does not work with it yet. + +Nothing happens when no release is open (start one first), when a pull request of this script is +still open, or when nothing is outside its constraint. + +Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (the deploy bot: pushes a branch, opens a pull +request). Needs git and composer. Standard library only. +""" + +import datetime +import json +import os +import re +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import semver # noqa: E402 + +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", "") +USER = "deploy-bot" +BRANCH_PREFIX = "renovate/deps-" +SECTIONS = ("require", "require-dev") + + +def api(method, path, body=None): + request = urllib.request.Request( + f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}", + data=json.dumps(body).encode() if body is not None else None, + method=method, + headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"}, + ) + 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 open_release(branches, tags): + """The release branch that is not released yet (its version is above the latest tag); the highest one.""" + newest = semver.latest(tags) + open_ones = [(semver.release_version(name), name) for name in branches] + open_ones = [(version, name) for version, name in open_ones if version and (newest is None or version > newest)] + return max(open_ones)[1] if open_ones else None + + +def caret(version): + """`^14.0` for 14.2.1; `^0.6` for 0.6.3 (a caret on a 0.x version only allows the minor).""" + parts = version.lstrip("v").split(".") + return f"^{parts[0]}.{parts[1] if parts[0] == '0' else '0'}" + + +def widen(constraint, latest): + """The constraint with the version of `latest` added, or None when it is (already) accepted or not a plain range.""" + # Only the plain forms: a caret, a tilde or a list of those. Anything else is left to a person. + if not re.fullmatch(r"[\^~][\w.\-]+(\s*\|\|?\s*[\^~][\w.\-]+)*", constraint.strip()): + return None + + added = caret(latest) + + if added in constraint.replace(" ", "").split("||"): + return None + + return f"{constraint.strip()}||{added}" + + +def widened(composer, outdated): + """Applies the packages that `composer outdated` says have a release outside their constraint; returns what changed.""" + changes = {} + + for package in outdated: + name, latest = package.get("name"), package.get("latest") + + if package.get("latest-status") != "update-possible" or not latest: + continue + + for section in SECTIONS: + current = composer.get(section, {}).get(name) + new = widen(current, latest) if current else None + + if new: + composer[section][name] = new + changes[name] = (current, new) + + return changes + + +def run(command, cwd, retries=1): + for attempt in range(1, retries + 1): + result = subprocess.run(command, cwd=cwd, capture_output=True, text=True) + + if result.returncode == 0 or attempt == retries: + return result + + time.sleep(attempt * 10) + + +def body(changes, release): + lines = "\n".join(f"- `{name}`: `{old}` → `{new}`" for name, (old, new) in sorted(changes.items())) + return f"""Automatic update of the version constraints, by the weekly workflow `Dependency updates`. + +{lines} + +PR CI tests the package with the newer versions. It merges into `{release}` by itself when everything is green; when it is red, the package does not work with them yet.""" + + +def main(): + if not (URL and OWNER and REPO and TOKEN): + sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.") + + branches = [item["name"] for item in api("GET", "branches?limit=50") or []] + tags = [item["name"] for item in api("GET", "tags?limit=50") or []] + release = open_release(branches, tags) + + if release is None: + print("No release is open: nothing to update. Start a release first.") + return + + for pull in api("GET", "pulls?state=open&limit=50") or []: + if pull["head"]["ref"].startswith(BRANCH_PREFIX): + print(f"Pull request #{pull['number']} of this workflow is still open: not making another.") + return + + remote = f"https://{USER}:{TOKEN}@{URL.split('://', 1)[1]}/{OWNER}/{REPO}.git" + work = os.path.join(tempfile.mkdtemp(), "repo") + clone = subprocess.run(["git", "clone", "--quiet", "--branch", release, remote, work], capture_output=True, text=True) + + if clone.returncode != 0: + sys.exit("git clone failed.") + + update = run(["composer", "update", "--prefer-stable", "--prefer-dist", "--no-scripts", "--no-interaction"], work, retries=3) + + if update.returncode != 0: + sys.exit(f"composer update failed:\n{update.stderr[-2000:]}") + + listed = run(["composer", "outdated", "--direct", "--format=json", "--no-interaction"], work) + outdated = json.loads(listed.stdout or "{}").get("installed", []) + + path = os.path.join(work, "composer.json") + composer = json.load(open(path)) + changes = widened(composer, outdated) + + if not changes: + print("Every direct dependency is inside its constraint: nothing to do.") + return + + with open(path, "w") as file: + json.dump(composer, file, indent=4, ensure_ascii=False) + file.write("\n") + + branch = BRANCH_PREFIX + datetime.date.today().strftime("%Y%m%d") + + for command in ( + ["git", "config", "user.name", USER], + ["git", "config", "user.email", f"{USER}@iriks-it.nl"], + ["git", "checkout", "-b", branch], + ["git", "commit", "-am", "Widen dependency constraints: " + ", ".join(sorted(changes))], + ["git", "push", "--quiet", "origin", branch], + ): + result = subprocess.run(command, cwd=work, capture_output=True, text=True) + + if result.returncode != 0: + sys.exit(f"{' '.join(command[:2])} failed: {result.stderr.strip()}") + + pull = api("POST", "pulls", {"title": "Dependency updates: " + ", ".join(sorted(changes)), "head": branch, "base": release, "body": body(changes, release)}) + print(f"Pull request #{pull['number']} to {release}: {', '.join(sorted(changes))}.") + + +if __name__ == "__main__": + main() diff --git a/.gitea/workflows/dependencies.yml b/.gitea/workflows/dependencies.yml new file mode 100644 index 0000000..3cba984 --- /dev/null +++ b/.gitea/workflows/dependencies.yml @@ -0,0 +1,36 @@ +name: Dependency updates + +# A package has no composer.lock, so what goes stale is the range of versions it accepts. Every +# Monday this looks for a direct dependency with a release outside its constraint (a new major) and +# opens a pull request to the open release branch that accepts it as well; PR CI then tests it and the +# pull request merges by itself when it is green. Nothing happens while no release is open. +on: + schedule: + - cron: '0 5 * * 1' + workflow_dispatch: + +jobs: + update: + runs-on: docker + container: + image: webdevops/php:8.4 + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: cache composer downloads + uses: actions/cache@v4 + with: + path: ~/.composer/cache + key: composer-dependencies-${{ hashFiles('composer.json') }} + restore-keys: | + composer-dependencies- + + - name: widen the constraints + run: python3 .gitea/scripts/update_dependencies.py + env: + COMPOSER_MAX_PARALLEL_HTTP: '4' + GT_URL: https://git.iriks.casa + GT_OWNER: iriks-it + GT_REPO: laravel-manager + GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 518f972..efbecb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ the section is the text of the release in Gitea. devices, programs, comparisons and CSV export. Which pages count is up to the site. - Breaking for a module that implements `Contract\Module` without extending `BaseModule`: the contract gained `actions()`, `views()` and `middleware()`. +- Weekly workflow *Dependency updates*: widens the version constraints in `composer.json` for a new release of a dependency, as a pull request to the open release branch. - `dev/token-usage-hermes.py`: the same rows per model for work done by a Hermes agent; the token script also counts the advisor. - `CLAUDE.md` and the rules shared with the other IriksIT repos in `AGENTS.md`. diff --git a/README.md b/README.md index 4f228d4..cb19428 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,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. | | Push to production | verify (Pest, audit), tag and release, Packagist, sync develop | | Every Monday | `composer audit` and Trivy on production | +| Every Monday | *Dependency updates*: a direct dependency with a release outside its constraint (a new major) gets its constraint widened in a pull request `renovate/deps-DATE` to the open release branch; PR CI tests it and it merges when green. Nothing happens while no release is open. A package has no `composer.lock`, so the central Renovate and Trivy of the homelab have nothing to resolve here. | | 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 diff --git a/TOKENS.md b/TOKENS.md index 4755670..d638e2a 100644 --- a/TOKENS.md +++ b/TOKENS.md @@ -19,3 +19,4 @@ Per stuk werk een rij; zie `dev/token-usage.py`. | 2026-12-01 | Adviseur-aanroep bij het eerdere werk (CI, release en eerste modules), die in de rijen erboven nog niet meetelde | - | claude-fable-5-2 | 1 | 10.012 | 115.261 | 0 | 0 | 0,00 | | 2026-12-04 | Adviseur-aanroepen bij de auditmodule en het banbeheer, die in de rij erboven nog niet meetelden | - | claude-fable-5-2 | 2 | 25.967 | 246.202 | 0 | 0 | 0,00 | | 2026-12-04 | Het Hermes-tokenscript uit bouwbedrijf overgenomen, met dezelfde rijen per model als het hoofdscript | - | claude-sonnet-5-5 | 9 | 7.044 | 20 | 15.263 | 2.258.010 | 0,01 | +| 2026-12-04 | Wekelijkse update van de versiebereiken van afhankelijkheden, als pull request naar de open release | - | claude-sonnet-5-5 | 6 | 7.611 | 12 | 10.963 | 1.632.350 | 0,01 | -- 2.47.3