diff --git a/.github/scripts/test_update_homebrew.py b/.github/scripts/test_update_homebrew.py new file mode 100644 index 0000000..3b0e298 --- /dev/null +++ b/.github/scripts/test_update_homebrew.py @@ -0,0 +1,42 @@ +import tempfile +import unittest +from pathlib import Path + +from update_homebrew import update_tap + + +class UpdateTapTest(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.tap = Path(directory.name) + self.formula = self.tap / "Formula/tsunagi.rb" + self.cask = self.tap / "Casks/tsunagi-gui.rb" + self.formula.parent.mkdir() + self.cask.parent.mkdir() + self.old_hash = "a" * 64 + self.new_hash = "b" * 64 + self.formula.write_text(f' VERSION = "1.9.0"\n SHA256 = "{self.old_hash}"\n') + self.cask.write_text(f' version "1.9.0"\n sha256 "{self.old_hash}"\n') + + def test_updates_both_packages_and_allows_retry(self): + for _ in range(2): + update_tap(self.tap, "v1.10.0", self.new_hash) + self.assertEqual(self.formula.read_text(), f' VERSION = "1.10.0"\n SHA256 = "{self.new_hash}"\n') + self.assertEqual(self.cask.read_text(), f' version "1.10.0"\n sha256 "{self.new_hash}"\n') + + def test_older_release_does_not_replace_either_package(self): + before = self.formula.read_bytes(), self.cask.read_bytes() + update_tap(self.tap, "v1.8.9", self.new_hash) + self.assertEqual((self.formula.read_bytes(), self.cask.read_bytes()), before) + + def test_invalid_release_or_cask_leaves_formula_untouched(self): + before = self.formula.read_bytes() + with self.assertRaises(ValueError): + update_tap(self.tap, "v1.10.0-rc.1", self.new_hash) + with self.assertRaises(ValueError): + update_tap(self.tap, "v1.10.0", "invalid") + self.cask.write_text(' version "1.9.0"\n') + with self.assertRaises(ValueError): + update_tap(self.tap, "v1.10.0", self.new_hash) + self.assertEqual(self.formula.read_bytes(), before) diff --git a/.github/scripts/update_homebrew.py b/.github/scripts/update_homebrew.py new file mode 100644 index 0000000..3228657 --- /dev/null +++ b/.github/scripts/update_homebrew.py @@ -0,0 +1,51 @@ +"""Update the tap's formula and cask for a verified macOS release archive.""" + +import argparse +import re +from pathlib import Path + +VERSION = r"(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*)){2}" +SHA256 = r"[0-9a-f]{64}" + + +def update_tap(tap: Path, tag: str, checksum: str) -> None: + if not re.fullmatch(f"v{VERSION}", tag): + raise ValueError("expected a stable vMAJOR.MINOR.PATCH release") + if not re.fullmatch(SHA256, checksum): + raise ValueError("expected a SHA-256 digest") + + version = tag[1:] + updates = {} + for filename, version_field, hash_field in ( + ("Formula/tsunagi.rb", "VERSION = ", "SHA256 = "), + ("Casks/tsunagi-gui.rb", "version ", "sha256 "), + ): + path = tap / filename + original = path.read_text() + version_pattern = rf'^( {version_field}")({VERSION})(")$' + hash_pattern = rf'^( {hash_field}")({SHA256})(")$' + current = re.findall(version_pattern, original, re.MULTILINE) + if len(current) != 1 or len(re.findall(hash_pattern, original, re.MULTILINE)) != 1: + raise ValueError(f"expected one version and one SHA-256 in {filename}") + if tuple(map(int, version.split("."))) < tuple(map(int, current[0][1].split("."))): + print(f"Skipping older release {tag}: {filename} already has {current[0][1]}") + return + updated = re.sub(version_pattern, rf"\g<1>{version}\g<3>", original, flags=re.MULTILINE) + updated = re.sub(hash_pattern, rf"\g<1>{checksum}\g<3>", updated, flags=re.MULTILINE) + updates[path] = (original, updated) + + for path, (original, updated) in updates.items(): + if updated != original: + path.write_text(updated) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("tap", type=Path) + parser.add_argument("tag") + parser.add_argument("checksum") + args = parser.parse_args() + try: + update_tap(args.tap, args.tag, args.checksum) + except (OSError, ValueError) as error: + parser.exit(1, f"{error}\n") diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e60c4ad..3f40be0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -412,6 +412,99 @@ jobs: '{event_type: "new_package", client_payload: {repository: $repository, tag: $tag}}' \ | gh api --method POST repos/house-of-vanity/arch_repo/dispatches --input - + update-homebrew: + name: Update the Homebrew tap + needs: publish + if: github.server_url == 'https://github.com' && github.repository == 'house-of-vanity/tsunagi' + runs-on: ubuntu-latest + permissions: + contents: read + env: + RELEASE_TAG: ${{ github.ref_name }} + steps: + - name: Check the release tag and tap credentials + id: stable + env: + TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }} + run: | + set -euo pipefail + if [[ ! "$RELEASE_TAG" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then + echo "Skipping Homebrew for non-stable tag $RELEASE_TAG" + exit 0 + fi + if [[ -z "$TAP_TOKEN" ]]; then + echo '::error::Set HOMEBREW_TAP_TOKEN with Contents: write access to house-of-vanity/homebrew-tap.' + exit 1 + fi + echo "publish=true" >> "$GITHUB_OUTPUT" + + - uses: actions/checkout@v5 + if: steps.stable.outputs.publish == 'true' + with: + persist-credentials: false + + - name: Verify the published macOS archive + if: steps.stable.outputs.publish == 'true' + id: archive + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + archive="tsunagi-macos-aarch64-${RELEASE_TAG#v}.tar.gz" + digest=$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$RELEASE_TAG" \ + | jq -er --arg archive "$archive" ' + select(.draft == false and .prerelease == false) + | .assets[] | select(.name == $archive and .state == "uploaded") + | .digest | select(type == "string" and test("^sha256:[0-9a-f]{64}$")) + ') + gh release download "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \ + --pattern "$archive" --dir "$RUNNER_TEMP" + hash="${digest#sha256:}" + actual=$(sha256sum "$RUNNER_TEMP/$archive") + if [[ "${actual%% *}" != "$hash" ]]; then + echo "::error::SHA-256 mismatch for $archive." + exit 1 + fi + echo "hash=$hash" >> "$GITHUB_OUTPUT" + + - uses: actions/checkout@v5 + if: steps.stable.outputs.publish == 'true' + with: + repository: house-of-vanity/homebrew-tap + ref: main + path: homebrew-tap + token: ${{ secrets.HOMEBREW_TAP_TOKEN }} + + - name: Update and push the formula and cask + if: steps.stable.outputs.publish == 'true' + env: + ARCHIVE_SHA256: ${{ steps.archive.outputs.hash }} + run: | + set -euo pipefail + # Retry from the latest tap state if another publisher pushes first. + for attempt in 1 2 3; do + git -C homebrew-tap fetch origin main + git -C homebrew-tap checkout --detach --force FETCH_HEAD + python3 .github/scripts/update_homebrew.py homebrew-tap "$RELEASE_TAG" "$ARCHIVE_SHA256" + cd homebrew-tap + ruby -c Formula/tsunagi.rb + ruby -c Casks/tsunagi-gui.rb + if git diff --quiet -- Formula/tsunagi.rb Casks/tsunagi-gui.rb; then + exit 0 + fi + git config user.name 'github-actions[bot]' + git config user.email '41898282+github-actions[bot]@users.noreply.github.com' + git add -- Formula/tsunagi.rb Casks/tsunagi-gui.rb + git commit -m "tsunagi ${RELEASE_TAG#v}" + if git push origin HEAD:main; then + exit 0 + fi + echo "Push to the Homebrew tap failed on attempt $attempt of 3." >&2 + cd .. + done + echo '::error::Could not push the updated formula and cask to the tap.' + exit 1 + publish-openartifact: name: Publish APT and pacman packages needs: publish diff --git a/dist/macos/README.md b/dist/macos/README.md index 08f038d..e751da9 100644 --- a/dist/macos/README.md +++ b/dist/macos/README.md @@ -41,6 +41,19 @@ The cask starts the service for you. The agent runs as root, and its control socket is open to the `admin` group, so the CLI and the tray work without `sudo` for an administrator. +### Publishing Homebrew packages + +After a stable `vMAJOR.MINOR.PATCH` GitHub release uploads its assets, the +`Update the Homebrew tap` job verifies the Apple Silicon archive against its +GitHub release digest and updates the `tsunagi` formula and `tsunagi-gui` cask +together on `house-of-vanity/homebrew-tap`'s `main` branch. + +Set the `HOMEBREW_TAP_TOKEN` Actions secret in `house-of-vanity/tsunagi` to a +fine-grained token with **Contents: Read and write** on +`house-of-vanity/homebrew-tap`. The token must be able to push to `main`. +If publication fails, fix the reported error and rerun the Homebrew job on +the existing release workflow run. + ## Native deployment — root LaunchDaemon For an always-on agent that starts at boot, install the bundled