Update python-publish.yml #4
This file contains 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
name: Publish Python Package to PyPI | |
on: | |
push: | |
branches: | |
- main | |
jobs: | |
build-and-publish: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Check out repository | |
uses: actions/checkout@v3 | |
with: | |
fetch-depth: 0 | |
- name: Set up Python | |
uses: actions/setup-python@v4 | |
with: | |
python-version: '3.x' | |
- name: Install build dependencies | |
run: | | |
python -m pip install --upgrade pip | |
pip install build twine packaging requests | |
- name: Build package | |
run: python -m build | |
# Get current version and package name | |
- name: Get package info | |
id: package_info | |
run: | | |
if [ -f "pyproject.toml" ]; then | |
VERSION=$(grep -Po "(?<=version = \")[^\"]*" pyproject.toml) | |
PACKAGE_NAME=$(grep -Po "(?<=name = \")[^\"]*" pyproject.toml) | |
elif [ -f "setup.py" ]; then | |
VERSION=$(python setup.py --version) | |
PACKAGE_NAME=$(python setup.py --name) | |
else | |
echo "No version file found" | |
exit 1 | |
fi | |
echo "version=$VERSION" >> "$GITHUB_OUTPUT" | |
echo "package_name=$PACKAGE_NAME" >> "$GITHUB_OUTPUT" | |
# Check PyPI version using API | |
- name: Check if version exists on PyPI | |
id: check_version | |
run: | | |
PACKAGE_NAME="${{ steps.package_info.outputs.package_name }}" | |
VERSION="${{ steps.package_info.outputs.version }}" | |
echo "Checking version $VERSION for package $PACKAGE_NAME" | |
# Use PyPI JSON API to check version | |
HTTP_STATUS=$(curl -s -o response.json -w "%{http_code}" "https://pypi.org/pypi/$PACKAGE_NAME/json") | |
if [ "$HTTP_STATUS" -eq 200 ]; then | |
# Check if version exists in releases | |
if cat response.json | python -c "import sys, json; data = json.load(sys.stdin); sys.exit(0 if '$VERSION' in data['releases'] else 1)"; then | |
echo "Version $VERSION already exists on PyPI" | |
echo "should_publish=false" >> "$GITHUB_OUTPUT" | |
else | |
echo "Version $VERSION is new" | |
echo "should_publish=true" >> "$GITHUB_OUTPUT" | |
fi | |
elif [ "$HTTP_STATUS" -eq 404 ]; then | |
# Package doesn't exist on PyPI yet | |
echo "Package not found on PyPI - this is a new package" | |
echo "should_publish=true" >> "$GITHUB_OUTPUT" | |
else | |
echo "Error checking PyPI API: HTTP status $HTTP_STATUS" | |
exit 1 | |
fi | |
- name: Publish to PyPI | |
if: steps.check_version.outputs.should_publish == 'true' | |
env: | |
TWINE_USERNAME: __token__ | |
TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }} | |
run: | | |
python -m twine upload dist/* | |
- name: Log skip publication | |
if: steps.check_version.outputs.should_publish != 'true' | |
run: | | |
echo "Skipping publication to PyPI as version ${{ steps.package_info.outputs.version }} already exists" |