|
| 1 | +"""Best-effort check for whether the installed ``repowise`` CLI is stale. |
| 2 | +
|
| 3 | +This is intentionally conservative: |
| 4 | +
|
| 5 | +* Current version comes from :data:`repowise.cli.__version__`. |
| 6 | +* Latest version is fetched from the PyPI JSON endpoint via the already-bundled |
| 7 | + ``httpx`` with a short timeout. |
| 8 | +* An install-method-appropriate upgrade *command* is suggested, but never run. |
| 9 | +
|
| 10 | +Network failures are swallowed — callers (e.g. ``repowise doctor``) must keep |
| 11 | +working when PyPI is unreachable. This module never raises and never invokes a |
| 12 | +package manager. |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import shutil |
| 18 | +import sys |
| 19 | +from dataclasses import dataclass |
| 20 | +from pathlib import Path |
| 21 | + |
| 22 | +PYPI_URL = "https://pypi.org/pypi/repowise/json" |
| 23 | + |
| 24 | + |
| 25 | +@dataclass(frozen=True) |
| 26 | +class UpdateCheck: |
| 27 | + """Result of a CLI update check. |
| 28 | +
|
| 29 | + ``update_available`` is ``None`` when the latest version could not be |
| 30 | + determined (network error, parse failure) so callers can distinguish |
| 31 | + "up to date" from "unknown". |
| 32 | + """ |
| 33 | + |
| 34 | + current_version: str |
| 35 | + latest_version: str | None |
| 36 | + resolved_executable: str | None |
| 37 | + running_executable: str |
| 38 | + python: str |
| 39 | + update_available: bool | None |
| 40 | + suggested_command: str |
| 41 | + install_hint: str |
| 42 | + error: str | None = None |
| 43 | + |
| 44 | + |
| 45 | +def _parse_release(version: str) -> tuple[int, ...] | None: |
| 46 | + """Parse the leading numeric release parts of a version string. |
| 47 | +
|
| 48 | + Returns a tuple of ints for the dotted numeric prefix (so ``0.15.2`` -> |
| 49 | + ``(0, 15, 2)``). Pre-release/local suffixes such as ``-rc1`` or ``+local`` |
| 50 | + are ignored. Returns ``None`` when no numeric component can be parsed. |
| 51 | + """ |
| 52 | + parts: list[int] = [] |
| 53 | + for chunk in version.strip().split("."): |
| 54 | + digits = "" |
| 55 | + for ch in chunk: |
| 56 | + if ch.isdigit(): |
| 57 | + digits += ch |
| 58 | + else: |
| 59 | + break |
| 60 | + if not digits: |
| 61 | + break |
| 62 | + parts.append(int(digits)) |
| 63 | + return tuple(parts) or None |
| 64 | + |
| 65 | + |
| 66 | +def is_newer_version(latest: str, current: str) -> bool: |
| 67 | + """Return ``True`` if ``latest`` is a strictly newer release than ``current``. |
| 68 | +
|
| 69 | + Uses a simple numeric-release comparison. If either version cannot be |
| 70 | + parsed, returns ``False`` (no update decision) rather than raising. |
| 71 | + """ |
| 72 | + lat = _parse_release(latest) |
| 73 | + cur = _parse_release(current) |
| 74 | + if lat is None or cur is None: |
| 75 | + return False |
| 76 | + # Pad to equal length so 0.15 compares correctly against 0.15.2. |
| 77 | + length = max(len(lat), len(cur)) |
| 78 | + lat = lat + (0,) * (length - len(lat)) |
| 79 | + cur = cur + (0,) * (length - len(cur)) |
| 80 | + return lat > cur |
| 81 | + |
| 82 | + |
| 83 | +def suggest_update_command(executable: str | None, python: str) -> tuple[str, str]: |
| 84 | + """Suggest an upgrade command and human-readable install hint. |
| 85 | +
|
| 86 | + Heuristic, based on the resolved executable path. Returns |
| 87 | + ``(command, hint)``. When the install method is unknown, falls back to a |
| 88 | + safe ``<python> -m pip install -U repowise``. |
| 89 | + """ |
| 90 | + path = (executable or "").replace("\\", "/").lower() |
| 91 | + |
| 92 | + if "pipx" in path: |
| 93 | + return ("pipx upgrade repowise", "pipx") |
| 94 | + # uv tool installs live under a uv data dir, e.g. |
| 95 | + # ~/.local/share/uv/tools/... or a uv-managed bin shim. |
| 96 | + if "/uv/" in path or "uv/tools" in path or "/uv/tools/" in path: |
| 97 | + return ("uv tool upgrade repowise", "uv tool") |
| 98 | + return (f"{python} -m pip install -U repowise", "pip") |
| 99 | + |
| 100 | + |
| 101 | +def _editable_checkout() -> Path | None: |
| 102 | + """Return the repo root when ``repowise`` is running from a source checkout. |
| 103 | +
|
| 104 | + Detected by the package not living under ``site-packages``/``dist-packages`` |
| 105 | + while a parent directory carries both ``pyproject.toml`` and ``.git``. |
| 106 | + """ |
| 107 | + try: |
| 108 | + from repowise.cli import __file__ as cli_file |
| 109 | + except Exception: |
| 110 | + return None |
| 111 | + pkg = Path(cli_file).resolve() |
| 112 | + if "site-packages" in pkg.parts or "dist-packages" in pkg.parts: |
| 113 | + return None |
| 114 | + for parent in pkg.parents: |
| 115 | + if (parent / "pyproject.toml").exists() and (parent / ".git").exists(): |
| 116 | + return parent |
| 117 | + return None |
| 118 | + |
| 119 | + |
| 120 | +def get_cli_update_check(timeout: float = 2.0) -> UpdateCheck: |
| 121 | + """Check whether the installed ``repowise`` CLI is out of date. |
| 122 | +
|
| 123 | + Always returns an :class:`UpdateCheck`; never raises. On network/parse |
| 124 | + failure, ``latest_version`` is ``None``, ``update_available`` is ``None``, |
| 125 | + and ``error`` carries a short description. |
| 126 | + """ |
| 127 | + from repowise.cli import __version__ |
| 128 | + |
| 129 | + current = __version__ |
| 130 | + resolved = shutil.which("repowise") |
| 131 | + running = sys.argv[0] if sys.argv else "" |
| 132 | + python = sys.executable or "python" |
| 133 | + |
| 134 | + checkout = _editable_checkout() |
| 135 | + if checkout is not None: |
| 136 | + suggested = f"cd {checkout} && git pull && {python} -m pip install -e ." |
| 137 | + hint = "editable" |
| 138 | + else: |
| 139 | + suggested, hint = suggest_update_command(resolved or running, python) |
| 140 | + |
| 141 | + latest: str | None = None |
| 142 | + error: str | None = None |
| 143 | + try: |
| 144 | + import httpx |
| 145 | + |
| 146 | + resp = httpx.get(PYPI_URL, timeout=timeout) |
| 147 | + resp.raise_for_status() |
| 148 | + fetched = resp.json()["info"]["version"] |
| 149 | + # Only accept a version we can actually compare; otherwise leave |
| 150 | + # latest=None so callers report "unknown" rather than a false "latest". |
| 151 | + if _parse_release(fetched) is None: |
| 152 | + error = f"unparsable latest version: {fetched!r}" |
| 153 | + else: |
| 154 | + latest = fetched |
| 155 | + except Exception as exc: # network, JSON, missing key — all advisory |
| 156 | + error = str(exc) or exc.__class__.__name__ |
| 157 | + |
| 158 | + if latest is None: |
| 159 | + update_available: bool | None = None |
| 160 | + else: |
| 161 | + update_available = is_newer_version(latest, current) |
| 162 | + |
| 163 | + return UpdateCheck( |
| 164 | + current_version=current, |
| 165 | + latest_version=latest, |
| 166 | + resolved_executable=resolved, |
| 167 | + running_executable=running, |
| 168 | + python=python, |
| 169 | + update_available=update_available, |
| 170 | + suggested_command=suggested, |
| 171 | + install_hint=hint, |
| 172 | + error=error, |
| 173 | + ) |
0 commit comments