#!/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. The screens have their own dependencies (`ui/package.json`, with a lock file). `update_dependencies.py ui` moves every npm package that has a newer release (a new major too) to it, but only to a release that has been public for 48 hours (a supply-chain guard: a hijacked release is usually pulled within days), rebuilds `resources/dist`, and opens a pull request the same way. PR CI type-checks and builds it, so a red pull request is the signal. Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (the deploy bot: pushes a branch, opens a pull request). Needs git and composer (npm and node for `ui`). 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-" UI_BRANCH_PREFIX = "renovate/ui-deps-" MIN_AGE = datetime.timedelta(hours=48) 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 npm_targets(outdated, published, now): """What each outdated npm package moves to: its newest release (or the newest inside its range) that is old enough. `outdated` is `npm outdated --json` (name -> current, wanted, latest); `published(name, version)` is the time that release came out (a datetime, or None when unknown, which counts as too new). """ targets = {} for name, info in sorted(outdated.items()): if not isinstance(info, dict) or not info.get("current"): continue for candidate in (info.get("latest"), info.get("wanted")): if not candidate or candidate == info["current"] or "-" in candidate: continue when = published(name, candidate) if when is not None and now - when >= MIN_AGE: targets[name] = (info["current"], candidate) break return targets def main_ui(): """The same cycle for ui/: bump what is outdated and old enough, rebuild the bundle, open a pull request.""" work, release, remote = prepare(UI_BRANCH_PREFIX) ui = os.path.join(work, "ui") install = run(["npm", "ci", "--no-audit", "--no-fund", "--ignore-scripts"], ui, retries=3) if install.returncode != 0: sys.exit(f"npm ci failed:\n{install.stderr[-2000:]}") listed = run(["npm", "outdated", "--json"], ui) # exit code 1 means "something is outdated" outdated = json.loads(listed.stdout or "{}") times = {} def published(name, version): if name not in times: view = run(["npm", "view", name, "time", "--json"], ui, retries=2) try: times[name] = json.loads(view.stdout or "{}") except ValueError: times[name] = {} stamp = times[name].get(version) if isinstance(times[name], dict) else None try: return datetime.datetime.fromisoformat(stamp.replace("Z", "+00:00")) if stamp else None except ValueError: return None targets = npm_targets(outdated, published, datetime.datetime.now(datetime.timezone.utc)) if not targets: print("Every npm package is up to date, or too new to adopt yet: nothing to do.") return applied = {} for name, (old, new) in targets.items(): result = run(["npm", "install", f"{name}@{new}", "--save-prefix=^", "--no-audit", "--no-fund", "--ignore-scripts"], ui) if result.returncode == 0: applied[name] = (old, new) else: run(["git", "checkout", "--", "ui/package.json", "ui/package-lock.json"], work) print(f"{name} {new} does not install: left as it was.") if not applied: print("Nothing could be installed.") return # A new bundle with the new dependencies; when it does not build the pull request still opens, red, with the old bundle. if run(["npm", "run", "build"], ui).returncode != 0: print("The build failed with the new packages: the pull request will be red.") publish(work, release, remote, UI_BRANCH_PREFIX, applied, "Update the dependencies of the screens", ["ui/package.json", "ui/package-lock.json", "resources/dist"]) def prepare(prefix): """Finds the open release, makes sure no pull request of this kind is open, and clones the release branch.""" 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.") sys.exit(0) for pull in api("GET", "pulls?state=open&limit=50") or []: if pull["head"]["ref"].startswith(prefix): print(f"Pull request #{pull['number']} of this workflow is still open: not making another.") sys.exit(0) 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.") return work, release, remote def publish(work, release, remote, prefix, changes, title, paths): """Commits `paths`, pushes a branch and opens the pull request to the release.""" 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", "add", "--", *paths], ["git", "commit", "-m", f"{title}: " + ", ".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": f"{title}: " + ", ".join(sorted(changes)), "head": branch, "base": release, "body": body(changes, release)}) print(f"Pull request #{pull['number']} to {release}: {', '.join(sorted(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 dependencies, by the weekly workflow `Dependency updates`. {lines} PR CI tests the package with the newer versions (and rebuilds the screens when it is about npm). It merges into `{release}` by itself when everything is green; when it is red, the package does not work with them yet.""" def main(): work, release, remote = prepare(BRANCH_PREFIX) 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") publish(work, release, remote, BRANCH_PREFIX, changes, "Dependency updates", ["composer.json"]) if __name__ == "__main__": main_ui() if sys.argv[1:] == ["ui"] else main()