| #!/usr/bin/env python3 | |
| """ | |
| Update the pins of bundled external tools to their latest upstream versions. | |
| Each updated tool is committed separately, so the pins can be reviewed and reverted one by one. | |
| Run from anywhere inside the repository: | |
| script/update-tools.py lean4lean nanoda | |
| script/update-tools.py -a | |
| Release lookups use `GITHUB_TOKEN`, else `GH_TOKEN`, else `gh auth token`, else no authentication. | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| import subprocess | |
| import sys | |
| import urllib.request | |
| from collections.abc import Callable | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parent.parent | |
| @dataclass | |
| class Pin: | |
| file: str | |
| pattern: str | |
| """Regex with exactly one group that captures the pinned version.""" | |
| def locate(self) -> tuple[str, re.Match]: | |
| text = (ROOT / self.file).read_text() | |
| matches = list(re.finditer(self.pattern, text, re.MULTILINE)) | |
| if len(matches) != 1: | |
| sys.exit( | |
| f"error: expected one match of {self.pattern!r} in {self.file}, found {len(matches)}" | |
| ) | |
| return text, matches[0] | |
| def read(self) -> str: | |
| return self.locate()[1].group(1) | |
| def write(self, version: str) -> None: | |
| text, m = self.locate() | |
| (ROOT / self.file).write_text(text[: m.start(1)] + version + text[m.end(1) :]) | |
| def git_tag_pin(project: str) -> Pin: | |
| """The `GIT_TAG` of the `ExternalProject_Add(<project> ...)` call in `src/CMakeLists.txt`.""" | |
| return Pin( | |
| "src/CMakeLists.txt", | |
| rf"^\s*ExternalProject_Add\(\s*{re.escape(project)}\s[^)]*?^\s*GIT_TAG\s+([0-9a-f]{{40}})\s*$", | |
| ) | |
| def latest_commit(repo: str, branch: str) -> str: | |
| out = subprocess.run( | |
| [ | |
| "git", | |
| "ls-remote", | |
| "--exit-code", | |
| f"https://github.com/{repo}", | |
| f"refs/heads/{branch}", | |
| ], | |
| check=True, | |
| capture_output=True, | |
| text=True, | |
| ).stdout | |
| return out.split()[0] | |
| def github_token() -> str | None: | |
| if token := os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN"): | |
| return token | |
| try: | |
| result = subprocess.run( | |
| ["gh", "auth", "token"], | |
| check=False, | |
| capture_output=True, | |
| text=True, | |
| ) | |
| except FileNotFoundError: | |
| return None | |
| if result.returncode != 0: | |
| return None | |
| return result.stdout.strip() or None | |
| def github_api(path: str): | |
| req = urllib.request.Request( | |
| f"https://api.github.com/{path}", | |
| headers={ | |
| "Accept": "application/vnd.github+json", | |
| "X-GitHub-Api-Version": "2022-11-28", | |
| }, | |
| ) | |
| if token := github_token(): | |
| req.add_header("Authorization", f"Bearer {token}") | |
| with urllib.request.urlopen(req) as resp: | |
| return json.load(resp) | |
| def latest_release(repo: str) -> str: | |
| """The release GitHub marks as "Latest" (never a draft or prerelease).""" | |
| return github_api(f"repos/{repo}/releases/latest")["tag_name"] | |
| @dataclass | |
| class Tool: | |
| repo: str | |
| pin: Pin | |
| latest: Callable[[], str] | |
| source: str | |
| """Where `latest` takes the version from, used as the commit message's target.""" | |
| def compare_url(self, old: str, new: str) -> str: | |
| return f"https://github.com/{self.repo}/compare/{old}...{new}" | |
| def branch_tool(project: str, repo: str, branch: str) -> Tool: | |
| return Tool( | |
| repo, | |
| git_tag_pin(project), | |
| lambda: latest_commit(repo, branch), | |
| f"`{repo}` branch `{branch}`", | |
| ) | |
| TOOLS: dict[str, Tool] = { | |
| "con-leche": branch_tool("con-leche", "leanprover/con-leche", "master"), | |
| "con-ron": branch_tool("con-ron", "leanprover/con-ron", "master"), | |
| # Forks tracking the kernel change from #13851 until upstream catches up (see #16671) | |
| "lean4lean": branch_tool("lean4lean", "nomeata/lean4lean", "no-large-elim"), | |
| "nanoda": branch_tool("nanoda", "nomeata/nanoda_lib", "no-large-elim"), | |
| "leantar": Tool( | |
| "nomeata/leangz", | |
| Pin("CMakeLists.txt", r"^\s*set\(LEANTAR_VERSION\s+(\S+)\)\s*$"), | |
| lambda: latest_release("nomeata/leangz"), | |
| "latest `nomeata/leangz` release", | |
| ), | |
| } | |
| def git(*args: str) -> str: | |
| return subprocess.run( | |
| ["git", "-C", str(ROOT), *args], check=True, capture_output=True, text=True | |
| ).stdout | |
| def short(version: str) -> str: | |
| return version[:12] if re.fullmatch(r"[0-9a-f]{40}", version) else version | |
| def update(name: str, commit: bool) -> bool: | |
| tool = TOOLS[name] | |
| old = tool.pin.read() | |
| new = tool.latest() | |
| if old == new: | |
| print(f"{name}: already at {short(old)}") | |
| return False | |
| print(f"{name}: {short(old)} -> {short(new)}") | |
| tool.pin.write(new) | |
| if commit: | |
| message = ( | |
| f"chore: update bundled {name} to {tool.source}\n\n" | |
| f"{tool.compare_url(old, new)}\n" | |
| ) | |
| git("commit", "--quiet", "--message", message, "--", tool.pin.file) | |
| return True | |
| def main() -> None: | |
| parser = argparse.ArgumentParser( | |
| description="Update bundled external tools to their latest upstream versions, one commit per tool.", | |
| epilog=f"known tools: {', '.join(TOOLS)}", | |
| ) | |
| parser.add_argument("tools", nargs="*", metavar="TOOL", help="tools to update") | |
| parser.add_argument( | |
| "-a", "--all", action="store_true", help="update all known tools" | |
| ) | |
| parser.add_argument( | |
| "--no-commit", action="store_true", help="only edit the pins, do not commit" | |
| ) | |
| args = parser.parse_args() | |
| if args.all and args.tools: | |
| parser.error("pass either -a or tool names, not both") | |
| if not args.all and not args.tools: | |
| parser.error("no tools given; pass tool names or -a") | |
| if unknown := [t for t in args.tools if t not in TOOLS]: | |
| parser.error( | |
| f"unknown tool(s): {', '.join(unknown)} (known: {', '.join(TOOLS)})" | |
| ) | |
| names = list(TOOLS) if args.all else list(dict.fromkeys(args.tools)) | |
| if not args.no_commit: | |
| files = sorted({TOOLS[n].pin.file for n in names}) | |
| if dirty := git("status", "--porcelain", "--", *files).strip(): | |
| sys.exit( | |
| f"error: uncommitted changes in files that would be committed:\n{dirty}" | |
| ) | |
| updated = [n for n in names if update(n, commit=not args.no_commit)] | |
| print(f"updated: {', '.join(updated)}" if updated else "all tools up to date") | |
| if __name__ == "__main__": | |
| main() |