diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 404125a..9643070 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -5,6 +5,8 @@ jobs:
runs-on: macos-15
steps:
- uses: actions/checkout@v4
+ - name: Test release automation
+ run: python3 -B -m unittest discover -s Scripts/tests
- name: Checkout local package dependencies
run: |
set -euo pipefail
diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml
index d996459..771e339 100644
--- a/.github/workflows/release-drafter.yml
+++ b/.github/workflows/release-drafter.yml
@@ -6,11 +6,36 @@ on:
push:
branches:
- main
+ paths-ignore:
+ - Sources/XcodesKit/Version.swift
+
+concurrency:
+ group: release-drafter-main
+
+permissions:
+ contents: write
+ pull-requests: read
jobs:
update_release_draft:
+ if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
+ - name: Check for a release in progress
+ id: release
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ set -euo pipefail
+ tags=$(git ls-remote --tags --refs "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git")
+ newest_tag=$(printf '%s\n' "$tags" | cut -f2 | sed -nE 's#^refs/tags/((0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*))$#\1#p' | sort -V | tail -n 1)
+ latest_release=$(gh api "repos/$GITHUB_REPOSITORY/releases/latest" --jq .tag_name)
+ if [[ "$newest_tag" == "$latest_release" ]]; then
+ echo 'ready=true' >> "$GITHUB_OUTPUT"
+ else
+ echo "Waiting for the current stable CLI release before updating the draft."
+ fi
- uses: release-drafter/release-drafter@v7
+ if: steps.release.outputs.ready == 'true'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..7a13f2c
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,13 @@
+# Releasing the xcodes CLI
+
+Run the release command from this repository on the maintainer’s Mac after the changes to ship are merged into GitHub main.
+
+| Task | Command |
+| --- | --- |
+| Preview a release | `./Scripts/release VERSION --dry-run` |
+| Publish a stable release | `./Scripts/release VERSION` |
+| Continue an interrupted release | `./Scripts/release --resume VERSION` |
+
+Use the actual requested version in place of `VERSION`. Run a dry run for planning or readiness checks. Publish or resume only when explicitly asked to do so for that version. If an authorized publication saves a release and then stops, continue with its printed resume command from the same checkout. Verify that it reports both the GitHub release URL and the Homebrew tap commit before reporting completion.
+
+The [release runbook](README.md#releasing-a-new-version-of-xcodes) covers credentials, notes, and recovery.
diff --git a/Makefile b/Makefile
index 85ad3ac..d484600 100644
--- a/Makefile
+++ b/Makefile
@@ -7,7 +7,8 @@ srcdir = Sources
REPODIR = $(shell pwd)
BUILDDIR = $(REPODIR)/.build
SOURCES = $(wildcard $(srcdir)/**/*.swift)
-RELEASEBUILDDIR = $(BUILDDIR)/apple/Products/Release/xcodes
+RELEASEBUILDDIR = $(shell dir=$$($(SWIFT_RELEASE_BUILD) --show-bin-path) && printf '%s/xcodes' "$$dir")
+SWIFT_BUILD_FLAGS ?=
.DEFAULT_GOAL = all
.PHONY: all
@@ -16,15 +17,21 @@ all: xcodes
# -Onone is a temporary workaround for FB7347879
# "swift build" gets stuck on a certain file in this project when using release configuration
# https://github.com/apple/swift/pull/26660
-.PHONY: xcodes
-xcodes: $(SOURCES)
- @swift build \
+SWIFT_RELEASE_BUILD = swift build \
--configuration release \
-Xswiftc -Onone \
--disable-sandbox \
--build-path "$(BUILDDIR)" \
--arch arm64 \
- --arch x86_64 \
+ --arch x86_64 $(SWIFT_BUILD_FLAGS)
+
+.PHONY: xcodes
+xcodes: $(SOURCES)
+ @$(SWIFT_RELEASE_BUILD)
+
+.PHONY: release-bin-path
+release-bin-path:
+ @path="$(RELEASEBUILDDIR)"; test -n "$$path" && printf '%s\n' "$$path"
.PHONY: sign
sign: xcodes
@@ -70,8 +77,8 @@ uninstall:
.PHONY: distclean
distclean:
- @rm -f $(RELEASEBUILDDIR)
+ @path="$(RELEASEBUILDDIR)"; if [ -n "$$path" ]; then rm -f "$$path"; fi
.PHONY: clean
clean: distclean
- @rm -rf $(BUILDDIR)
+ @rm -rf "$(BUILDDIR)"
diff --git a/README.md b/README.md
index 6c3c306..bb1aa6a 100644
--- a/README.md
+++ b/README.md
@@ -69,11 +69,9 @@ Makefile's Developer ID signing or notarization steps.
#### Build output path troubleshooting
-The Makefile expects `.build/apple/Products/Release/xcodes`. Some toolchains
-instead produce `.build/out/Products/Release/xcodes`, also accessible through
-the `.build/release` symlink. If the build succeeds but installation reports
-`No such file or directory` for the expected executable, check the build output
-and override `RELEASEBUILDDIR` with the actual executable path:
+The Makefile uses SwiftPM to locate the release executable. Run
+`make -s release-bin-path` to see the location. For a custom build, override
+`RELEASEBUILDDIR` with the absolute path to the executable.
```sh
make install prefix="$HOME/.local" \
@@ -82,14 +80,6 @@ make install prefix="$HOME/.local" \
"$HOME/.local/bin/xcodes" --help
```
-This override was verified with an installation into a temporary prefix:
-the installed executable contained both arm64 and x86_64 architectures, reported
-version `2.1.0`, and successfully displayed help. The default build succeeded,
-but installation required the path override on that toolchain. A warning about
-x86_64 being deprecated for the active macOS 27.0 deployment target did not
-prevent the universal build from completing. These were build and CLI smoke
-checks, not a test-suite run.
-
Run `make clean` to remove `.build`, including downloaded dependency checkouts.
To remove an installed executable, run `make uninstall` with the same `prefix`
or `bindir` used for installation, for example `make uninstall prefix="$HOME/.local"`.
@@ -250,50 +240,38 @@ The `sign`, `zip`, `bottle`, and `notarize` targets use a hardcoded maintainer
signing identity and require the corresponding certificate and private key.
They are not necessary for local development or installation.
-
-Releasing a new version of xcodes
+### Releasing a new version of xcodes
+
+Merge the changes you intend to ship into `main` in XcodesOrg/xcodes. From this checkout on the maintainer’s Mac, replace `VERSION` with the exact stable version you want to publish.
```sh
-# Bump the version number in Version.swift, commit the change, and tag it
-vim Sources/XcodesKit/Version.swift
-git add Sources/XcodesKit/Version.swift
-git commit -m "Bump version to $VERSION"
-git tag -asm "$VERSION" "$VERSION"
-
-# Run the release automation
-./release.sh --version "$VERSION" --team-id "ABC123"
-
-# Or run the release steps manually:
-# Clean first
-make clean
-
-# Make a release build of xcodes, sign it, and zip it
-make zip
-# Create a Homebrew bottle
-make bottle VERSION="$VERSION"
-
-# Duplicate the Homebrew bottle for all expected platform filenames
-cp "xcodes-$VERSION.mojave.bottle.tar.gz" "xcodes-$VERSION.arm64_mojave.bottle.tar.gz"
-cp "xcodes-$VERSION.mojave.bottle.tar.gz" "xcodes-$VERSION.macos.i386.bottle.tar.gz"
-cp "xcodes-$VERSION.mojave.bottle.tar.gz" "xcodes-$VERSION.macos.arm64.bottle.tar.gz"
-
-# Notarize the release build
-# This can take a while
-make notarize \
- TEAMID="ABC123"
-
-# Push the new version bump commit and tag when ready
-git push --follow-tags
-
-# Edit the draft release created by Release Drafter to point at the new tag
-# Set the release title to the new version
-# Add the xcodes.zip and xcodes-$VERSION.*.bottle.tar.gz files to the release
-# Publish the release
-
-# Update the Homebrew Bottle: https://github.com/XcodesOrg/homebrew-made/blob/master/Formula/xcodes.rb
+./Scripts/release VERSION --dry-run
+./Scripts/release VERSION
```
-
+The dry run shows the GitHub source commit, the notes source, and the Homebrew bottle destination. To customize the notes, edit the Release Drafter draft before running the publish command. The command preserves the draft body and generates GitHub release notes when the draft is missing or empty.
+
+The release command builds and tests in an isolated checkout. It signs and notarizes the universal CLI, publishes the GitHub release and its assets, and updates the Homebrew formula. Success prints the GitHub release URL and Homebrew tap commit. The root [AGENTS.md](AGENTS.md) records the commands for future agents.
+
+#### One-time setup
+
+- Install and select a full Xcode installation. Install Python 3.9 or newer and the GitHub CLI.
+- Sign in with `gh auth login`. Use an account with admin push access to CLI `main` under its current branch protection and push access to `main` in XcodesOrg/homebrew-made. Set your Git name and email. The command uses your Git signing configuration for commits and annotated release tags.
+- Install the Developer ID Application certificate for team `ZU6GR6B2FY` and its private key in your Mac’s Keychain. Save your Apple ID notarization credentials in the `AC_PASSWORD` Keychain profile. Enter the app-specific password when prompted.
+
+```sh
+xcrun notarytool store-credentials AC_PASSWORD --apple-id YOUR_APPLE_ID --team-id ZU6GR6B2FY
+```
+
+#### Resuming a release
+
+If the command prints a resume instruction, use the same checkout and version. Prepared artifacts and the release state live under the checkout’s Git directory. Resume reuses verified uploads and completes an outstanding Homebrew update. If `main` advanced before the tag was pushed, resume builds from current `main`.
+
+```sh
+./Scripts/release --resume VERSION
+```
+
+If preparation stops before saving artifacts, resolve the error and rerun the original command. Use the dry run to check GitHub access and the notarization profile, and use `security find-identity -v -p codesigning` to check the Developer ID identity. If Apple reports a missing or expired agreement, have the Account Holder accept it before retrying. The legacy `release.sh` command remains available for packaging an already-versioned checkout.
Notable design decisions are recorded in [DECISIONS.md](./DECISIONS.md). The Apple authentication flow is described in [Apple.paw](./Apple.paw), which will allow you to play with the API endpoints that are involved using the [Paw](https://paw.cloud) app.
diff --git a/Scripts/release b/Scripts/release
new file mode 100755
index 0000000..3a383dd
--- /dev/null
+++ b/Scripts/release
@@ -0,0 +1,531 @@
+#!/usr/bin/env python3
+"""Publish a stable xcodes CLI release from a maintainer's Mac."""
+
+import argparse
+import base64
+import fcntl
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import sys
+import tarfile
+import tempfile
+import time
+from zipfile import ZIP_DEFLATED, ZipFile
+
+
+ROOT = Path(__file__).resolve().parent.parent
+CLI = "XcodesOrg/xcodes"
+TAP = "XcodesOrg/homebrew-made"
+VERSION_FILE = "Sources/XcodesKit/Version.swift"
+FORMULA = "Formula/xcodes.rb"
+TEAM = "ZU6GR6B2FY"
+SIGNING_IDENTITY = f"Developer ID Application: Matt Kiazyk ({TEAM})"
+VERSION = r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)"
+VERSION_LITERAL = rf'(?m)^([ \t]*Version\(")({VERSION})("\)![ \t]*)$'
+FORMULA_TAG = rf'(?m)^( url "https://github\.com/{CLI}\.git", tag: ")({VERSION})(")$'
+BOTTLE_PLATFORMS = ("all", "mojave", "arm64_mojave", "macos.i386", "macos.arm64")
+DEPENDENCIES = ("XcodesLoginKit", "XcodesKit")
+ENV = {**os.environ, "GH_PROMPT_DISABLED": "1", "GIT_TERMINAL_PROMPT": "0"}
+
+
+class ReleaseError(Exception):
+ pass
+
+
+def run(*command, cwd=ROOT, data=None, capture=True):
+ result = subprocess.run(
+ command, cwd=cwd, input=data, stdout=subprocess.PIPE if capture else None, env=ENV,
+ )
+ if result.returncode:
+ raise ReleaseError(f"{' '.join(map(os.fspath, command[:2]))} exited with status {result.returncode}.")
+ return result.stdout
+
+
+def git(*args, **kwargs):
+ return run("git", "-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential",
+ *args, **kwargs)
+
+
+def github(repo, path="", *, method="GET", body=None, paginate=False):
+ args = ["gh", "api", "--hostname", "github.com", "--method", method, f"repos/{repo}{path}"]
+ if paginate:
+ args += ["--paginate", "--slurp"]
+ if body is not None:
+ args += ["--input", "-"]
+ data = json.dumps(body).encode() if body is not None else None
+ try:
+ output = run(*args, data=data)
+ except ReleaseError as error:
+ raise ReleaseError(f"GitHub {method} repos/{repo}{path} failed: {error}") from error
+ return json.loads(output) if output else None
+
+
+def repo_url(repo):
+ return f"https://github.com/{repo}.git"
+
+
+def remote_refs(repo, *patterns):
+ lines = git("ls-remote", "--refs", repo_url(repo), *patterns).decode().splitlines()
+ return {ref: sha for sha, ref in (line.split("\t") for line in lines)}
+
+
+def remote_file(repo, path, ref):
+ result = github(repo, f"/contents/{path}?ref={ref}")
+ return base64.b64decode(result["content"]).decode()
+
+
+def releases():
+ return [item for page in github(CLI, "/releases?per_page=100", paginate=True) for item in page]
+
+
+def version_key(version):
+ return tuple(map(int, version.split(".")))
+
+
+def one_match(pattern, text, description):
+ matches = list(re.finditer(pattern, text))
+ if len(matches) != 1:
+ raise ReleaseError(f"Expected one {description}, found {len(matches)}.")
+ return matches[0]
+
+
+def replace_one(pattern, text, replacement, description):
+ match = one_match(pattern, text, description)
+ return text[:match.start()] + replacement(match) + text[match.end():]
+
+
+def bottle_name(version, platform="all"):
+ return f"xcodes-{version}.{platform}.bottle.tar.gz"
+
+
+def download_root(version):
+ return f"https://github.com/{CLI}/releases/download/{version}"
+
+
+def rewrite_formula(text, manifest, resolved, version, checksum):
+ text = replace_one(FORMULA_TAG, text, lambda m: f"{m[1]}{version}{m[3]}", "formula source tag")
+ bottle_pattern = (
+ rf'(?m)^ bottle do\n root_url "https://github\.com/{CLI}/releases/download/{VERSION}"\n'
+ r'(?: sha256 cellar: :any_skip_relocation, (?:arm64_mojave|mojave|all): +"[0-9a-f]{64}"\n)+ end$'
+ )
+ bottle = (
+ f' bottle do\n root_url "{download_root(version)}"\n'
+ f' sha256 cellar: :any_skip_relocation, all: "{checksum}"\n end'
+ )
+ text = replace_one(bottle_pattern, text, lambda _: bottle, "formula bottle block")
+ pins = json.loads(resolved)["pins"]
+ for dependency in DEPENDENCIES:
+ url = f"https://github.com/XcodesOrg/{dependency}.git"
+ declaration = one_match(
+ rf"""(?m)^[ \t]*(\.package\(url: "{re.escape(url)}", [^'\n]+\)),?[ \t]*$""",
+ manifest, f"{dependency} package declaration",
+ )[1]
+ revisions = [
+ pin["state"]["revision"] for pin in pins
+ if pin["identity"] == dependency.lower() and pin["location"].lower() == url.lower()
+ ]
+ if len(revisions) != 1 or not re.fullmatch(r"[0-9a-f]{40}", revisions[0]):
+ raise ReleaseError(f"Expected one locked revision for {dependency}.")
+ resource = (
+ rf'(?m)^( resource "{dependency}" do\n url "{re.escape(url)}",\n'
+ r' revision: ")[0-9a-f]{40}("\n end)$'
+ )
+ text = replace_one(resource, text, lambda m: f"{m[1]}{revisions[0]}{m[2]}", f"{dependency} resource")
+ substitution = (
+ rf"""(?m)^([ \t]+\.gsub\(')\.package\(url: "{re.escape(url)}", [^'\n]+\)"""
+ rf"""(',\n[ \t]+'\.package\(path: "{dependency}"\)'\))$"""
+ )
+ text = replace_one(substitution, text, lambda m: f"{m[1]}{declaration}{m[2]}",
+ f"{dependency} source substitution")
+ run("ruby", "-c", data=text.encode())
+ return text
+
+
+def drafter_candidate(all_releases):
+ drafts = [
+ item for item in all_releases
+ if item["draft"] and not item["prerelease"]
+ and item["target_commitish"] in ("main", "refs/heads/main")
+ and item["author"]["login"] == "github-actions[bot]"
+ and (not item["tag_name"] or item["tag_name"].startswith("untagged-"))
+ ]
+ if len(drafts) > 1:
+ raise ReleaseError("GitHub has multiple Release Drafter drafts for main.")
+ if drafts and drafts[0]["assets"]:
+ raise ReleaseError("The untagged Release Drafter draft already has assets.")
+ return drafts[0] if drafts else None
+
+
+def inspect_release(version):
+ refs = remote_refs(CLI, "refs/heads/main", "refs/tags/*")
+ base = refs["refs/heads/main"]
+ tags = [ref.removeprefix("refs/tags/") for ref in refs if ref.startswith("refs/tags/")]
+ stable = max((tag for tag in tags if re.fullmatch(VERSION, tag)), key=version_key)
+ latest = github(CLI, "/releases/latest")["tag_name"]
+ if stable != latest:
+ raise ReleaseError(f"The stable tag {stable} is still awaiting publication. Resume that release first.")
+ source_version = one_match(VERSION_LITERAL, remote_file(CLI, VERSION_FILE, base), "CLI version")[2]
+ if version_key(version) <= max(version_key(stable), version_key(source_version)):
+ raise ReleaseError(f"{version} must be greater than both the published version {stable} and main's version {source_version}.")
+ all_releases = releases()
+ if any(item["tag_name"] == version for item in all_releases):
+ raise ReleaseError(f"A GitHub release already uses tag {version}.")
+ tap_base = remote_refs(TAP, "refs/heads/main")["refs/heads/main"]
+ formula = remote_file(TAP, FORMULA, tap_base)
+ tap_version = one_match(FORMULA_TAG, formula, "formula source tag")[2]
+ if tap_version != latest:
+ raise ReleaseError(f"Homebrew has {tap_version} and GitHub has {latest}. Finish the previous Homebrew update first.")
+ return {"version": version, "base": base, "previous": latest}, drafter_candidate(all_releases), formula
+
+
+def print_preview(state, draft, *, dry_run):
+ version = state["version"]
+ prefix = "Dry run" if dry_run else "Preparing"
+ print(f"{prefix} {version} from {CLI} main at {state['base'][:12]}", flush=True)
+ notes = draft["html_url"] if draft and (draft["body"] or "").strip() else "GitHub-generated notes"
+ print(f"Release notes: {notes}\nHomebrew: {TAP} main ({bottle_name(version)})", flush=True)
+
+
+def preflight():
+ if sys.platform != "darwin":
+ raise ReleaseError("Run this release command on the maintainer's Mac.")
+ cli = github(CLI)["permissions"]
+ if not cli["admin"] or not cli["push"] or not github(TAP)["permissions"]["push"]:
+ raise ReleaseError(f"GitHub requires admin push access to {CLI} main and push access to {TAP} main.")
+ run("ruby", "--version")
+
+
+def build_preflight():
+ run("xcodebuild", "-version")
+ identities = run("security", "find-identity", "-v", "-p", "codesigning").decode()
+ if f'"{SIGNING_IDENTITY}"' not in identities:
+ raise ReleaseError(f"Install the certificate and private key for {SIGNING_IDENTITY}.")
+ run("xcrun", "notarytool", "history", "--keychain-profile", "AC_PASSWORD", "--team-id", TEAM)
+
+
+def clone_main(repo, destination):
+ git("clone", "--quiet", "--depth", "1", "--no-tags", "--branch", "main", repo_url(repo), destination)
+ # Keep the maintainer's repo-local identity and signing policy in the isolated checkout.
+ config = subprocess.run(
+ ["git", "config", "--null", "--get-regexp",
+ r"^(user\.(name|email|signingkey)$|gpg\.|commit\.gpgsign$|tag\.(gpgsign|forcesignannotated)$)"],
+ cwd=ROOT, stdout=subprocess.PIPE, env=ENV,
+ )
+ if config.returncode not in (0, 1):
+ raise ReleaseError("Could not read Git identity and signing settings.")
+ for entry in config.stdout.decode().split("\0"):
+ if entry:
+ key, value = entry.split("\n", 1)
+ git("config", "--local", key, value, cwd=destination)
+ return git("rev-parse", "HEAD", cwd=destination).decode().strip()
+
+
+def fingerprint(path):
+ digest = hashlib.sha256()
+ with path.open("rb") as file:
+ for block in iter(lambda: file.read(1024 * 1024), b""):
+ digest.update(block)
+ return {"digest": f"sha256:{digest.hexdigest()}", "size": path.stat().st_size}
+
+
+def make_artifacts(path, source, version):
+ swift_flags = "SWIFT_BUILD_FLAGS=--disable-automatic-resolution"
+ run("make", "sign", swift_flags, cwd=source, capture=False)
+ binary = Path(run("make", "-s", "release-bin-path", swift_flags, cwd=source).decode().strip())
+ if not binary.is_file() or source not in binary.resolve().parents:
+ raise ReleaseError("Could not locate the release executable in the isolated checkout.")
+ if run(binary, "version", cwd=source).decode().strip() != version:
+ raise ReleaseError("The new executable reports the wrong version.")
+ if set(run("lipo", "-archs", binary).decode().split()) != {"x86_64", "arm64"}:
+ raise ReleaseError("The executable is missing the requested universal architectures.")
+ run("codesign", "--verify", "--strict", binary)
+ signing = subprocess.check_output(
+ ["codesign", "--display", "--verbose=4", binary], stderr=subprocess.STDOUT,
+ ).decode().splitlines()
+ if f"Authority={SIGNING_IDENTITY}" not in signing or f"TeamIdentifier={TEAM}" not in signing:
+ raise ReleaseError(f"The executable is missing the expected Developer ID signature for {TEAM}.")
+ archive = path / "xcodes.zip"
+ with ZipFile(archive, "w", compression=ZIP_DEFLATED) as zipped:
+ zipped.write(binary, "xcodes")
+ bottle = path / bottle_name(version)
+ with tarfile.open(bottle, "w:gz") as tar:
+ tar.add(binary, arcname=f"xcodes/{version}/bin/xcodes")
+ for platform in BOTTLE_PLATFORMS[1:]:
+ shutil.copyfile(bottle, path / bottle_name(version, platform))
+ run("./notarize.sh", archive, TEAM, cwd=source, capture=False)
+ names = [archive.name, *(bottle_name(version, platform) for platform in BOTTLE_PLATFORMS)]
+ return {name: fingerprint(path / name) for name in names}
+
+
+def save_state(path, state):
+ temporary = path / "release.json.tmp"
+ temporary.write_text(json.dumps(state, indent=2) + "\n")
+ temporary.replace(path / "release.json")
+
+
+def prepare(path, state, formula):
+ with tempfile.TemporaryDirectory(prefix="preparing-", dir=path.parent) as temporary:
+ stage = Path(temporary) / path.name
+ stage.mkdir()
+ source = stage / "source"
+ if clone_main(CLI, source) != state["base"]:
+ raise ReleaseError("main moved while preparing the checkout. Retry the release command.")
+ if not (source / "Scripts/release").is_file():
+ raise ReleaseError("Merge the release automation into CLI main before publishing.")
+ version = state["version"]
+ version_file = source / VERSION_FILE
+ version_file.write_text(replace_one(
+ VERSION_LITERAL, version_file.read_text(), lambda m: f"{m[1]}{version}{m[3]}", "CLI version",
+ ))
+ rewrite_formula(formula, (source / "Package.swift").read_text(),
+ (source / "Package.resolved").read_text(), version, "0" * 64)
+ git("add", "--", VERSION_FILE, cwd=source)
+ git("commit", "-m", f"Release {version}", cwd=source, capture=False)
+ git("tag", "-a", version, "-m", version, cwd=source)
+ run("swift", "test", "--disable-automatic-resolution", cwd=source, capture=False)
+ state["artifacts"] = make_artifacts(stage, source, version)
+ shutil.rmtree(source / ".build")
+ state["commit"] = git("rev-parse", "HEAD", cwd=source).decode().strip()
+ state["tag_sha"] = git("rev-parse", f"refs/tags/{version}", cwd=source).decode().strip()
+ save_state(stage, state)
+ if path.exists():
+ path.rename(Path(temporary) / "superseded")
+ stage.rename(path)
+
+
+def push_version(path, state):
+ version = state["version"]
+ tag = f"refs/tags/{version}"
+ refs = remote_refs(CLI, "refs/heads/main", tag)
+ if refs.get(tag) == state["tag_sha"]:
+ return
+ if tag in refs or refs["refs/heads/main"] != state["base"]:
+ raise ReleaseError("The release tag or CLI main changed on GitHub. Resume to reconcile the release.")
+ git("push", "--atomic", "origin", f"{state['commit']}:refs/heads/main", f"{tag}:{tag}",
+ cwd=path / "source", capture=False)
+ if remote_refs(CLI, tag).get(tag) != state["tag_sha"]:
+ raise ReleaseError("GitHub did not confirm the expected release tag.")
+
+
+def wait_for_drafter():
+ deadline = time.monotonic() + 300
+ while True:
+ runs = github(CLI, "/actions/workflows/release-drafter.yml/runs?branch=main&per_page=100")["workflow_runs"]
+ if all(run["status"] == "completed" for run in runs):
+ return
+ if time.monotonic() >= deadline:
+ raise ReleaseError("Release Drafter is still running. Resume after the workflow finishes.")
+ time.sleep(5)
+
+
+def verify_asset(asset, expected):
+ if asset["state"] != "uploaded" or any(asset.get(key) != value for key, value in expected.items()):
+ raise ReleaseError(f"GitHub asset {asset['name']} does not match the saved size and SHA-256.")
+
+
+def release_assets(release, expected):
+ assets = {}
+ for asset in release["assets"]:
+ name = asset["name"]
+ if name not in expected or name in assets:
+ raise ReleaseError(f"GitHub release has an unexpected or duplicate asset named {name}.")
+ assets[name] = asset
+ return assets
+
+
+def draft_release(path, state, all_releases):
+ version = state["version"]
+ candidate = drafter_candidate(all_releases)
+ if state.get("draft_id") is not None and (not candidate or candidate["id"] != state["draft_id"]):
+ raise ReleaseError("The saved Release Drafter draft was replaced or repurposed.")
+ body = candidate["body"] if candidate else ""
+ if not (body or "").strip():
+ body = github(CLI, "/releases/generate-notes", method="POST", body={
+ "tag_name": version, "target_commitish": state["commit"], "previous_tag_name": state["previous"],
+ })["body"]
+ if not (body or "").strip():
+ raise ReleaseError("GitHub returned empty release notes.")
+ payload = {"tag_name": version, "target_commitish": state["commit"], "name": version,
+ "body": body, "draft": True, "prerelease": False}
+ if candidate:
+ state["draft_id"] = candidate["id"]
+ save_state(path, state)
+ return github(CLI, f"/releases/{candidate['id']}", method="PATCH", body=payload)
+ return github(CLI, "/releases", method="POST", body=payload)
+
+
+def release_for_tag(all_releases, version):
+ matches = [item for item in all_releases if item["tag_name"] == version]
+ if len(matches) > 1:
+ raise ReleaseError(f"Multiple GitHub releases use {version}.")
+ return matches[0] if matches else None
+
+
+def publish(path, state):
+ version = state["version"]
+ release = release_for_tag(releases(), version)
+ if not release:
+ wait_for_drafter()
+ all_releases = releases()
+ release = release_for_tag(all_releases, version) or draft_release(path, state, all_releases)
+ if release["prerelease"] or release["tag_name"] != version or (
+ state.get("draft_id") is not None and release["id"] != state["draft_id"]
+ ) or (release["draft"] and release["name"] != version):
+ raise ReleaseError(f"GitHub returned a different release for {version}.")
+ state["draft_id"] = release["id"]
+ save_state(path, state)
+ endpoint = f"/releases/{release['id']}"
+ expected = state["artifacts"]
+ assets = release_assets(release, expected)
+ if release["draft"]:
+ for name, metadata in expected.items():
+ asset = assets.get(name)
+ if asset and asset["state"] == "starter" and asset["size"] == 0:
+ github(CLI, f"/releases/assets/{asset['id']}", method="DELETE")
+ asset = None
+ if asset:
+ verify_asset(asset, metadata)
+ else:
+ run("gh", "release", "upload", version, path / name, "--repo", f"github.com/{CLI}", capture=False)
+ release = github(CLI, endpoint)
+ if not release["draft"] or any(
+ release[key] != value for key, value in (("tag_name", version), ("name", version), ("prerelease", False))
+ ) or not (release["body"] or "").strip():
+ raise ReleaseError("The GitHub draft changed during upload.")
+ assets = release_assets(release, expected)
+ if assets.keys() != expected.keys():
+ raise ReleaseError("GitHub is missing one or more release assets.")
+ for name, asset in assets.items():
+ verify_asset(asset, expected[name])
+ ref = f"refs/tags/{version}"
+ if release["draft"]:
+ if remote_refs(CLI, ref).get(ref) != state["tag_sha"]:
+ raise ReleaseError(f"The GitHub tag for {version} changed before publication.")
+ release = github(CLI, endpoint, method="PATCH", body={
+ "draft": False, "make_latest": "true", "target_commitish": state["commit"],
+ })
+ if release["draft"] or release["prerelease"] or release["tag_name"] != version:
+ raise ReleaseError("GitHub did not publish the expected stable release.")
+ if github(CLI, "/releases/latest")["tag_name"] != version:
+ raise ReleaseError(f"GitHub does not report {version} as the latest stable release.")
+ if remote_refs(CLI, ref).get(ref) != state["tag_sha"]:
+ raise ReleaseError(f"The GitHub tag for {version} changed during publication.")
+ print(f"GitHub release: {release['html_url']}", flush=True)
+
+
+def update_tap(path, state):
+ version = state["version"]
+ name = bottle_name(version)
+ expected = state["artifacts"][name]
+ with tempfile.TemporaryDirectory(prefix="updating-tap-", dir=path.parent) as temporary:
+ temporary = Path(temporary)
+ download = temporary / name
+ run("curl", "--fail", "--silent", "--show-error", "--location", "--retry", "3", "--retry-all-errors",
+ "--max-time", "120", "--output", download, f"{download_root(version)}/{name}")
+ if fingerprint(download) != expected:
+ raise ReleaseError("The public Homebrew bottle does not match the notarized release.")
+ checkout = temporary / "tap"
+ base = clone_main(TAP, checkout)
+ formula = checkout / FORMULA
+ original = formula.read_text()
+ sources = [
+ git("show", f"{state['commit']}:{file}", cwd=path / "source").decode()
+ for file in ("Package.swift", "Package.resolved")
+ ]
+ candidate = rewrite_formula(original, *sources, version, expected["digest"].removeprefix("sha256:"))
+ tap_version = one_match(FORMULA_TAG, original, "formula source tag")[2]
+ if original == candidate:
+ commit = base
+ else:
+ if tap_version != state["previous"]:
+ raise ReleaseError(f"Homebrew has an unexpected or conflicting formula for xcodes {tap_version}.")
+ formula.write_text(candidate)
+ git("add", "--", FORMULA, cwd=checkout)
+ git("commit", "-m", f"Update xcodes to {version}", cwd=checkout, capture=False)
+ git("push", "origin", "HEAD:refs/heads/main", cwd=checkout, capture=False)
+ commit = git("rev-parse", "HEAD", cwd=checkout).decode().strip()
+ tip = remote_refs(TAP, "refs/heads/main")["refs/heads/main"]
+ if remote_file(TAP, FORMULA, tip) != candidate:
+ raise ReleaseError("Could not verify the updated formula on GitHub.")
+ print(f"Homebrew tap: https://github.com/{TAP}/commit/{commit}", flush=True)
+
+
+def finish(path, state):
+ version = state["version"]
+ for name, expected in state["artifacts"].items():
+ if fingerprint(path / name) != expected:
+ raise ReleaseError(f"The saved artifact {name} no longer matches the prepared release.")
+ push_version(path, state)
+ publish(path, state)
+ update_tap(path, state)
+ print(f"Released xcodes {version} on GitHub and Homebrew.", flush=True)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ target = parser.add_mutually_exclusive_group(required=True)
+ target.add_argument("version", metavar="VERSION", nargs="?", help="stable version to publish")
+ target.add_argument("--resume", metavar="VERSION", help="continue a release prepared in this checkout")
+ parser.add_argument("--dry-run", action="store_true", help="preview a new release using read-only checks")
+ args = parser.parse_args()
+ version = args.version or args.resume
+ if not re.fullmatch(VERSION, version):
+ parser.error("VERSION must have the form MAJOR.MINOR.PATCH, for example 2.2.1.")
+ if args.resume and args.dry_run:
+ parser.error("--dry-run applies to a new release.")
+ preflight()
+ if args.dry_run:
+ state, draft, formula = inspect_release(version)
+ sources = [remote_file(CLI, file, state["base"]) for file in ("Package.swift", "Package.resolved")]
+ rewrite_formula(formula, *sources, version, "0" * 64)
+ build_preflight()
+ print_preview(state, draft, dry_run=True)
+ return
+ git_dir = Path(git("rev-parse", "--path-format=absolute", "--git-common-dir").decode().strip())
+ storage = git_dir / "xcodes-cli-releases"
+ storage.mkdir(exist_ok=True)
+ with (storage / "release.lock").open("a") as lock:
+ try:
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ raise ReleaseError("Another release is running in this checkout.") from None
+ path = storage / version
+ journal = path / "release.json"
+ if args.resume and not journal.is_file():
+ raise ReleaseError(f"No prepared release for {version} was found in this checkout.")
+ if not args.resume and journal.is_file():
+ raise ReleaseError(f"Use ./Scripts/release --resume {version} to continue the saved release.")
+ try:
+ state = json.loads(journal.read_text()) if args.resume else None
+ if state:
+ if state["version"] != version:
+ raise ReleaseError(f"The saved release state belongs to {state['version']}, not {version}.")
+ tag = f"refs/tags/{version}"
+ refs = remote_refs(CLI, "refs/heads/main", tag)
+ if tag not in refs and refs["refs/heads/main"] != state["base"]:
+ print("CLI main advanced before the release was pushed. Rebuilding from current main.", flush=True)
+ state = None
+ if state is None:
+ state, draft, formula = inspect_release(version)
+ build_preflight()
+ print_preview(state, draft, dry_run=False)
+ prepare(path, state, formula)
+ finish(path, state)
+ except (ReleaseError, OSError, subprocess.SubprocessError, ValueError, KeyError, KeyboardInterrupt):
+ if journal.is_file():
+ print(f"Continue with ./Scripts/release --resume {version}", file=sys.stderr)
+ raise
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except (ReleaseError, OSError, subprocess.SubprocessError, ValueError, KeyError) as error:
+ sys.exit(f"Release stopped: {error}")
+ except KeyboardInterrupt:
+ sys.exit("Release interrupted.")
diff --git a/Scripts/tests/test_release.py b/Scripts/tests/test_release.py
new file mode 100644
index 0000000..5307455
--- /dev/null
+++ b/Scripts/tests/test_release.py
@@ -0,0 +1,235 @@
+import contextlib
+import importlib.machinery
+import importlib.util
+import io
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+import unittest
+from unittest.mock import patch
+
+
+ROOT = Path(__file__).resolve().parents[2]
+loader = importlib.machinery.SourceFileLoader("release", str(ROOT / "Scripts/release"))
+spec = importlib.util.spec_from_loader(loader.name, loader)
+release = importlib.util.module_from_spec(spec)
+loader.exec_module(release)
+
+MANIFEST = '''
+ .package(url: "https://github.com/XcodesOrg/XcodesLoginKit.git", revision: "v1.2.0"),
+ .package(url: "https://github.com/XcodesOrg/XcodesKit.git", .upToNextMinor(from: "1.2.0"))
+'''
+PINS = json.dumps({"pins": [
+ {"identity": name.lower(), "location": f"https://github.com/XcodesOrg/{name}.git",
+ "state": {"revision": digit * 40}}
+ for name, digit in zip(release.DEPENDENCIES, ("a", "b"))
+]})
+FORMULA = f'''class Xcodes < Formula
+ url "https://github.com/XcodesOrg/xcodes.git", tag: "2.2.0"
+ head "https://github.com/XcodesOrg/xcodes.git", branch: "main"
+
+ bottle do
+ root_url "https://github.com/XcodesOrg/xcodes/releases/download/2.2.0"
+ sha256 cellar: :any_skip_relocation, arm64_mojave: "{"c" * 64}"
+ sha256 cellar: :any_skip_relocation, mojave: "{"c" * 64}"
+ end
+
+ depends_on macos: :ventura
+
+ resource "XcodesLoginKit" do
+ url "https://github.com/XcodesOrg/XcodesLoginKit.git",
+ revision: "{"c" * 40}"
+ end
+
+ resource "XcodesKit" do
+ url "https://github.com/XcodesOrg/XcodesKit.git",
+ revision: "{"d" * 40}"
+ end
+
+ def install
+ package_swift.atomic_write package_swift.read
+ .gsub('.package(url: "https://github.com/XcodesOrg/XcodesLoginKit.git", branch: "main")',
+ '.package(path: "XcodesLoginKit")')
+ .gsub('.package(url: "https://github.com/XcodesOrg/XcodesKit.git", .upToNextMinor(from: "1.1.0"))',
+ '.package(path: "XcodesKit")')
+ end
+end
+'''
+
+
+class ReleaseTests(unittest.TestCase):
+ def test_formula_tracks_the_locked_source_and_is_idempotent(self):
+ rendered = release.rewrite_formula(FORMULA, MANIFEST, PINS, "2.2.1", "e" * 64)
+ self.assertIn(f'all: "{"e" * 64}"', rendered)
+ self.assertIn('tag: "2.2.1"', rendered)
+ self.assertIn('depends_on macos: :ventura', rendered)
+ for declaration in MANIFEST.strip().splitlines():
+ self.assertIn(declaration.strip().rstrip(","), rendered)
+ self.assertIn(f'revision: "{"a" * 40}"', rendered)
+ self.assertIn(f'revision: "{"b" * 40}"', rendered)
+ self.assertEqual(rendered, release.rewrite_formula(rendered, MANIFEST, PINS, "2.2.1", "e" * 64))
+
+ def test_notarization_requires_accepted_status(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ path = Path(temporary)
+ archive = path / "xcodes.zip"
+ archive.touch()
+ stub = path / "xcrun"
+ stub.write_text('''#!/bin/sh
+if [ "$2" = submit ]; then
+ printf '{"status":"%s","id":"fixture-id"}\\n' "$TEST_NOTARY_STATUS"
+else
+ echo "notarization log for $3"
+fi
+''')
+ stub.chmod(0o755)
+ for status, success in (("Invalid", False), ("In Progress", False), ("Accepted", True)):
+ with self.subTest(status=status):
+ result = subprocess.run(
+ [ROOT / "notarize.sh", archive, release.TEAM], capture_output=True, text=True,
+ env={**os.environ, "PATH": f"{path}:{os.environ['PATH']}", "TEST_NOTARY_STATUS": status},
+ )
+ self.assertEqual(result.returncode == 0, success, result.stderr)
+ if not success:
+ self.assertIn(f"Notarization status: {status}", result.stderr)
+
+ def test_push_stops_when_main_moves(self):
+ state = {"version": "2.2.1", "tag_sha": "wanted-tag", "base": "original-main"}
+ with patch.object(release, "remote_refs", return_value={"refs/heads/main": "new-main"}):
+ with patch.object(release, "git") as git:
+ with self.assertRaisesRegex(release.ReleaseError, "CLI main changed"):
+ release.push_version(Path("/unused"), state)
+ git.assert_not_called()
+
+ def test_missing_draft_generates_notes_for_the_tagged_commit(self):
+ state = {"version": "2.2.1", "previous": "2.2.0", "commit": "tagged-commit"}
+ with patch.object(release, "github", side_effect=[{"body": "Generated notes"}, {"id": 1}]) as github:
+ release.draft_release(Path("/unused"), state, [])
+ generated, created = github.call_args_list
+ self.assertEqual(generated.kwargs["body"], {
+ "tag_name": "2.2.1", "previous_tag_name": "2.2.0", "target_commitish": "tagged-commit",
+ })
+ self.assertEqual(created.kwargs["body"]["body"], "Generated notes")
+ self.assertTrue(created.kwargs["body"]["draft"])
+
+ def test_uploaded_asset_with_wrong_digest_stops_publication(self):
+ asset = {"name": "xcodes.zip", "state": "uploaded", "size": 123, "digest": "sha256:wrong"}
+ with self.assertRaisesRegex(release.ReleaseError, "does not match"):
+ release.verify_asset(asset, {"size": 123, "digest": "sha256:expected"})
+
+ def test_release_preserves_draft_and_resumes_upload_and_tap_push(self):
+ with tempfile.TemporaryDirectory() as temporary, contextlib.redirect_stdout(io.StringIO()):
+ root = Path(temporary)
+ repos = {repo: root / repo.split("/")[1] for repo in (release.CLI, release.TAP)}
+ git_env = {
+ **release.ENV, "GIT_AUTHOR_NAME": "Release Fixture", "GIT_AUTHOR_EMAIL": "fixture@example.invalid",
+ "GIT_COMMITTER_NAME": "Release Fixture", "GIT_COMMITTER_EMAIL": "fixture@example.invalid",
+ "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_SYSTEM": os.devnull,
+ }
+ with patch.object(release, "ENV", git_env), patch.object(release, "ROOT", root / "seed-xcodes"):
+ self.exercise_release(root, repos)
+
+ def exercise_release(self, root, repos):
+ def seed(repo, files):
+ destination = root / f"seed-{repos[repo].name}"
+ destination.mkdir()
+ release.git("init", "--quiet", "-b", "main", cwd=destination)
+ for name, text in files.items():
+ file = destination / name
+ file.parent.mkdir(parents=True, exist_ok=True)
+ file.write_text(text)
+ release.git("add", ".", cwd=destination)
+ release.git("commit", "--quiet", "-m", "Initial", cwd=destination)
+ release.git("clone", "--bare", "--quiet", destination, repos[repo], cwd=destination)
+ return release.git("rev-parse", "HEAD", cwd=destination).decode().strip()
+
+ base = seed(release.CLI, {
+ release.VERSION_FILE: 'public var version: Version {\n Version("2.2.0")!\n}\n',
+ "Scripts/release": "# release command fixture\n",
+ "Package.swift": MANIFEST, "Package.resolved": PINS,
+ })
+ seed(release.TAP, {release.FORMULA: FORMULA})
+ storage = root / "releases"
+ storage.mkdir()
+ path = storage / "2.2.1"
+ draft = {"id": 1, "draft": True, "prerelease": False, "tag_name": "",
+ "body": "Customized release notes", "target_commitish": "main",
+ "author": {"login": "github-actions[bot]"}, "assets": [], "html_url": "fixture-release"}
+ uploads = []
+ tap_pushes = []
+
+ def github(repo, endpoint="", *, method="GET", body=None, paginate=False):
+ if (repo, endpoint) == (release.CLI, "/releases?per_page=100"):
+ return [[draft.copy()]]
+ if endpoint.startswith("/actions/"):
+ return {"workflow_runs": [{"status": "completed"}]}
+ if (repo, endpoint) == (release.CLI, "/releases/1"):
+ if method == "PATCH":
+ draft.update(body)
+ return draft.copy()
+ if (repo, endpoint) == (release.CLI, "/releases/latest"):
+ self.assertFalse(draft["draft"])
+ return draft.copy()
+ self.fail(f"Unexpected GitHub call {repo}{endpoint} ({method})")
+
+ def remote_file(repo, name, ref):
+ return release.git("show", f"{ref}:{name}", cwd=repos[repo]).decode()
+
+ actual_run = release.run
+
+ def run(*command, **options):
+ if command[:2] == ("swift", "test"):
+ (options["cwd"] / ".build").mkdir()
+ return
+ if command[:3] == ("gh", "release", "upload"):
+ artifact = command[4]
+ if len(uploads) == 1:
+ uploads.append("interrupted")
+ raise release.ReleaseError("upload interrupted")
+ uploads.append(artifact.name)
+ draft["assets"].append({"name": artifact.name, "state": "uploaded", **release.fingerprint(artifact)})
+ return
+ if command[0] == "curl":
+ self.assertFalse(draft["draft"])
+ shutil.copyfile(path / release.bottle_name("2.2.1"), command[-2])
+ return
+ if "push" in command and options["cwd"].name == "tap":
+ tap_pushes.append(command)
+ if len(tap_pushes) == 1:
+ raise release.ReleaseError("tap push interrupted")
+ return actual_run(*command, **options)
+
+ def make_artifacts(stage, source, version):
+ self.assertIn(f'Version("{version}")!', (source / release.VERSION_FILE).read_text())
+ names = ["xcodes.zip", *(release.bottle_name(version, platform) for platform in release.BOTTLE_PLATFORMS)]
+ for name in names:
+ (stage / name).write_text(f"Notarized artifact fixture {name}")
+ return {name: release.fingerprint(stage / name) for name in names}
+
+ with patch.object(release, "repo_url", side_effect=lambda repo: repos[repo].as_uri()):
+ with patch.object(release, "github", side_effect=github), patch.object(release, "remote_file", side_effect=remote_file):
+ with patch.object(release, "run", side_effect=run), patch.object(release, "make_artifacts", side_effect=make_artifacts):
+ state = {"version": "2.2.1", "previous": "2.2.0", "base": base}
+ release.prepare(path, state, FORMULA)
+ with self.assertRaisesRegex(release.ReleaseError, "upload interrupted"):
+ release.finish(path, state)
+ self.assertTrue(draft["draft"])
+ with self.assertRaisesRegex(release.ReleaseError, "tap push interrupted"):
+ release.finish(path, json.loads((path / "release.json").read_text()))
+ self.assertFalse(draft["draft"])
+ release.finish(path, json.loads((path / "release.json").read_text()))
+ self.assertEqual(draft["body"], "Customized release notes")
+ self.assertEqual(uploads.count("xcodes.zip"), 1)
+ self.assertEqual(len(draft["assets"]), len(state["artifacts"]))
+ self.assertEqual(len(tap_pushes), 2)
+ self.assertEqual(release.remote_refs(release.CLI, "refs/tags/2.2.1")["refs/tags/2.2.1"], state["tag_sha"])
+ formula = remote_file(release.TAP, release.FORMULA, "main")
+ self.assertIn('tag: "2.2.1"', formula)
+ self.assertIn(state["artifacts"][release.bottle_name("2.2.1")]["digest"][7:], formula)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/notarize.sh b/notarize.sh
index fa438f0..21e1c96 100755
--- a/notarize.sh
+++ b/notarize.sh
@@ -1,19 +1,29 @@
#!/bin/sh
-#
-# notarize.sh
-#
-# E.g. ./notarize.sh "test@example.com" "@keychain:altool" MyOrg xcodes.zip
-#
-# Adapted from https://github.com/keybase/client/blob/46f5df0aa64ff19198ba7b044bbb7cd907c0be9f/packaging/desktop/package_darwin.sh
+set -eu
-file="$1"
-team_id="$2"
+if [ "$#" -ne 2 ] || [ ! -f "$1" ] || [ -z "$2" ]; then
+ echo "Usage: $0 " >&2
+ exit 1
+fi
-echo "Uploading to notarization service"
+archive=$1
+team_id=$2
+result=$(mktemp)
+trap 'rm -f "$result"' EXIT
-result=$(xcrun notarytool submit "$file" \
- --keychain-profile "AC_PASSWORD" \
- --team-id "$team_id" \
- --wait)
+echo "Submitting $archive to Apple for notarization"
+if ! xcrun notarytool submit "$archive" --keychain-profile AC_PASSWORD --team-id "$team_id" \
+ --wait --timeout 30m --output-format json > "$result"; then
+ cat "$result" >&2
+ exit 1
+fi
-echo $result
+status=$(plutil -extract status raw -o - "$result")
+submission_id=$(plutil -extract id raw -o - "$result")
+if [ "$status" != Accepted ]; then
+ echo "Notarization status: $status (submission $submission_id)" >&2
+ xcrun notarytool log "$submission_id" --keychain-profile AC_PASSWORD --team-id "$team_id" >&2 || true
+ exit 1
+fi
+
+echo "Notarization accepted (submission $submission_id)"