diff --git a/.github/workflows/tvos-ci.yml b/.github/workflows/tvos-ci.yml index 4b676e4b..c664215a 100644 --- a/.github/workflows/tvos-ci.yml +++ b/.github/workflows/tvos-ci.yml @@ -20,7 +20,16 @@ on: pull_request: paths: ['apple-tv/**', '.github/workflows/tvos-*.yml'] workflow_dispatch: + inputs: + xcode_version: + description: 'Xcode on the runner: exact (26.1) or newest of a major (26)' + default: '26' + type: string workflow_call: + inputs: + xcode_version: + default: '26' + type: string permissions: contents: read concurrency: @@ -31,14 +40,46 @@ jobs: name: tvOS Foundation, remote UI and signed Release runs-on: macos-26 timeout-minutes: 45 + env: + HOMEBREW_NO_AUTO_UPDATE: '1' + HOMEBREW_NO_INSTALL_CLEANUP: '1' + HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK: '1' + SOZO_BREW_TOOLS: xcodegen ffmpeg actionlint shellcheck steps: - uses: actions/checkout@v4 + # push/pull_request runs have no inputs; '26' must match the input defaults above. + - name: Select Xcode + env: + XCODE_VERSION: ${{ inputs.xcode_version || '26' }} + run: apple-tv/scripts/select-xcode.sh "${XCODE_VERSION}" + - name: Locate Homebrew download cache + id: brew + run: | + echo "cache=$(brew --cache)" >> "$GITHUB_OUTPUT" + echo "key=$(date +%Y-%m)-${SOZO_BREW_TOOLS// /-}" >> "$GITHUB_OUTPUT" + - name: Restore Homebrew downloads + uses: actions/cache@v4 + with: + path: ${{ steps.brew.outputs.cache }} + key: brew-${{ runner.os }}-${{ runner.arch }}-${{ steps.brew.outputs.key }} + restore-keys: brew-${{ runner.os }}-${{ runner.arch }}- - name: Install build and fixture tools - run: brew install xcodegen ffmpeg actionlint shellcheck + run: | + # shellcheck disable=SC2086 + brew install $SOZO_BREW_TOOLS - name: Validate workflow and shell scripts run: | actionlint .github/workflows/tvos-ci.yml .github/workflows/tvos-release.yml shellcheck apple-tv/scripts/*.sh + # SozoTV.xcodeproj is gitignored, so the committed outputs of project.yml + # are what can drift: Info.plist and anything else xcodegen writes. + - name: Check xcodegen output matches the committed files + working-directory: apple-tv + run: | + xcodegen generate + git diff --exit-code -- . || { echo "::error::Run xcodegen generate in apple-tv/ and commit the result. CI has xcodegen $(xcodegen --version), unpinned; the committed files were made with 2.46.0, so a version change alone can cause this diff."; exit 1; } + untracked="$(git ls-files --others --exclude-standard -- .)" + if [ -n "$untracked" ]; then echo "::error::xcodegen created untracked files: $untracked"; exit 1; fi - name: Run the same checks as local development run: apple-tv/scripts/ci.sh - name: Save logs, screenshots, results and simulator app diff --git a/.github/workflows/tvos-release.yml b/.github/workflows/tvos-release.yml index 2340466f..320f1bfe 100644 --- a/.github/workflows/tvos-release.yml +++ b/.github/workflows/tvos-release.yml @@ -1,4 +1,6 @@ name: Apple TV Release +run-name: >- + Apple TV ${{ inputs.version }} (build ${{ inputs.build_number || 'auto' }})${{ inputs.upload_testflight && ', TestFlight upload' || ', archive only' }} on: workflow_dispatch: inputs: @@ -8,34 +10,129 @@ on: default: '1.0.0' type: string build_number: - description: 'New App Store build number (1–9999, higher than previous upload)' - required: true + description: 'Build number override (1–9999). Empty = latest TestFlight build + 1' + required: false + default: '' type: string upload_testflight: description: 'Upload to App Store Connect for TestFlight processing' default: false type: boolean + wait_for_processing: + description: 'After upload, wait until App Store Connect finishes processing' + default: true + type: boolean + testflight_group: + description: 'Internal TestFlight group to add the processed build to (empty = none)' + required: false + default: '' + type: string + xcode_version: + description: 'Xcode on the runner: exact (26.1) or newest of a major (26)' + default: '26' + type: string permissions: contents: read concurrency: group: tvos-release cancel-in-progress: false jobs: + # Linux, and before the macOS gate, so missing secrets cost seconds, not macOS minutes. + preflight: + runs-on: ubuntu-latest + timeout-minutes: 5 + environment: apple-tv + steps: + - uses: actions/checkout@v4 + - name: Check secrets and inputs + env: + SOZO_TV_VERSION: ${{ inputs.version }} + SOZO_TV_BUILD_NUMBER: ${{ inputs.build_number }} + SOZO_TV_UPLOAD_TESTFLIGHT: ${{ inputs.upload_testflight }} + SOZO_TV_WAIT_PROCESSING: ${{ inputs.upload_testflight && inputs.wait_for_processing }} + SOZO_TV_TESTFLIGHT_GROUP: ${{ inputs.testflight_group }} + APPLE_TV_TEAM_ID: ${{ secrets.APPLE_TV_TEAM_ID }} + APPLE_TV_CERTIFICATE_P12_BASE64: ${{ secrets.APPLE_TV_CERTIFICATE_P12_BASE64 }} + APPLE_TV_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_TV_CERTIFICATE_PASSWORD }} + APPLE_TV_PROFILE_BASE64: ${{ secrets.APPLE_TV_PROFILE_BASE64 }} + ASC_API_KEY_P8_BASE64: ${{ secrets.ASC_API_KEY_P8_BASE64 }} + ASC_API_KEY_ID: ${{ secrets.ASC_API_KEY_ID }} + ASC_API_ISSUER_ID: ${{ secrets.ASC_API_ISSUER_ID }} + TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} + TELEGRAM_CHAT_IDS: ${{ secrets.TELEGRAM_CHAT_IDS }} + run: apple-tv/scripts/preflight.sh + - name: Refuse a build number that is already tagged + if: inputs.build_number != '' && inputs.build_number != 'auto' + env: + TAG: tvos-${{ inputs.version }}-${{ inputs.build_number }} + run: | + if git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null; then + echo "::error title=Tag exists::${TAG} was already uploaded. Use a higher build number or leave it empty." + exit 1 + fi + - name: Refuse a build number App Store Connect already passed + if: inputs.build_number != '' && inputs.build_number != 'auto' + env: + ASC_API_KEY_P8_BASE64: ${{ secrets.ASC_API_KEY_P8_BASE64 }} + ASC_API_KEY_ID: ${{ secrets.ASC_API_KEY_ID }} + ASC_API_ISSUER_ID: ${{ secrets.ASC_API_ISSUER_ID }} + VERSION: ${{ inputs.version }} + BUILD: ${{ inputs.build_number }} + run: | + if [ -z "${ASC_API_KEY_P8_BASE64}" ] || [ -z "${ASC_API_KEY_ID}" ] || [ -z "${ASC_API_ISSUER_ID}" ]; then + echo 'No App Store Connect key; skipping.'; exit 0 + fi + umask 077 + export ASC_API_KEY_PATH="${RUNNER_TEMP}/AuthKey.p8" + trap 'rm -f "${ASC_API_KEY_PATH}"' EXIT + printf '%s' "${ASC_API_KEY_P8_BASE64}" | tr -d '[:space:]' | base64 -d > "${ASC_API_KEY_PATH}" + python3 apple-tv/scripts/asc.py check-build "${VERSION}" "${BUILD}" + verify: + needs: preflight uses: ./.github/workflows/tvos-ci.yml + with: + xcode_version: ${{ inputs.xcode_version }} + distribute: needs: verify runs-on: macos-26 timeout-minutes: 40 environment: apple-tv + permissions: + contents: write + outputs: + build_number: ${{ steps.release.outputs.build_number }} + uploaded: ${{ steps.release.outputs.uploaded }} + env: + HOMEBREW_NO_AUTO_UPDATE: '1' + HOMEBREW_NO_INSTALL_CLEANUP: '1' + HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK: '1' steps: - uses: actions/checkout@v4 + - name: Select Xcode + env: + XCODE_VERSION: ${{ inputs.xcode_version }} + run: apple-tv/scripts/select-xcode.sh "${XCODE_VERSION}" + - name: Locate Homebrew download cache + id: brew + run: | + echo "cache=$(brew --cache)" >> "$GITHUB_OUTPUT" + echo "key=$(date +%Y-%m)-xcodegen" >> "$GITHUB_OUTPUT" + - name: Restore Homebrew downloads + uses: actions/cache@v4 + with: + path: ${{ steps.brew.outputs.cache }} + key: brew-${{ runner.os }}-${{ runner.arch }}-${{ steps.brew.outputs.key }} + restore-keys: brew-${{ runner.os }}-${{ runner.arch }}- - name: Install project generator run: brew install xcodegen - name: Archive and export; upload only when requested + id: release env: SOZO_TV_VERSION: ${{ inputs.version }} SOZO_TV_BUILD_NUMBER: ${{ inputs.build_number }} + SOZO_TV_BUILD_NUMBER_FALLBACK: ${{ github.run_number }} SOZO_TV_UPLOAD_TESTFLIGHT: ${{ inputs.upload_testflight }} APPLE_TV_TEAM_ID: ${{ secrets.APPLE_TV_TEAM_ID }} APPLE_TV_CERTIFICATE_P12_BASE64: ${{ secrets.APPLE_TV_CERTIFICATE_P12_BASE64 }} @@ -45,11 +142,116 @@ jobs: ASC_API_KEY_ID: ${{ secrets.ASC_API_KEY_ID }} ASC_API_ISSUER_ID: ${{ secrets.ASC_API_ISSUER_ID }} run: apple-tv/scripts/release.sh + # The build number is spent once App Store Connect has it, so tag even if a later step fails. + - name: Tag the uploaded build + if: always() && steps.release.outputs.uploaded == 'true' + env: + TAG: tvos-${{ inputs.version }}-${{ steps.release.outputs.build_number }} + run: | + git tag "${TAG}" "${GITHUB_SHA}" + if git push origin "refs/tags/${TAG}"; then + echo "::notice title=Tagged::${TAG}" + else + echo "::warning title=Tag not pushed::${TAG} could not be pushed; the upload itself succeeded." + fi - name: Save distribution artifacts and diagnostics if: always() uses: actions/upload-artifact@v4 with: - name: tvos-release-${{ inputs.version }}-${{ inputs.build_number }}-${{ github.run_attempt }} + name: tvos-release-${{ inputs.version }}-${{ steps.release.outputs.build_number || 'unresolved' }}-${{ github.run_attempt }} path: apple-tv/build/release/ if-no-files-found: warn retention-days: 14 + + # Polling App Store Connect is plain HTTPS, so it waits on Linux at a tenth of the macOS rate. + testflight: + needs: distribute + if: >- + always() && needs.distribute.outputs.uploaded == 'true' && + (inputs.wait_for_processing || inputs.testflight_group != '') + runs-on: ubuntu-latest + timeout-minutes: 75 + environment: apple-tv + outputs: + processed: ${{ steps.wait.outputs.processed }} + grouped: ${{ steps.group.outputs.grouped }} + steps: + - uses: actions/checkout@v4 + - name: Wait for App Store Connect processing + id: wait + env: + ASC_API_KEY_P8_BASE64: ${{ secrets.ASC_API_KEY_P8_BASE64 }} + ASC_API_KEY_ID: ${{ secrets.ASC_API_KEY_ID }} + ASC_API_ISSUER_ID: ${{ secrets.ASC_API_ISSUER_ID }} + VERSION: ${{ inputs.version }} + BUILD: ${{ needs.distribute.outputs.build_number }} + run: | + umask 077 + export ASC_API_KEY_PATH="${RUNNER_TEMP}/AuthKey.p8" + printf '%s' "${ASC_API_KEY_P8_BASE64}" | tr -d '[:space:]' | base64 -d > "${ASC_API_KEY_PATH}" + build_id="$(python3 apple-tv/scripts/asc.py wait "${VERSION}" "${BUILD}" 60)" + echo "build_id=${build_id}" >> "$GITHUB_OUTPUT" + echo 'processed=true' >> "$GITHUB_OUTPUT" + - name: Add to internal TestFlight group + id: group + if: inputs.testflight_group != '' + env: + ASC_API_KEY_ID: ${{ secrets.ASC_API_KEY_ID }} + ASC_API_ISSUER_ID: ${{ secrets.ASC_API_ISSUER_ID }} + BUILD_ID: ${{ steps.wait.outputs.build_id }} + GROUP: ${{ inputs.testflight_group }} + run: | + ASC_API_KEY_PATH="${RUNNER_TEMP}/AuthKey.p8" python3 apple-tv/scripts/asc.py add-to-group "${BUILD_ID}" "${GROUP}" + echo 'grouped=true' >> "$GITHUB_OUTPUT" + - name: Remove the API key + if: always() + run: rm -f "${RUNNER_TEMP}/AuthKey.p8" + + notify: + needs: [preflight, verify, distribute, testflight] + if: always() && !cancelled() + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Send to Telegram + env: + TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} + TELEGRAM_CHAT_IDS: ${{ secrets.TELEGRAM_CHAT_IDS }} + VERSION: ${{ inputs.version }} + BUILD: ${{ needs.distribute.outputs.build_number }} + UPLOAD_REQUESTED: ${{ inputs.upload_testflight }} + UPLOADED: ${{ needs.distribute.outputs.uploaded }} + PROCESSED: ${{ needs.testflight.outputs.processed }} + GROUPED: ${{ needs.testflight.outputs.grouped }} + GROUP: ${{ inputs.testflight_group }} + RESULTS: >- + preflight=${{ needs.preflight.result }} verify=${{ needs.verify.result }} + distribute=${{ needs.distribute.result }} testflight=${{ needs.testflight.result }} + run: | + set -uo pipefail + if [ -z "${TELEGRAM_BOT_TOKEN}" ] || [ -z "${TELEGRAM_CHAT_IDS}" ]; then + echo "::warning title=Telegram skipped::TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_IDS not set." + exit 0 + fi + RUN_URL="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" + if [ "${UPLOADED}" = true ]; then + MSG="Sozo Apple TV ${VERSION} (${BUILD}) uploaded to TestFlight." + if [ "${PROCESSED}" = true ]; then MSG="${MSG} Processing finished."; fi + if [ "${GROUPED}" = true ]; then MSG="${MSG} Added to group \"${GROUP}\"."; fi + if [[ "${RESULTS}" == *failure* ]]; then MSG="${MSG} A later step failed: ${RESULTS}."; fi + elif [ "${UPLOAD_REQUESTED}" = true ] || [[ "${RESULTS}" == *failure* ]]; then + MSG="Sozo Apple TV ${VERSION} release FAILED, nothing uploaded. ${RESULTS}." + else + MSG="Sozo Apple TV ${VERSION} (${BUILD:-?}) archived and signed; upload was not requested." + fi + MSG="$(printf '%s\n\n%s' "${MSG}" "${RUN_URL}")" + IFS=',' read -ra CHATS <<< "${TELEGRAM_CHAT_IDS}" + for raw in "${CHATS[@]}"; do + chat="$(echo "${raw}" | xargs)" + [ -z "${chat}" ] && continue + curl -sS --fail-with-body -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \ + --data-urlencode "chat_id=${chat}" \ + --data-urlencode "text=${MSG}" \ + --data "disable_web_page_preview=true" -o /dev/null \ + || echo "::warning::Telegram sendMessage to one chat failed." + done diff --git a/apple-tv/README.md b/apple-tv/README.md index 84f55595..c13c49b9 100644 --- a/apple-tv/README.md +++ b/apple-tv/README.md @@ -80,7 +80,7 @@ placeholder geometry. Native glass containers group nearby controls; content pan readable solid surfaces. Siri Remote tests cover navigation between the header/grid, search pagination, profile management, PINs, notifications, closed support conversations and settings isolation. Avatars load their bundled PNGs as original images. App Icon and Top Shelf use -native layered/static branded assets. +native layered/static branded assets; the wide Top Shelf is the standard one padded with its own background. For the actual AVKit integration checks, install FFmpeg and run: @@ -149,33 +149,52 @@ SOZO_TV_OUTPUT_DIR=/tmp/sozo-tvos-ci-new-run apple-tv/scripts/ci.sh Use a new output directory for each run. A simulator ZIP is for macOS Simulator, not an installable package for physical Apple TV. -`.github/workflows/tvos-release.yml` is manual. It first passes the complete CI gate, -then signs a device archive and exports an App Store IPA. `upload_testflight` defaults -to false; enabling it uploads the validated archive for App Store Connect processing. -It never submits for App Review or automatically distributes to external testers. -Marketing version and build number are supplied explicitly; use a higher build number -than the previous upload. It does not commit version changes or create Android tags. - -Create the `apple-tv` GitHub environment and set these secrets: - -| Secret | Contents | +`.github/workflows/tvos-release.yml` is manual (Actions, Apple TV Release, Run workflow). +A Linux preflight job first lists every missing secret by name, then the complete CI gate +runs, then the device archive is signed and exported as an App Store IPA. `upload_testflight` +defaults to false, so you choose which build ships. Leave `build_number` empty to use the +higher of the latest App Store Connect build and the latest `tvos-*` tag, + 1. If that +query fails, an upload stops; an archive-only run falls back to the run number. A manual +number is refused in preflight if it is already tagged or not above the latest App Store +Connect build of that version. Right after a successful upload the commit is tagged +`tvos--` (never `v*`, which belongs to Android). The tag only means the +number is spent: it is pushed before processing, so it does not prove the build reached +TestFlight. Waiting for processing and +adding to an internal group run on Linux; Telegram reports the outcome when +`TELEGRAM_BOT_TOKEN`/`TELEGRAM_CHAT_IDS` are set. It never submits for App Review or +distributes to external testers. `xcode_version` pins Xcode (`26` = newest 26.x on the +runner, `26.1` = exactly that one); CI also fails if `xcodegen generate` changes committed files. + +### First TestFlight upload + +Create the `apple-tv` environment (Settings, Environments) and add these as its secrets: + +| Step | Secret | | --- | --- | -| `APPLE_TV_TEAM_ID` | Your Apple Developer team ID | -| `APPLE_TV_CERTIFICATE_P12_BASE64` | Base64 Apple Distribution certificate **with its private key** | -| `APPLE_TV_CERTIFICATE_PASSWORD` | Password protecting that P12 | -| `APPLE_TV_PROFILE_BASE64` | Base64 **tvOS App Store** provisioning profile for `com.saikou.sozotv` | -| `ASC_API_KEY_P8_BASE64` | Base64 App Store Connect team API private key; required for upload | -| `ASC_API_KEY_ID` | App Store Connect key ID; required for upload | -| `ASC_API_ISSUER_ID` | App Store Connect issuer ID; required for upload | - -The app must already exist in App Store Connect under that bundle ID and team. The -profile must authorize the supplied distribution certificate. The pipeline rejects a -wrong team, bundle, platform, expired profile and development/ad-hoc/enterprise profiles. -Signing runs in a temporary keychain, restores the original search list and removes its -private material/profile on exit. Do not put these secrets in the repository. +| Team ID from developer.apple.com, Membership | `APPLE_TV_TEAM_ID` | +| Apple Distribution certificate exported from Keychain as .p12 **with its private key**: `base64 -i dist.p12 \| pbcopy` | `APPLE_TV_CERTIFICATE_P12_BASE64` | +| Password chosen when exporting that .p12 | `APPLE_TV_CERTIFICATE_PASSWORD` | +| Identifier `com.saikou.sozotv`, then a **tvOS App Store** provisioning profile for it using that certificate: `base64 -i SozoTV.mobileprovision \| pbcopy` | `APPLE_TV_PROFILE_BASE64` | +| App Store Connect, Users and Access, Integrations: team API key with App Manager role; download the .p8 once: `base64 -i AuthKey_XXXX.p8 \| pbcopy` | `ASC_API_KEY_P8_BASE64` | +| Key ID shown next to that key | `ASC_API_KEY_ID` | +| Issuer ID shown above the key list | `ASC_API_ISSUER_ID` | + +Then, in App Store Connect: + +1. Create the app record (My Apps, +, New App, platform tvOS, bundle ID `com.saikou.sozotv`). +2. TestFlight, Internal Testing: create a group (e.g. `Team`) and add testers. +3. Run the workflow with `upload_testflight` on and `testflight_group` set to that group's exact name. + +Telegram uses the existing repository secrets `TELEGRAM_BOT_TOKEN` and `TELEGRAM_CHAT_IDS`; +without them the run only warns. The profile must authorize the supplied distribution +certificate. The pipeline rejects a wrong team, bundle, platform, expired profile and +development/ad-hoc/enterprise profiles. Signing runs in a temporary keychain, restores the +original search list and removes its private material/profile on exit. Do not put these +secrets in the repository. On a dedicated local Mac, set the same environment variables plus `SOZO_TV_VERSION`, -`SOZO_TV_BUILD_NUMBER` and optionally `SOZO_TV_UPLOAD_TESTFLIGHT=true`, then run +optionally `SOZO_TV_BUILD_NUMBER` (default: App Store Connect + 1), `SOZO_TV_UPLOAD_TESTFLIGHT=true`, +`SOZO_TV_WAIT_PROCESSING=true` and `SOZO_TV_TESTFLIGHT_GROUP`, then run `apple-tv/scripts/release.sh` **after** `apple-tv/scripts/ci.sh` passes. This is the fallback when GitHub Actions is unavailable. Signed device archive/export/upload needs those credentials; a successful simulator build does not prove distribution signing. diff --git a/apple-tv/Resources/Assets.xcassets/AppIcon.brandassets/Contents.json b/apple-tv/Resources/Assets.xcassets/AppIcon.brandassets/Contents.json index e44d0a6d..d4cfeb2c 100644 --- a/apple-tv/Resources/Assets.xcassets/AppIcon.brandassets/Contents.json +++ b/apple-tv/Resources/Assets.xcassets/AppIcon.brandassets/Contents.json @@ -17,6 +17,12 @@ "idiom" : "tv", "role" : "top-shelf-image", "size" : "1920x720" + }, + { + "filename" : "TopShelfWide.imageset", + "idiom" : "tv", + "role" : "top-shelf-image-wide", + "size" : "2320x720" } ], "info" : { diff --git a/apple-tv/Resources/Assets.xcassets/AppIcon.brandassets/TopShelfWide.imageset/Contents.json b/apple-tv/Resources/Assets.xcassets/AppIcon.brandassets/TopShelfWide.imageset/Contents.json new file mode 100644 index 00000000..bd0ed423 --- /dev/null +++ b/apple-tv/Resources/Assets.xcassets/AppIcon.brandassets/TopShelfWide.imageset/Contents.json @@ -0,0 +1,18 @@ +{ + "images" : [ + { + "filename" : "ShelfWide.png", + "idiom" : "tv", + "scale" : "1x" + }, + { + "filename" : "ShelfWide@2x.png", + "idiom" : "tv", + "scale" : "2x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} \ No newline at end of file diff --git a/apple-tv/Resources/Assets.xcassets/AppIcon.brandassets/TopShelfWide.imageset/ShelfWide.png b/apple-tv/Resources/Assets.xcassets/AppIcon.brandassets/TopShelfWide.imageset/ShelfWide.png new file mode 100644 index 00000000..cdac5c8c Binary files /dev/null and b/apple-tv/Resources/Assets.xcassets/AppIcon.brandassets/TopShelfWide.imageset/ShelfWide.png differ diff --git a/apple-tv/Resources/Assets.xcassets/AppIcon.brandassets/TopShelfWide.imageset/ShelfWide@2x.png b/apple-tv/Resources/Assets.xcassets/AppIcon.brandassets/TopShelfWide.imageset/ShelfWide@2x.png new file mode 100644 index 00000000..321cd4cb Binary files /dev/null and b/apple-tv/Resources/Assets.xcassets/AppIcon.brandassets/TopShelfWide.imageset/ShelfWide@2x.png differ diff --git a/apple-tv/Tests/ReleasePipeline/check.py b/apple-tv/Tests/ReleasePipeline/check.py index b286c8bf..e71be740 100644 --- a/apple-tv/Tests/ReleasePipeline/check.py +++ b/apple-tv/Tests/ReleasePipeline/check.py @@ -30,3 +30,101 @@ except AssertionError: continue raise AssertionError(f'Accepted {label} profile') print('Release profile gates PASS (valid + 7 rejected variants)') + +import base64, json, os, subprocess, tempfile +spec = importlib.util.spec_from_file_location('asc', script.with_name('asc.py')) +asc = importlib.util.module_from_spec(spec) +spec.loader.exec_module(asc) +with tempfile.TemporaryDirectory() as tmp: + key, pub = pathlib.Path(tmp, 'AuthKey.p8'), pathlib.Path(tmp, 'pub.pem') + subprocess.run(['openssl', 'genpkey', '-algorithm', 'EC', '-pkeyopt', 'ec_paramgen_curve:P-256', '-out', key], check=True) + subprocess.run(['openssl', 'pkey', '-in', key, '-pubout', '-out', pub], check=True) + os.environ.update(ASC_API_KEY_ID='TESTKEY123', ASC_API_ISSUER_ID='issuer', ASC_API_KEY_PATH=str(key)) + for _ in range(20): + head, body, sig = asc.token().split('.') + raw = base64.urlsafe_b64decode(sig + '=' * (-len(sig) % 4)) + assert len(raw) == 64, 'ES256 signature must be 64 bytes' + def integer(b): + b = b.lstrip(b'\0') + b = b'\0' + b if b[0] & 0x80 else b + return bytes([2, len(b)]) + b + seq = integer(raw[:32]) + integer(raw[32:]) + pathlib.Path(tmp, 'sig.der').write_bytes(bytes([0x30, len(seq)]) + seq) + subprocess.run(['openssl', 'dgst', '-sha256', '-verify', pub, '-signature', pathlib.Path(tmp, 'sig.der')], + input=f'{head}.{body}'.encode(), check=True, capture_output=True) + assert json.loads(base64.urlsafe_b64decode(body + '==='))['aud'] == 'appstoreconnect-v1' +print('App Store Connect JWT PASS (20 ES256 signatures verified)') + +import contextlib, io +def fake(responses): + calls = [] + def call(path, params=None, body=None): + calls.append((path, params, body)) + return responses(path, params or {}, body) + return call, calls +def builds(*versions): + return {'data': [{'id': f'b{v}', 'attributes': {'version': v}} for v in versions]} +def expect_exit(fn, *args): + try: + with contextlib.redirect_stderr(io.StringIO()): fn(*args) + except SystemExit as e: + assert e.code not in (None, 0); return str(e.code) + raise AssertionError(f'{fn.__name__}{args} did not fail') +def stdout_of(fn, *args): + out = io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): fn(*args) + return out.getvalue().strip() +app = {'data': [{'id': 'app1', 'attributes': {'bundleId': asc.BUNDLE_ID}}]} +def with_builds(data): + return lambda path, params, body: app if path == '/apps' else data +asc.tagged_builds = lambda: [] +asc.call, _ = fake(with_builds(builds('3', '12', '1.2', 'abc'))) +assert stdout_of(asc.next_build) == '13' +asc.call, _ = fake(with_builds(builds())) +assert stdout_of(asc.next_build) == '1' +asc.tagged_builds = lambda: [20] +asc.call, _ = fake(with_builds(builds('12'))) +assert stdout_of(asc.next_build) == '21', 'a fresh tag must beat an unlisted build' +asc.tagged_builds = lambda: [] +asc.call, calls = fake(with_builds(builds('5'))) +expect_exit(asc.check_build, '1.0.0', '5') +stdout_of(asc.check_build, '1.0.0', '6') +assert calls[-1][1]['filter[preReleaseVersion.version]'] == '1.0.0' + +asc.time.sleep = lambda s: None +def states(*seq): + it = iter(seq) + def respond(path, params, body): + if path == '/apps': return app + state = next(it) + return {'data': []} if state is None else {'data': [{'id': 'B1', 'attributes': {'processingState': state}}]} + return respond +asc.call, _ = fake(states(None, 'PROCESSING', 'VALID')) +assert stdout_of(asc.wait, '1.0.0', '7') == 'B1' +for bad in ('FAILED', 'INVALID'): + asc.call, _ = fake(states('PROCESSING', bad)) + assert bad in expect_exit(asc.wait, '1.0.0', '7') +asc.call, _ = fake(states(*['PROCESSING'] * 5)) +real_time, clock = asc.time.time, iter([0, 0, 120]) +asc.time.time = lambda: next(clock) +assert 'after 1 minutes' in expect_exit(asc.wait, '1.0.0', '7', 1) +asc.time.time = real_time + +def groups(internal): + def respond(path, params, body): + if path == '/apps': return app + if path == '/betaGroups': + return {'data': [{'id': 'G1', 'attributes': {'name': 'Team', 'isInternalGroup': internal}}, + {'id': 'G2', 'attributes': {'name': 'Team 2', 'isInternalGroup': True}}]} + return {} + return respond +asc.call, calls = fake(groups(False)) +assert 'external' in expect_exit(asc.add_to_group, 'B1', 'Team') +assert not any(c[2] for c in calls), 'nothing may be posted to an external group' +asc.call, calls = fake(groups(True)) +stdout_of(asc.add_to_group, 'B1', 'Team') +assert calls[-1][0] == '/betaGroups/G1/relationships/builds' +assert calls[-1][2] == {'data': [{'type': 'builds', 'id': 'B1'}]} +asc.call, _ = fake(groups(True)) +expect_exit(asc.add_to_group, 'B1', 'Nobody') +print('App Store Connect client PASS (next-build, check-build, wait states, group guard)') diff --git a/apple-tv/scripts/asc.py b/apple-tv/scripts/asc.py new file mode 100755 index 00000000..1d32e178 --- /dev/null +++ b/apple-tv/scripts/asc.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""Minimal App Store Connect API client for the tvOS release (stdlib + openssl only). + + asc.py next-build latest uploaded tvOS build number (or tvos-* tag) + 1 + asc.py check-build VERSION BUILD fail if BUILD is not above every build of VERSION + asc.py wait VERSION BUILD [MINUTES] block until the build is VALID; prints its id + asc.py add-to-group BUILD_ID GROUP add a processed build to an internal TestFlight group + +Needs ASC_API_KEY_ID, ASC_API_ISSUER_ID and ASC_API_KEY_PATH (the decoded .p8). +""" +import base64 +import json +import os +import re +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +API = 'https://api.appstoreconnect.apple.com/v1' +BUNDLE_ID = 'com.saikou.sozotv' + + +def b64url(data): + return base64.urlsafe_b64encode(data).rstrip(b'=') + + +def der_to_raw(der): + # openssl emits an ASN.1 SEQUENCE of two INTEGERs; JWS ES256 wants r||s, 32 bytes each. + assert der[0] == 0x30, 'Unexpected signature encoding' + i = 3 if der[1] & 0x80 else 2 + parts = [] + for _ in range(2): + assert der[i] == 0x02, 'Unexpected signature encoding' + n = der[i + 1] + parts.append(der[i + 2:i + 2 + n].lstrip(b'\0').rjust(32, b'\0')) + i += 2 + n + return b''.join(parts) + + +def token(): + header = {'alg': 'ES256', 'kid': os.environ['ASC_API_KEY_ID'], 'typ': 'JWT'} + now = int(time.time()) + claims = {'iss': os.environ['ASC_API_ISSUER_ID'], 'iat': now, 'exp': now + 1140, 'aud': 'appstoreconnect-v1'} + signing_input = b64url(json.dumps(header).encode()) + b'.' + b64url(json.dumps(claims).encode()) + der = subprocess.run(['openssl', 'dgst', '-sha256', '-sign', os.environ['ASC_API_KEY_PATH']], + input=signing_input, capture_output=True, check=True).stdout + return (signing_input + b'.' + b64url(der_to_raw(der))).decode() + + +def call(path, params=None, body=None): + url = f'{API}{path}' + if params: + url += '?' + urllib.parse.urlencode(params) + data = json.dumps(body).encode() if body is not None else None + request = urllib.request.Request(url, data=data, method='POST' if data else 'GET', + headers={'Authorization': f'Bearer {token()}', 'Content-Type': 'application/json'}) + try: + with urllib.request.urlopen(request, timeout=60) as response: + raw = response.read() + except urllib.error.HTTPError as error: + detail = error.read().decode(errors='replace')[:600] + sys.exit(f'App Store Connect {error.code} on {path}: {detail}') + return json.loads(raw) if raw else {} + + +def app_id(): + apps = call('/apps', {'filter[bundleId]': BUNDLE_ID, 'fields[apps]': 'bundleId'})['data'] + apps = [a for a in apps if a['attributes']['bundleId'] == BUNDLE_ID] + if not apps: + sys.exit(f'No App Store Connect app record for {BUNDLE_ID}; create it first.') + return apps[0]['id'] + + +def tagged_builds(): + # A build uploaded seconds ago may not be listed by App Store Connect yet; its tag is. + try: + out = subprocess.run(['git', 'ls-remote', '--tags', 'origin', 'refs/tags/tvos-*'], + capture_output=True, text=True, timeout=60).stdout + except (OSError, subprocess.SubprocessError): + return [] + return [int(m.group(1)) for m in re.finditer(r'refs/tags/tvos-[^\s]*-(\d+)$', out, re.M)] + + +def build_numbers(**filters): + params = {'filter[app]': app_id(), 'filter[preReleaseVersion.platform]': 'TV_OS', + 'sort': '-uploadedDate', 'limit': 200, 'fields[builds]': 'version'} + params.update(filters) + builds = call('/builds', params)['data'] + return [int(b['attributes']['version']) for b in builds if b['attributes']['version'].isdigit()] + + +def next_build(): + print(max(build_numbers() + tagged_builds(), default=0) + 1) + + +def check_build(version, build): + latest = max(build_numbers(**{'filter[preReleaseVersion.version]': version}), default=0) + if int(build) <= latest: + sys.exit(f'Build {build} is not above {latest}, the latest App Store Connect build of {version}') + print(f'Build {build} is above {latest}, the latest build of {version}', file=sys.stderr) + + +def wait(version, build, minutes=45): + deadline = time.time() + minutes * 60 + app = app_id() + while True: + found = call('/builds', {'filter[app]': app, 'filter[version]': build, + 'filter[preReleaseVersion.version]': version, + 'filter[preReleaseVersion.platform]': 'TV_OS', + 'fields[builds]': 'processingState'})['data'] + state = found[0]['attributes']['processingState'] if found else 'NOT_LISTED_YET' + print(f'{version} ({build}): {state}', file=sys.stderr) + if state == 'VALID': + print(found[0]['id']) + return + if state in ('FAILED', 'INVALID'): + sys.exit(f'Build {version} ({build}) finished processing as {state}') + if time.time() > deadline: + sys.exit(f'Build {version} ({build}) still {state} after {minutes} minutes') + time.sleep(30) + + +def add_to_group(build_id, name): + groups = call('/betaGroups', {'filter[app]': app_id(), 'filter[name]': name, + 'fields[betaGroups]': 'name,isInternalGroup'})['data'] + groups = [g for g in groups if g['attributes']['name'] == name] + if not groups: + sys.exit(f'No TestFlight group named "{name}"') + if not groups[0]['attributes'].get('isInternalGroup'): + sys.exit(f'"{name}" is an external group; external testing needs Beta App Review and stays manual') + call(f'/betaGroups/{groups[0]["id"]}/relationships/builds', body={'data': [{'type': 'builds', 'id': build_id}]}) + print(f'Added build {build_id} to "{name}"', file=sys.stderr) + + +if __name__ == '__main__': + command, args = (sys.argv[1], sys.argv[2:]) if len(sys.argv) > 1 else ('', []) + if command == 'next-build' and not args: + next_build() + elif command == 'check-build' and len(args) == 2: + check_build(*args) + elif command == 'wait' and len(args) in (2, 3): + wait(args[0], args[1], *(int(a) for a in args[2:])) + elif command == 'add-to-group' and len(args) == 2: + add_to_group(*args) + else: + sys.exit(__doc__) diff --git a/apple-tv/scripts/preflight.sh b/apple-tv/scripts/preflight.sh new file mode 100755 index 00000000..20160679 --- /dev/null +++ b/apple-tv/scripts/preflight.sh @@ -0,0 +1,67 @@ +#!/bin/bash +# Report which release secrets and inputs are missing, by name only, before any +# macOS minutes are spent. Values are never printed. +set -uo pipefail +sozo_upload="${SOZO_TV_UPLOAD_TESTFLIGHT:-false}" +sozo_group="${SOZO_TV_TESTFLIGHT_GROUP:-}" +sozo_build="${SOZO_TV_BUILD_NUMBER:-}" +sozo_failed=0 +sozo_lines=() +row() { sozo_lines+=("| $1 | \`$2\` | $3 |"); } +need() { + if [ -n "${!1:-}" ]; then row ok "$1" "$2"; else row MISSING "$1" "$2"; sozo_failed=1; fi +} +want() { + if [ -n "${!1:-}" ]; then row ok "$1" "$2"; else row optional "$1" "$2"; fi +} + +need APPLE_TV_TEAM_ID 'Apple Developer Team ID (10 characters)' +need APPLE_TV_CERTIFICATE_P12_BASE64 'Apple Distribution certificate + private key, .p12, base64' +need APPLE_TV_CERTIFICATE_PASSWORD 'Password of that .p12' +need APPLE_TV_PROFILE_BASE64 'tvOS App Store provisioning profile for com.saikou.sozotv, base64' +for name in ASC_API_KEY_P8_BASE64 ASC_API_KEY_ID ASC_API_ISSUER_ID; do + case "$name" in + ASC_API_KEY_P8_BASE64) sozo_what='App Store Connect API key .p8, base64' ;; + ASC_API_KEY_ID) sozo_what='App Store Connect API Key ID' ;; + *) sozo_what='App Store Connect Issuer ID' ;; + esac + if [ "$sozo_upload" = true ]; then + need "$name" "$sozo_what (upload)" + else + want "$name" "$sozo_what (automatic build number; upload)" + fi +done +want TELEGRAM_BOT_TOKEN 'Telegram notification (repository secret)' +want TELEGRAM_CHAT_IDS 'Comma-separated Telegram chat ids (repository secret)' + +if [ -n "${APPLE_TV_TEAM_ID:-}" ] && ! printf '%s' "$APPLE_TV_TEAM_ID" | grep -Eq '^[A-Z0-9]{10}$'; then + row INVALID APPLE_TV_TEAM_ID 'Secret: must be 10 uppercase letters or digits'; sozo_failed=1 +fi +if ! printf '%s' "${SOZO_TV_VERSION:-}" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then + row INVALID version 'Input: three-part marketing version, e.g. 1.0.0'; sozo_failed=1 +fi +if [ -n "$sozo_build" ] && [ "$sozo_build" != auto ] && ! printf '%s' "$sozo_build" | grep -Eq '^[1-9][0-9]{0,3}$'; then + row INVALID build_number 'Input: empty/auto, or 1–9999'; sozo_failed=1 +fi +if [ -n "$sozo_group" ] && [ "$sozo_upload" != true ]; then + row INVALID upload_testflight 'Input: a TestFlight group needs upload_testflight'; sozo_failed=1 +fi +if [ "${SOZO_TV_WAIT_PROCESSING:-false}" = true ] && [ "$sozo_upload" != true ]; then + row INVALID upload_testflight 'Input: waiting for processing needs upload_testflight'; sozo_failed=1 +fi + +{ + echo '### Apple TV release preflight' + echo + echo '| State | Name | What it is |' + echo '| --- | --- | --- |' + printf '%s\n' "${sozo_lines[@]}" + echo + if [ "$sozo_failed" = 1 ]; then + echo 'Add every MISSING secret to the apple-tv environment (Settings, Environments), fix any INVALID input and dispatch again. See apple-tv/README.md, "First TestFlight upload".' + fi +} | tee -a "${GITHUB_STEP_SUMMARY:-/dev/null}" +if [ "$sozo_failed" = 1 ]; then + echo '::error title=Apple TV release preflight::Required secrets or inputs are missing; see the checklist above.' +fi +exit "$sozo_failed" diff --git a/apple-tv/scripts/release.sh b/apple-tv/scripts/release.sh index 117cd156..20bf45a5 100755 --- a/apple-tv/scripts/release.sh +++ b/apple-tv/scripts/release.sh @@ -1,5 +1,8 @@ #!/bin/bash # Manual App Store distribution signing. Upload is off unless explicitly enabled. +# SOZO_TV_BUILD_NUMBER empty or "auto": latest App Store Connect build + 1, else +# SOZO_TV_BUILD_NUMBER_FALLBACK (CI passes github.run_number) for archive-only runs. +# An upload never falls back: a guessed number can collide and fail only after archiving. set -euo pipefail umask 077 cd "$(dirname "$0")/.." @@ -8,21 +11,34 @@ cd "$(dirname "$0")/.." : "${APPLE_TV_CERTIFICATE_PASSWORD:?Set APPLE_TV_CERTIFICATE_PASSWORD}" : "${APPLE_TV_PROFILE_BASE64:?Set APPLE_TV_PROFILE_BASE64}" : "${SOZO_TV_VERSION:?Set SOZO_TV_VERSION}" -: "${SOZO_TV_BUILD_NUMBER:?Set SOZO_TV_BUILD_NUMBER}" +: "${SOZO_TV_BUILD_NUMBER:=auto}" +export SOZO_TV_BUILD_NUMBER sozo_upload="${SOZO_TV_UPLOAD_TESTFLIGHT:-false}" -case "$sozo_upload" in true|false) ;; *) echo 'Upload must be true or false' >&2; exit 1 ;; esac +sozo_wait="${SOZO_TV_WAIT_PROCESSING:-false}" +sozo_group="${SOZO_TV_TESTFLIGHT_GROUP:-}" +for flag in "$sozo_upload" "$sozo_wait"; do + case "$flag" in true|false) ;; *) echo 'Upload and wait flags must be true or false' >&2; exit 1 ;; esac +done +if [ -n "$sozo_group" ]; then sozo_wait=true; fi +if [ "$sozo_wait" = true ] && [ "$sozo_upload" != true ]; then + echo 'Waiting for processing or adding to a group needs SOZO_TV_UPLOAD_TESTFLIGHT=true' >&2; exit 1 +fi +sozo_has_asc=false +if [ -n "${ASC_API_KEY_P8_BASE64:-}" ] && [ -n "${ASC_API_KEY_ID:-}" ] && [ -n "${ASC_API_ISSUER_ID:-}" ]; then + sozo_has_asc=true +fi python3 - <<'PY' import os, re assert re.fullmatch(r'[A-Z0-9]{10}', os.environ['APPLE_TV_TEAM_ID']), 'Invalid team ID' assert re.fullmatch(r'\d+\.\d+\.\d+', os.environ['SOZO_TV_VERSION']), 'Use a three-part marketing version' -assert re.fullmatch(r'[1-9]\d{0,3}', os.environ['SOZO_TV_BUILD_NUMBER']), 'Use build number 1–9999' +assert re.fullmatch(r'auto|[1-9]\d{0,3}', os.environ['SOZO_TV_BUILD_NUMBER']), 'Use build number 1–9999 or auto' PY if [ "$sozo_upload" = true ]; then : "${ASC_API_KEY_P8_BASE64:?Set ASC_API_KEY_P8_BASE64 for TestFlight upload}" : "${ASC_API_KEY_ID:?Set ASC_API_KEY_ID for TestFlight upload}" : "${ASC_API_ISSUER_ID:?Set ASC_API_ISSUER_ID for TestFlight upload}" fi -for tool in xcodegen xcodebuild python3 security codesign; do +for tool in xcodegen xcodebuild python3 security codesign openssl; do command -v "$tool" >/dev/null || { echo "Missing required tool: $tool" >&2; exit 1; } done sozo_output="${SOZO_TV_RELEASE_DIR:-$PWD/build/release}" @@ -55,9 +71,31 @@ root = pathlib.Path(os.environ['SOZO_TV_SECRET_DIR']) for env, name in [('APPLE_TV_CERTIFICATE_P12_BASE64', 'certificate.p12'), ('APPLE_TV_PROFILE_BASE64', 'profile.mobileprovision')]: (root / name).write_bytes(base64.b64decode(''.join(os.environ[env].split()), validate=True)) -if os.environ.get('SOZO_TV_UPLOAD_TESTFLIGHT') == 'true': +if os.environ.get('ASC_API_KEY_P8_BASE64'): (root / 'AuthKey.p8').write_bytes(base64.b64decode(''.join(os.environ['ASC_API_KEY_P8_BASE64'].split()), validate=True)) PY +export ASC_API_KEY_PATH="$sozo_secret_dir/AuthKey.p8" +if [ "$SOZO_TV_BUILD_NUMBER" = auto ]; then + sozo_resolved='' + if [ "$sozo_has_asc" = true ]; then + sozo_resolved="$(python3 scripts/asc.py next-build)" || sozo_resolved='' + fi + if [ -z "$sozo_resolved" ] && [ "$sozo_upload" = true ]; then + echo 'Could not read the latest build from App Store Connect; retry, or set SOZO_TV_BUILD_NUMBER' >&2; exit 1 + fi + if [ -z "$sozo_resolved" ]; then + : "${SOZO_TV_BUILD_NUMBER_FALLBACK:?Could not read the latest build from App Store Connect; set SOZO_TV_BUILD_NUMBER}" + echo "App Store Connect query unavailable; falling back to build number $SOZO_TV_BUILD_NUMBER_FALLBACK" >&2 + sozo_resolved="$SOZO_TV_BUILD_NUMBER_FALLBACK" + fi + SOZO_TV_BUILD_NUMBER="$sozo_resolved" + if ! printf '%s' "$SOZO_TV_BUILD_NUMBER" | grep -Eq '^[1-9][0-9]{0,3}$'; then + echo "Resolved build number $SOZO_TV_BUILD_NUMBER is outside 1–9999" >&2; exit 1 + fi +fi +echo "Build number: $SOZO_TV_BUILD_NUMBER" +printf '%s\n' "$SOZO_TV_BUILD_NUMBER" > "$sozo_output/build-number.txt" +if [ -n "${GITHUB_OUTPUT:-}" ]; then echo "build_number=$SOZO_TV_BUILD_NUMBER" >> "$GITHUB_OUTPUT"; fi security cms -D -i "$sozo_secret_dir/profile.mobileprovision" > "$sozo_secret_dir/profile.plist" python3 scripts/prepare-release.py "$sozo_secret_dir/profile.plist" "$sozo_secret_dir/ExportOptions.plist" > "$sozo_secret_dir/profile-uuid.txt" sozo_profile_uuid="$(cat "$sozo_secret_dir/profile-uuid.txt")" @@ -94,4 +132,13 @@ fi xcodebuild -exportArchive -archivePath "$sozo_output/SozoTV.xcarchive" \ -exportOptionsPlist "$sozo_secret_dir/ExportOptions.plist" \ -exportPath "$sozo_output/export" "${sozo_auth[@]}" 2>&1 | tee "$sozo_output/export.log" +if [ "$sozo_upload" = true ] && [ -n "${GITHUB_OUTPUT:-}" ]; then echo 'uploaded=true' >> "$GITHUB_OUTPUT"; fi echo "Release complete: $SOZO_TV_VERSION ($SOZO_TV_BUILD_NUMBER), upload=$sozo_upload" +if [ "$sozo_wait" = true ]; then + sozo_build_id="$(python3 scripts/asc.py wait "$SOZO_TV_VERSION" "$SOZO_TV_BUILD_NUMBER" "${SOZO_TV_WAIT_MINUTES:-45}")" + if [ -n "${GITHUB_OUTPUT:-}" ]; then echo 'processed=true' >> "$GITHUB_OUTPUT"; fi + if [ -n "$sozo_group" ]; then + python3 scripts/asc.py add-to-group "$sozo_build_id" "$sozo_group" + if [ -n "${GITHUB_OUTPUT:-}" ]; then echo 'grouped=true' >> "$GITHUB_OUTPUT"; fi + fi +fi diff --git a/apple-tv/scripts/select-xcode.sh b/apple-tv/scripts/select-xcode.sh new file mode 100755 index 00000000..3d5d664e --- /dev/null +++ b/apple-tv/scripts/select-xcode.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# Pin Xcode on a hosted runner. "26.1" (or "26.1.1") must exist exactly; a bare +# major such as "26" takes the newest installed 26.x, so an image update can +# never silently move the build to the next major. +set -euo pipefail +sozo_wanted="${1:?Usage: select-xcode.sh }" +if ! printf '%s' "$sozo_wanted" | grep -Eq '^[0-9]+(\.[0-9]+){0,2}$'; then + echo "Invalid Xcode version: $sozo_wanted" >&2; exit 1 +fi +sozo_root="${SOZO_TV_XCODE_ROOT:-/Applications}" +sozo_available="$(find "$sozo_root" -maxdepth 1 -name 'Xcode_*.app' | sed -E 's|.*/Xcode_(.*)\.app$|\1|' | grep -E '^[0-9.]+$' | sort -t. -k1,1n -k2,2n -k3,3n || true)" +if [[ "$sozo_wanted" == *.* ]]; then + sozo_pick="$(printf '%s\n' "$sozo_available" | grep -Fx "$sozo_wanted" || true)" +else + sozo_pick="$(printf '%s\n' "$sozo_available" | grep -E "^${sozo_wanted}(\.|$)" | tail -1 || true)" +fi +if [ -z "$sozo_pick" ]; then + echo "::error title=Xcode $sozo_wanted not installed::Available on this runner: $(printf '%s' "$sozo_available" | tr '\n' ' ')" >&2 + exit 1 +fi +sozo_dir="$sozo_root/Xcode_${sozo_pick}.app/Contents/Developer" +echo "DEVELOPER_DIR=$sozo_dir" >> "${GITHUB_ENV:-/dev/null}" +DEVELOPER_DIR="$sozo_dir" xcodebuild -version