Publish to PyPI (Trusted Publishing) #14
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # .github/workflows/publish-to-pypi.yml | |
| name: Publish to PyPI | |
| on: | |
| release: | |
| types: [published] | |
| workflow_dispatch: # Allows you to manually trigger the workflow | |
| permissions: | |
| contents: read | |
| id-token: write # Required for secure OIDC authentication with PyPI | |
| jobs: | |
| deploy: | |
| runs-on: ubuntu-latest | |
| environment: pypi # Recommended for security | |
| steps: | |
| - name: Checkout code | |
| uses: actions/checkout@v4 | |
| # This fetches the specific commit associated with the tag | |
| # to ensure the workflow is using the correct code. | |
| - name: Set up Python | |
| uses: actions/setup-python@v5 | |
| with: | |
| python-version: '3.11' | |
| cache: 'pip' # Speeds up dependency installation | |
| - name: Install dependencies | |
| run: | | |
| python -m pip install --upgrade pip | |
| pip install build twine | |
| - name: Verify package version | |
| run: | | |
| PACKAGE_VERSION=$(python -c "import toml; print(toml.load(open('pyproject.toml'))['project']['version'])") | |
| echo "Detected version from pyproject.toml: $PACKAGE_VERSION" | |
| echo "Expected tag version: ${{ github.ref_name }}" | |
| if [ "$PACKAGE_VERSION" != "${{ github.ref_name }}" ]; then | |
| echo "Error: The version in pyproject.toml does not match the release tag." | |
| exit 1 | |
| fi | |
| - name: Clean old builds and build new package | |
| run: | | |
| rm -rf dist/ # Always delete the old dist directory to prevent stale artifacts | |
| python -m build | |
| - name: Publish package to PyPI | |
| uses: pypa/gh-action-pypi-publish@release/v1 # This action is a secure and recommended way to publish | |
| with: | |
| password: ${{ secrets.PYPI_API_TOKEN }} | |
| # The action will automatically find and upload the files in the 'dist' folder | |