188 lines
7.1 KiB
Python
Executable File
188 lines
7.1 KiB
Python
Executable File
#!/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()
|