11# .github/workflows/publish-to-pypi.yml
22
3- name : Publish Python Package to PyPI
3+ name : Publish to PyPI
44
55on :
66 release :
7- types : [published] # This workflow runs when a new release is published on GitHub
7+ types : [published]
8+ workflow_dispatch : # Allows you to manually trigger the workflow
9+
10+ permissions :
11+ contents : read
12+ id-token : write # Required for secure OIDC authentication with PyPI
813
914jobs :
1015 deploy :
1116 runs-on : ubuntu-latest
12-
17+ environment : pypi # Recommended for security
18+
1319 steps :
1420 - name : Checkout code
1521 uses : actions/checkout@v4
22+ # This fetches the specific commit associated with the tag
23+ # to ensure the workflow is using the correct code.
1624
1725 - name : Set up Python
1826 uses : actions/setup-python@v5
1927 with :
20- # Use the specific Python version you require, e-g-, 3.11
2128 python-version : ' 3.11'
29+ cache : ' pip' # Speeds up dependency installation
2230
23- - name : Install modern build dependencies
31+ - name : Install dependencies
2432 run : |
2533 python -m pip install --upgrade pip
2634 pip install build twine
27- # build - The modern, PEP 517 compliant build frontend
28- # twine - The standard for securely uploading packages
2935
30- - name : Build package
31- # This command automatically finds and uses your pyproject.toml
32- # It builds the source distribution (sdist) and the wheel.
33- run : python -m build
36+ - name : Verify package version
37+ run : |
38+ PACKAGE_VERSION=$(python -c "import toml; print(toml.load(open('pyproject.toml'))['project']['version'])")
39+ echo "Detected version from pyproject.toml: $PACKAGE_VERSION"
40+ echo "Expected tag version: ${{ github.ref_name }}"
41+ if [ "$PACKAGE_VERSION" != "${{ github.ref_name }}" ]; then
42+ echo "Error: The version in pyproject.toml does not match the release tag."
43+ exit 1
44+ fi
45+
46+ - name : Clean old builds and build new package
47+ run : |
48+ rm -rf dist/ # Always delete the old dist directory to prevent stale artifacts
49+ python -m build
3450
3551 - name : Publish package to PyPI
36- env :
37- # Use the secret you created in GitHub Settings -> Secrets -> Actions
38- TWINE_USERNAME : __token__
39- TWINE_PASSWORD : ${{ secrets.PYPI_API_TOKEN }}
40- run : twine upload dist/*
52+ uses : pypa/gh-action-pypi-publish@release/v1 # This action is a secure and recommended way to publish
53+ with :
54+ password : ${{ secrets.PYPI_API_TOKEN }}
55+ # The action will automatically find and upload the files in the 'dist' folder
56+
0 commit comments