|
| 1 | +# jiggle_version/pypi.py |
| 2 | +""" |
| 3 | +Implements a pre-flight check against PyPI to prevent bumping an unpublished version. |
| 4 | +""" |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import sys |
| 8 | +from datetime import datetime, timedelta, timezone |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | +import requests |
| 12 | +import tomlkit |
| 13 | +from packaging.version import Version |
| 14 | + |
| 15 | +# Handle Python < 3.11 needing tomli |
| 16 | +if sys.version_info < (3, 11): |
| 17 | + import tomli as tomllib |
| 18 | +else: |
| 19 | + import tomllib |
| 20 | + |
| 21 | + |
| 22 | +# --- Custom Exception --- |
| 23 | +class UnpublishedVersionError(Exception): |
| 24 | + """Raised when attempting to bump a version that is unpublished on PyPI.""" |
| 25 | + |
| 26 | + |
| 27 | +# --- Caching Configuration --- |
| 28 | +CACHE_TTL = timedelta(days=1) |
| 29 | + |
| 30 | + |
| 31 | +def get_package_name(project_root: Path) -> str | None: |
| 32 | + """ |
| 33 | + Finds the package name from pyproject.toml [project].name. |
| 34 | + """ |
| 35 | + pyproject_path = project_root / "pyproject.toml" |
| 36 | + if not pyproject_path.is_file(): |
| 37 | + return None |
| 38 | + try: |
| 39 | + config = tomllib.loads(pyproject_path.read_text(encoding="utf-8")) |
| 40 | + return config.get("project", {}).get("name") |
| 41 | + except tomllib.TOMLDecodeError: |
| 42 | + return None |
| 43 | + |
| 44 | + |
| 45 | +def get_latest_published_version(package_name: str, config_path: Path) -> str | None: |
| 46 | + """ |
| 47 | + Fetches the latest published version of a package from PyPI, caching the |
| 48 | + result in the project's .jiggle_version.config file. |
| 49 | + """ |
| 50 | + # --- Read from TOML cache --- |
| 51 | + doc = ( |
| 52 | + tomlkit.parse(config_path.read_text(encoding="utf-8")) |
| 53 | + if config_path.is_file() |
| 54 | + else tomlkit.document() |
| 55 | + ) |
| 56 | + jiggle_tool_config = doc.get("tool", {}).get("jiggle_version", {}) |
| 57 | + pypi_cache = jiggle_tool_config.get("pypi_cache", {}) |
| 58 | + last_checked_str = pypi_cache.get("timestamp") |
| 59 | + |
| 60 | + if last_checked_str: |
| 61 | + last_checked = datetime.fromisoformat(last_checked_str) |
| 62 | + if datetime.now(timezone.utc) - last_checked < CACHE_TTL: |
| 63 | + print( |
| 64 | + f" (from cache created at {last_checked.strftime('%Y-%m-%d %H:%M')})" |
| 65 | + ) |
| 66 | + return pypi_cache.get("latest_version") |
| 67 | + |
| 68 | + # --- Fetch from PyPI --- |
| 69 | + print(" (querying pypi.org...)") |
| 70 | + url = f"https://pypi.org/pypi/{package_name}/json" |
| 71 | + latest_version = None |
| 72 | + try: |
| 73 | + response = requests.get(url, timeout=10) |
| 74 | + if response.status_code == 404: |
| 75 | + latest_version = None # Package not on PyPI at all |
| 76 | + elif response.status_code == 200: |
| 77 | + data = response.json() |
| 78 | + latest_version = data.get("info", {}).get("version") |
| 79 | + # On other errors, we return None to skip the check gracefully |
| 80 | + |
| 81 | + # --- Update TOML cache --- |
| 82 | + cache_table = tomlkit.table() |
| 83 | + cache_table.add("timestamp", datetime.now(timezone.utc).isoformat()) |
| 84 | + cache_table.add("latest_version", latest_version) |
| 85 | + |
| 86 | + if "tool" not in doc: |
| 87 | + doc.add("tool", tomlkit.table()) |
| 88 | + if "jiggle_version" not in doc.get("tool", {}): # type: ignore |
| 89 | + doc["tool"].add("jiggle_version", tomlkit.table()) # type: ignore |
| 90 | + |
| 91 | + doc["tool"]["jiggle_version"]["pypi_cache"] = cache_table # type: ignore |
| 92 | + config_path.write_text(tomlkit.dumps(doc), encoding="utf-8") |
| 93 | + |
| 94 | + except requests.RequestException: |
| 95 | + # Network error, skip the check |
| 96 | + pass |
| 97 | + |
| 98 | + return latest_version |
| 99 | + |
| 100 | + |
| 101 | +def check_pypi_publication( |
| 102 | + package_name: str, current_version: str, new_version: str, config_path: Path |
| 103 | +) -> None: |
| 104 | + """ |
| 105 | + Checks if the current version is published and allows bumping under specific rules. |
| 106 | + """ |
| 107 | + latest_published_str = get_latest_published_version(package_name, config_path) |
| 108 | + |
| 109 | + if not latest_published_str: |
| 110 | + # NEW BEHAVIOR: If the package has never been published, block the bump. |
| 111 | + raise UnpublishedVersionError( |
| 112 | + f"Package '{package_name}' is not on PyPI. Publish the initial version first." |
| 113 | + ) |
| 114 | + |
| 115 | + current_v = Version(current_version) |
| 116 | + published_v = Version(latest_published_str) |
| 117 | + new_v = Version(new_version) |
| 118 | + |
| 119 | + if current_v > published_v: |
| 120 | + if new_v > current_v: |
| 121 | + print( |
| 122 | + f"🟡 Current version '{current_v}' is unpublished (PyPI has '{published_v}'). " |
| 123 | + f"Allowing bump to '{new_v}'." |
| 124 | + ) |
| 125 | + return |
| 126 | + raise UnpublishedVersionError( |
| 127 | + f"Current version '{current_v}' is not published on PyPI (latest is '{published_v}').\n" |
| 128 | + "Cannot perform a redundant bump." |
| 129 | + ) |
| 130 | + elif new_v > published_v: |
| 131 | + print(f"✅ PyPI version is '{published_v}'. Bump to '{new_v}' is allowed.") |
| 132 | + return |
| 133 | + else: |
| 134 | + raise UnpublishedVersionError( |
| 135 | + f"New version '{new_v}' is not greater than the latest published version on PyPI ('{published_v}')." |
| 136 | + ) |
0 commit comments