Skip to content

Update python-publish.yml #5

Update python-publish.yml

Update python-publish.yml #5

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 tomli
- name: Build package
run: python -m build
# Get current version and package name using Python
- name: Get package info
id: package_info
run: |
python - <<EOF >> "$GITHUB_OUTPUT"
import tomli
import json
try:
with open("pyproject.toml", "rb") as f:
data = tomli.load(f)
# Handle different possible TOML structures
if "project" in data:
# PEP 621 metadata
version = data["project"]["version"]
name = data["project"]["name"]
elif "tool" in data and "poetry" in data["tool"]:
# Poetry metadata
version = data["tool"]["poetry"]["version"]
name = data["tool"]["poetry"]["name"]
else:
raise KeyError("Could not find version/name in pyproject.toml")
print(f"version={version}")
print(f"package_name={name}")
except Exception as e:
print(f"Error parsing pyproject.toml: {e}")
exit(1)
EOF
# 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"