name: Continuous Delivery

on:
  push:
    tags: ['v*']  # push events to matching v*, i.e. v1.0, v20.15.10

env:
  PYTHON_DEFAULT_VERSION: "3.12"

jobs:
  deploy:
    env:
      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      B2_PYPI_PASSWORD: ${{ secrets.B2_PYPI_PASSWORD }}
    runs-on: ubuntu-latest
    steps:
      - name: Determine if pre-release
        id: prerelease_check
        run: |
          export IS_PRERELEASE=$([[ ${{ github.ref }} =~ [^0-9]$ ]] && echo true || echo false)
          echo "prerelease=$IS_PRERELEASE" >> $GITHUB_OUTPUT
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - name: Set up Python ${{ env.PYTHON_DEFAULT_VERSION }}
        uses: actions/setup-python@v6
        with:
          python-version: ${{ env.PYTHON_DEFAULT_VERSION }}
      - name: Display Python version
        run: python -c "import sys; print(sys.version)"
      - name: Install dependencies
        run: python -m pip install --upgrade nox pdm
      - name: Build the distribution
        id: build
        run: nox -vs build
      - name: Read the Changelog
        id: read-changelog
        uses: mindsers/changelog-reader-action@v2
        with:
          version: ${{ steps.build.outputs.version }}
      - name: Create GitHub release and upload the distribution
        id: create-release
        uses: softprops/action-gh-release@v2
        with:
          name: ${{ steps.build.outputs.version }}
          body: ${{ steps.read-changelog.outputs.changes }}
          draft: ${{ env.ACTIONS_STEP_DEBUG == 'true' }}
          prerelease: ${{ steps.prerelease_check.outputs.prerelease }}
          files: ${{ steps.build.outputs.asset_path }}
      - name: Upload the distribution to PyPI
        if: ${{ env.B2_PYPI_PASSWORD != '' && steps.prerelease_check.outputs.prerelease == 'false' }}
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          user: __token__
          password: ${{ secrets.B2_PYPI_PASSWORD }}
