name: PyPI
on:
  push:
    branches:
      - main
      - auto-release
  pull_request:
    branches: [main]
  release:
    types: [published]

# Cancels all previous workflow runs for pull requests that have not completed.
concurrency:
  # The concurrency group contains the workflow name and the branch name for pull requests
  # or the commit hash for any other events.
  group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }}
  cancel-in-progress: true

jobs:
  # The job to build precompiled pypi wheels.
  make_sdist:
    name: Make SDist
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
          submodules: true

      - name: Build SDist
        run: pipx run build --sdist

      - uses: actions/upload-artifact@v3
        with:
          path: dist/*.tar.gz

  build_wheels:
    name: Build ${{ matrix.python-version }} wheels on ${{ matrix.platform }}
    runs-on: ${{ matrix.platform }}
    strategy:
      matrix:
        platform:
          - macos-12
          - windows-2022
          - ubuntu-20.04
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Build wheels
        uses: pypa/cibuildwheel@v2.12.3

      - uses: actions/upload-artifact@v3
        with:
          path: ./wheelhouse/*.whl

  check_dist:
    name: Check dist
    needs: [make_sdist,build_wheels]
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/download-artifact@v3
        with:
          name: artifact
          path: dist
      - name: Check SDist
        run: |
          mkdir -p test-sdist
          cd test-sdist
          python -m venv venv-sdist
          venv-sdist/bin/python -m pip install ../dist/pytensor-*.tar.gz
          # check import
          venv-sdist/bin/python -c "import pytensor;print(pytensor.__version__)"
          # check import cython module
          venv-sdist/bin/python -c 'from pytensor.scan import scan_perform; print(scan_perform.get_version())'

      - run: pipx run twine check --strict dist/*

  upload_pypi:
    name: Upload to PyPI on release
    needs: [check_dist]
    runs-on: ubuntu-latest
    if: github.event_name == 'release' && github.event.action == 'published'
    steps:
    - uses: actions/download-artifact@v3
      with:
        name: artifact
        path: dist

    - uses: pypa/gh-action-pypi-publish@v1.8.6
      with:
        user: __token__
        password: ${{ secrets.pypi_password }}
