diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8f23ffd..5d0c868 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,6 +5,7 @@ on: push: branches: - main + workflow_dispatch: permissions: contents: read diff --git a/.github/workflows/update_pyrefly_releases.py b/.github/workflows/update_pyrefly_releases.py new file mode 100644 index 0000000..4022786 --- /dev/null +++ b/.github/workflows/update_pyrefly_releases.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Add stable Pyrefly releases newer than the newest checked-in version. + +Reads the asset digests from the GitHub releases API, writes +pyrefly/private/versions.bzl and CHANGELOG.md, and prints the added versions. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import re +import subprocess +import sys +from typing import Any, Iterable + + +ROOT = Path(__file__).resolve().parents[2] +VERSIONS = ROOT / "pyrefly" / "private" / "versions.bzl" +TOOLCHAIN_REPO = ROOT / "pyrefly" / "private" / "toolchain_repo.bzl" +CHANGELOG = ROOT / "CHANGELOG.md" +PYREFLY_REPOSITORY = "pyrefly-org/pyrefly" + +STABLE_VERSION = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+$") +VERSION_KEY = re.compile(r'^ "(?P[0-9]+\.[0-9]+\.[0-9]+)": \{$', re.M) +ASSET_ENTRY = re.compile(r'^\s*"(?P[^"]+)": "(?P[0-9a-f]{64})",$', re.M) +ASSET_NAME = re.compile(r'^\s*asset = "(?P[^"]+)",$', re.M) +RELEASES_START = "PYREFLY_RELEASES = {" + + +def version_tuple(version: str) -> tuple[int, ...]: + return tuple(int(part) for part in version.split(".")) + + +def supported_assets(toolchain_repo: str) -> list[str]: + assets = sorted(match.group("asset") for match in ASSET_NAME.finditer(toolchain_repo)) + if not assets: + raise ValueError("Could not find any asset names in toolchain_repo.bzl") + return assets + + +def parse_releases(source: str) -> dict[str, dict[str, str]]: + releases: dict[str, dict[str, str]] = {} + matches = list(VERSION_KEY.finditer(source)) + for index, match in enumerate(matches): + end = matches[index + 1].start() if index + 1 < len(matches) else len(source) + body = source[match.end() : end] + releases[match.group("version")] = { + entry.group("asset"): entry.group("sha256") + for entry in ASSET_ENTRY.finditer(body) + } + if not releases: + raise ValueError("Could not find any releases in versions.bzl") + return releases + + +def render_releases(source: str, releases: dict[str, dict[str, str]]) -> str: + header = source[: source.index(RELEASES_START)] + lines = [RELEASES_START] + for version in sorted(releases, key=version_tuple): + lines.append(f' "{version}": {{') + lines.append(' "assets": {') + for asset in sorted(releases[version]): + lines.append(f' "{asset}": "{releases[version][asset]}",') + lines.append(" },") + lines.append(" },") + lines.append("}") + return header + "\n".join(lines) + "\n" + + +def new_releases( + github_releases: Iterable[dict[str, Any]], + known_versions: Iterable[str], + assets: list[str], +) -> dict[str, dict[str, str]]: + newest = max(version_tuple(version) for version in known_versions) + result: dict[str, dict[str, str]] = {} + for release in github_releases: + version = release["tag_name"] + if release["draft"] or release["prerelease"]: + continue + if not STABLE_VERSION.fullmatch(version) or version_tuple(version) <= newest: + continue + digests = {asset["name"]: asset.get("digest") or "" for asset in release["assets"]} + missing = [asset for asset in assets if not digests.get(asset, "").startswith("sha256:")] + if missing: + raise ValueError( + f"Pyrefly release {version} has no SHA-256 digest for {missing}. " + "The release binaries may still be uploading." + ) + result[version] = { + asset: digests[asset].removeprefix("sha256:") for asset in assets + } + return result + + +def add_changelog_entries(source: str, versions: list[str]) -> str: + entries = "".join( + f"- Checked-in release metadata for Pyrefly {version}.\n" for version in versions + ) + unreleased = "## [Unreleased]\n" + start = source.index(unreleased) + len(unreleased) + next_release = source.find("\n## [", start) + section_end = next_release + 1 if next_release != -1 else len(source) + added = source.find("### Added\n", start, section_end) + if added == -1: + return source[:start] + "\n### Added\n\n" + entries + source[start:] + insert = added + len("### Added\n\n") + return source[:insert] + entries + source[insert:] + + +def fetch_github_releases() -> list[dict[str, Any]]: + output = subprocess.run( + [ + "gh", + "api", + "--paginate", + f"repos/{PYREFLY_REPOSITORY}/releases", + "--jq", + ".[]", + ], + check=True, + encoding="utf-8", + stdout=subprocess.PIPE, + ).stdout + return [json.loads(line) for line in output.splitlines() if line] + + +def main() -> None: + versions_source = VERSIONS.read_text(encoding="utf-8") + releases = parse_releases(versions_source) + added = new_releases( + fetch_github_releases(), + releases, + supported_assets(TOOLCHAIN_REPO.read_text(encoding="utf-8")), + ) + added_versions = sorted(added, key=version_tuple) + if added_versions: + releases.update(added) + VERSIONS.write_text(render_releases(versions_source, releases), encoding="utf-8") + CHANGELOG.write_text( + add_changelog_entries(CHANGELOG.read_text(encoding="utf-8"), added_versions), + encoding="utf-8", + ) + + joined = ", ".join(added_versions) + print(f"Added Pyrefly releases: {joined}" if joined else "No new Pyrefly releases") + github_output = os.environ.get("GITHUB_OUTPUT") + if github_output: + with open(github_output, "a", encoding="utf-8") as output: + output.write(f"versions={joined}\n") + + +if __name__ == "__main__": + try: + main() + except (OSError, subprocess.CalledProcessError, ValueError) as error: + raise SystemExit(str(error)) from error diff --git a/.github/workflows/update_pyrefly_releases.yaml b/.github/workflows/update_pyrefly_releases.yaml new file mode 100644 index 0000000..3e255cc --- /dev/null +++ b/.github/workflows/update_pyrefly_releases.yaml @@ -0,0 +1,59 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: Update Pyrefly releases + +# Adds every stable Pyrefly release newer than the newest checked-in version +# and commits the change to main. A run with no new release changes nothing. + +on: + schedule: + - cron: "17 16 * * *" + workflow_dispatch: + +permissions: {} + +concurrency: + group: update-pyrefly-releases + cancel-in-progress: false + +jobs: + update: + runs-on: ubuntu-latest + permissions: + actions: write + contents: write + steps: + - uses: actions/checkout@v4 + - name: Add new Pyrefly releases + id: update + env: + GH_TOKEN: ${{ github.token }} + run: python3 .github/workflows/update_pyrefly_releases.py + - name: Commit to main + if: steps.update.outputs.versions != '' + env: + VERSIONS: ${{ steps.update.outputs.versions }} + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git commit -am "Add Pyrefly $VERSIONS" + git push origin HEAD:main + # A push made with GITHUB_TOKEN does not start CI, but a + # workflow_dispatch event sent with it does. + - name: Run CI on main + if: steps.update.outputs.versions != '' + env: + GH_TOKEN: ${{ github.token }} + run: gh workflow run ci.yml --repo "$GITHUB_REPOSITORY" --ref main diff --git a/tests/test_update_pyrefly_releases.py b/tests/test_update_pyrefly_releases.py new file mode 100644 index 0000000..ca30c64 --- /dev/null +++ b/tests/test_update_pyrefly_releases.py @@ -0,0 +1,106 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import importlib.util +from pathlib import Path +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / ".github" / "workflows" / "update_pyrefly_releases.py" +SPEC = importlib.util.spec_from_file_location("update_pyrefly_releases", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +update = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(update) + +ASSETS = ["pyrefly-a.tar.gz", "pyrefly-b.zip"] + + +def release(version: str, prerelease: bool = False, digests: bool = True) -> dict: + return { + "tag_name": version, + "draft": False, + "prerelease": prerelease, + "assets": [ + { + "name": asset, + "digest": f"sha256:{index:064x}" if digests else None, + } + for index, asset in enumerate(ASSETS + ["pyrefly-wasm.tar.gz"]) + ], + } + + +class UpdatePyreflyReleasesTest(unittest.TestCase): + def test_checked_in_versions_round_trip(self) -> None: + source = update.VERSIONS.read_text(encoding="utf-8") + self.assertEqual( + update.render_releases(source, update.parse_releases(source)), source + ) + + def test_reads_supported_assets_from_toolchain_repo(self) -> None: + assets = update.supported_assets( + update.TOOLCHAIN_REPO.read_text(encoding="utf-8") + ) + self.assertIn("pyrefly-macos-arm64.tar.gz", assets) + self.assertIn("pyrefly-windows-x86_64.zip", assets) + + def test_adds_only_newer_stable_releases(self) -> None: + added = update.new_releases( + [ + release("1.6.0"), + release("1.6.0-dev.1", prerelease=True), + release("1.5.10"), + release("1.5.1"), + release("1.4.0"), + ], + ["1.4.0", "1.5.1"], + ASSETS, + ) + self.assertEqual(sorted(added), ["1.5.10", "1.6.0"]) + self.assertEqual( + added["1.6.0"], + {"pyrefly-a.tar.gz": f"{0:064x}", "pyrefly-b.zip": f"{1:064x}"}, + ) + + def test_fails_when_digests_are_missing(self) -> None: + with self.assertRaisesRegex(ValueError, "no SHA-256 digest"): + update.new_releases([release("2.0.0", digests=False)], ["1.0.0"], ASSETS) + + def test_adds_changelog_entries_under_unreleased(self) -> None: + source = ( + "# Changelog\n\n## [Unreleased]\n\n### Added\n\n- Existing.\n\n" + "## [0.1.0] - 2026-08-01\n\n### Added\n\n- Old.\n" + ) + self.assertEqual( + update.add_changelog_entries(source, ["1.5.2"]), + "# Changelog\n\n## [Unreleased]\n\n### Added\n\n" + "- Checked-in release metadata for Pyrefly 1.5.2.\n- Existing.\n\n" + "## [0.1.0] - 2026-08-01\n\n### Added\n\n- Old.\n", + ) + + def test_creates_added_section_when_unreleased_has_none(self) -> None: + source = "## [Unreleased]\n\n## [0.1.0] - 2026-08-01\n\n### Added\n\n- Old.\n" + self.assertEqual( + update.add_changelog_entries(source, ["1.5.2"]), + "## [Unreleased]\n\n### Added\n\n" + "- Checked-in release metadata for Pyrefly 1.5.2.\n\n" + "## [0.1.0] - 2026-08-01\n\n### Added\n\n- Old.\n", + ) + + +if __name__ == "__main__": + unittest.main()