|
7 | 7 |
|
8 | 8 | from __future__ import annotations |
9 | 9 |
|
| 10 | +from collections.abc import Callable |
| 11 | +import json |
| 12 | +import re |
| 13 | +import subprocess |
10 | 14 | from typing import Any |
| 15 | +from urllib.parse import urlsplit |
11 | 16 |
|
12 | 17 | from .update_artifact import resolve_artifact, target_direction |
13 | 18 | from ..activation_qualification import runtime_activation_qualification |
| 19 | +from ..python_install_owner import SPLIT_UPDATE_GUIDANCE |
| 20 | + |
| 21 | + |
| 22 | +def pin_pip_update_target( |
| 23 | + command: list[str], *, installed_version: object, timeout_seconds: int, |
| 24 | +) -> str: |
| 25 | + """Resolve the real pip target and return an immutable install requirement.""" |
| 26 | + result = subprocess.run( |
| 27 | + [*command[:-1], "--dry-run", "--quiet", "--disable-pip-version-check", "--report", "-", command[-1]], |
| 28 | + text=True, encoding="utf-8", errors="replace", capture_output=True, timeout=timeout_seconds, |
| 29 | + ) |
| 30 | + if result.returncode: |
| 31 | + raise ValueError("pip could not resolve the in-place update target. Inspect the pip installation source.") |
| 32 | + |
| 33 | + unverified = "pip could not verify the exact LoopX package for an in-place update." |
| 34 | + try: |
| 35 | + report = json.loads(result.stdout) |
| 36 | + if report["version"] not in {"0", "1"} or not isinstance(report["install"], list): |
| 37 | + raise ValueError |
| 38 | + packages = { |
| 39 | + re.sub(r"[-_.]+", "-", item["metadata"]["name"].lower()): item |
| 40 | + for item in report["install"] |
| 41 | + } |
| 42 | + if len(packages) != len(report["install"]): |
| 43 | + raise ValueError |
| 44 | + except (AttributeError, KeyError, TypeError, ValueError): |
| 45 | + raise ValueError(unverified) from None |
| 46 | + |
| 47 | + target = packages.get("loopx") |
| 48 | + requirements = target["metadata"].get("requires_dist", []) if target is not None else [] |
| 49 | + if not isinstance(requirements, list) or not all(isinstance(item, str) for item in requirements): |
| 50 | + raise ValueError(unverified) |
| 51 | + if "loopx-core" in packages or any( |
| 52 | + re.match(r"^\s*loopx[-_.]+core(?=$|[\s\[(;@<>=!~])", item, re.IGNORECASE) |
| 53 | + for item in requirements |
| 54 | + ): |
| 55 | + raise ValueError(f"The selected LoopX package changes file ownership to the split layout. {SPLIT_UPDATE_GUIDANCE}") |
| 56 | + |
| 57 | + if target is None: |
| 58 | + # Keep the existing distribution selected while preserving pip's normal |
| 59 | + # dependency handling and the runtime's post-install validation. |
| 60 | + if not isinstance(installed_version, str) or not re.fullmatch(r"[0-9A-Za-z.!+_-]+", installed_version): |
| 61 | + raise ValueError(unverified) |
| 62 | + return f"loopx=={installed_version}" |
| 63 | + try: |
| 64 | + download = target["download_info"] |
| 65 | + url = download["url"].partition("#")[0] |
| 66 | + archive = download["archive_info"] |
| 67 | + legacy = re.fullmatch(r"sha256=([0-9a-fA-F]{64})", archive.get("hash", "")) |
| 68 | + digest = archive.get("hashes", {}).get("sha256") or (legacy[1] if legacy else "") |
| 69 | + if urlsplit(url).scheme not in {"https", "http", "file"} or any(character.isspace() for character in url): |
| 70 | + raise ValueError |
| 71 | + if not re.fullmatch(r"[0-9a-fA-F]{64}", digest): |
| 72 | + raise ValueError |
| 73 | + except (AttributeError, KeyError, TypeError, ValueError): |
| 74 | + raise ValueError(unverified) from None |
| 75 | + return f"loopx @ {url}#sha256={digest}" |
| 76 | + |
| 77 | + |
| 78 | +def install_python_package( |
| 79 | + payload: dict[str, Any], command: list[str], *, installed_version: object, |
| 80 | + timeout_seconds: int, progress: Callable[[str], None], |
| 81 | +) -> subprocess.CompletedProcess[str] | dict[str, Any]: |
| 82 | + """Apply the owning package manager command after validating a pip target.""" |
| 83 | + install_command = command |
| 84 | + artifact_url = "" |
| 85 | + if payload["install_lifecycle"]["execution_driver"] == "python_pip": |
| 86 | + progress("Checking the Python package selected by pip") |
| 87 | + try: |
| 88 | + requirement = pin_pip_update_target(command, installed_version=installed_version, timeout_seconds=timeout_seconds) |
| 89 | + except ValueError as exc: |
| 90 | + reason = str(exc) |
| 91 | + return { |
| 92 | + **payload, "ok": False, "changes_applied": False, "execution": None, |
| 93 | + "error": reason, "recommended_action": reason, |
| 94 | + "plan": {**payload.get("plan", {}), "apply_supported": False, |
| 95 | + "blocked_reason": reason, "mutates_release_install": False}, |
| 96 | + "next_action": {"kind": "review_update_target", "command": None, |
| 97 | + "mutating": False, "requires_explicit_approval": False, "reason": reason}, |
| 98 | + } |
| 99 | + install_command = [*command[:-1], requirement] |
| 100 | + artifact_url = requirement.partition(" @ ")[2].partition("#")[0] |
| 101 | + progress("Updating CLI through its Python package manager") |
| 102 | + try: |
| 103 | + result = subprocess.run( |
| 104 | + install_command, text=True, encoding="utf-8", errors="replace", |
| 105 | + capture_output=True, timeout=timeout_seconds, |
| 106 | + ) |
| 107 | + except subprocess.TimeoutExpired as exc: |
| 108 | + if artifact_url: |
| 109 | + raise subprocess.TimeoutExpired(command, exc.timeout) from None |
| 110 | + raise |
| 111 | + if artifact_url: |
| 112 | + # The retained worker output must not expose a signed artifact URL. |
| 113 | + result.stdout = result.stdout.replace(artifact_url, "<verified LoopX package>") |
| 114 | + result.stderr = result.stderr.replace(artifact_url, "<verified LoopX package>") |
| 115 | + return result |
14 | 116 |
|
15 | 117 |
|
16 | 118 | def prepare_target(payload: dict[str, Any], *, freshness: dict, resolve_remote: bool, |
|
0 commit comments