Skip to content

Update python-publish.yml #6

Update python-publish.yml

Update python-publish.yml #6

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 Python
- name: Check if version exists on PyPI
id: check_version
run: |
python - <<EOF >> "$GITHUB_OUTPUT"
import requests
import sys
import os
import json
from packaging import version as packaging_version
package_name = os.environ['PACKAGE_NAME']
current_version = os.environ['VERSION']
print(f"Checking version {current_version} for package {package_name}")
url = f"https://pypi.org/pypi/{package_name}/json"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
releases = data.get('releases', {})
# Normalize the version for comparison
current_ver = packaging_version.parse(current_version)
# Check if version exists
if str(current_ver) in releases:
print("Version already exists on PyPI")
print("should_publish=false")
else:
print("Version is new")
print("should_publish=true")
elif response.status_code == 404:
print("Package not found on PyPI - this is a new package")
print("should_publish=true")
else:
print(f"Error checking PyPI API: HTTP status {response.status_code}")
sys.exit(1)
EOF
env:
PACKAGE_NAME: ${{ steps.package_info.outputs.package_name }}
VERSION: ${{ steps.package_info.outputs.version }}
- 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"