diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 6e37bb0..e93adbc 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -9,6 +9,9 @@ on: # Allows you to run this workflow manually from the Actions tab workflow_dispatch: +permissions: + contents: read + jobs: tests: name: "python=${{ matrix.python-version }} zarr=${{ matrix.zarr-version }} tests" @@ -20,13 +23,13 @@ jobs: zarr-version: [">=2,<3", ">=3"] steps: - name: Cancel previous - uses: styfle/cancel-workflow-action@0.7.0 + uses: styfle/cancel-workflow-action@d7e57e26a6f753933f8ef746a37097a61375236b # 0.7.0 with: access_token: ${{ github.token }} if: ${{github.ref != 'refs/head/main'}} - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 with: python-version: ${{ matrix.python-version }} - name: Get pip cache dir @@ -35,7 +38,7 @@ jobs: python -m pip install --upgrade pip wheel echo "::set-output name=dir::$(pip cache dir)" - name: pip cache - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 with: path: ${{ steps.pip-cache.outputs.dir }} key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }} @@ -52,18 +55,119 @@ jobs: # * Repo is self (prevents running from forks) # * Branch is `main` if: | - github.repository == 'google/xarray-Tensorstore' + github.repository == 'google/xarray-tensorstore' && github.ref == 'refs/heads/main' needs: tests # Only publish after tests are successful runs-on: ubuntu-latest permissions: contents: write + id-token: write timeout-minutes: 30 steps: - # Publish the package (if local `__version__` > pip version) - - uses: etils-actions/pypi-auto-publish@v1 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: '3.12' + - name: Check version and build if new + id: check_version + run: | + python -m pip install --upgrade pip build twine packaging + LOCAL_VER=$(python -c "import xarray_tensorstore; print(xarray_tensorstore.__version__)") + PYPI_VER=$(python -c "import json, urllib.request; print(json.loads(urllib.request.urlopen('https://pypi.org/pypi/xarray-tensorstore/json').read())['info']['version'])") + echo "Local: $LOCAL_VER, PyPI: $PYPI_VER" + if python -c "from packaging.version import Version; exit(0 if Version('$LOCAL_VER') > Version('$PYPI_VER') else 1)"; then + echo "should_publish=true" >> "$GITHUB_OUTPUT" + python -m build + else + echo "should_publish=false" >> "$GITHUB_OUTPUT" + fi + - name: Authenticate to Google Cloud (OSS Exit Gate) + if: steps.check_version.outputs.should_publish == 'true' + uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0 with: - pypi-token: ${{ secrets.PYPI_API_TOKEN }} - gh-token: ${{ secrets.GITHUB_TOKEN }} - parse-changelog: false + workload_identity_provider: 'projects/305452601764/locations/global/workloadIdentityPools/builders/providers/github' + - name: Set up Cloud SDK + if: steps.check_version.outputs.should_publish == 'true' + uses: google-github-actions/setup-gcloud@aa5489c8933f4cc7a4f7d45035b3b1440c9c10db # v3.0.1 + - name: Clean up failed staging attempt for this exact version (if any) + if: steps.check_version.outputs.should_publish == 'true' + run: | + python3 - <<'PY' + import email, glob, re, subprocess, tarfile, zipfile + seen = set() + for f in sorted(glob.glob("dist/**/*.whl", recursive=True) + glob.glob("dist/**/*.tar.gz", recursive=True)): + try: + if f.endswith(".whl"): + with zipfile.ZipFile(f) as zf: + meta = [n for n in zf.namelist() if n.endswith(".dist-info/METADATA")][0] + msg = email.message_from_bytes(zf.read(meta)) + else: + with tarfile.open(f) as tf: + info = [m for m in tf.getmembers() if m.name.endswith("/PKG-INFO") or m.name == "PKG-INFO"][0] + msg = email.message_from_bytes(tf.extractfile(info).read()) + pkg = re.sub(r"[-_.]+", "-", msg["Name"].strip()).lower() + ver = msg["Version"].strip() + except Exception: + continue + if (pkg, ver) in seen: + continue + seen.add((pkg, ver)) + if subprocess.run([ + "gcloud", "artifacts", "versions", "describe", ver, + f"--package={pkg}", "--project=oss-exit-gate-prod", "--location=us", "--repository=xarray-tensorstore--pypi" + ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0: + subprocess.run([ + "gcloud", "artifacts", "versions", "delete", ver, + f"--package={pkg}", "--project=oss-exit-gate-prod", "--location=us", "--repository=xarray-tensorstore--pypi", "--quiet" + ], check=False) + PY + + - name: Stage to OSS Exit Gate and upload manifest + if: steps.check_version.outputs.should_publish == 'true' + run: | + TWINE_PASSWORD="$(gcloud auth print-access-token)" + echo "::add-mask::${TWINE_PASSWORD}" + python -m twine upload \ + --repository-url "https://us-python.pkg.dev/oss-exit-gate-prod/xarray-tensorstore--pypi/" \ + -u oauth2accesstoken \ + -p "${TWINE_PASSWORD}" \ + dist/* + python3 - dist/* <<'PY' + import email, json, re, sys, tarfile, zipfile + pairs = set() + for path in sys.argv[1:]: + if path.endswith(".whl"): + with zipfile.ZipFile(path) as zf: + for name in zf.namelist(): + if name.endswith(".dist-info/METADATA"): + msg = email.message_from_bytes(zf.read(name)) + pkg = re.sub(r"[-_.]+", "-", msg["Name"].strip()).lower() + pairs.add((pkg, msg["Version"].strip())) + break + elif path.endswith(".tar.gz"): + with tarfile.open(path, "r:gz") as tf: + for member in tf.getmembers(): + if member.name.endswith("/PKG-INFO") and member.name.count("/") == 1: + f = tf.extractfile(member) + if f is not None: + msg = email.message_from_bytes(f.read()) + pkg = re.sub(r"[-_.]+", "-", msg["Name"].strip()).lower() + pairs.add((pkg, msg["Version"].strip())) + break + if not pairs: + raise SystemExit("ERROR: No .whl/.tar.gz package metadata found for manifest.json") + manifest = { + "publish_all": False, + "publishing_groups": [{ + "packages": [{"name": pkg, "version": ver} for pkg, ver in sorted(pairs)] + }], + } + with open("manifest.json", "w", encoding="utf-8") as fh: + json.dump(manifest, fh, indent=2) + fh.write("\n") + PY + gcloud storage cp manifest.json \ + "gs://oss-exit-gate-prod-projects-bucket/xarray-tensorstore/pypi/manifests/manifest-${{ github.run_id }}-${{ github.run_attempt }}.json"