#!/usr/bin/env python3 """Copy installed wheel packages into a fresh Conda prefix of the same Python ABI. Run with the source venv's Python. Uses RECORD to include native libraries, headers and entry points, repairs script shebangs and RECORD hashes, and makes independent copies (no links or PYTHONPATH dependency on the source venv). Conda's pip, setuptools and wheel are retained. Existing files are never replaced. """ from __future__ import annotations import argparse import base64 import csv import hashlib import importlib.metadata as metadata import io import json import os from pathlib import Path import shutil import subprocess import sys import sysconfig def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--target", type=Path, required=True) parser.add_argument("--report", type=Path, required=True) args = parser.parse_args() source = Path(sys.prefix).resolve() target = args.target.resolve() source_site = Path(sysconfig.get_path("purelib")).resolve() if source == target or not (source / "pyvenv.cfg").is_file(): parser.error("run this script with the source venv Python") if not (target / "conda-meta/history").is_file(): parser.error("target must already be a Conda environment") info = json.loads(subprocess.check_output([ str(target / "bin/python"), "-I", "-c", "import json,sys,sysconfig; print(json.dumps({'abi':sys.implementation.cache_tag," "'site':sysconfig.get_path('purelib')}))", ], text=True)) if info["abi"] != sys.implementation.cache_tag: parser.error("source and target must use the same CPython major/minor ABI") target_site = Path(info["site"]).resolve() if source_site.relative_to(source) != target_site.relative_to(target): parser.error("source and target must have matching site-packages layouts") plans = [] skipped = [] for dist in sorted(metadata.distributions(path=[str(source_site)]), key=lambda d: d.name.lower()): if dist.name.lower() in {"pip", "setuptools", "wheel"}: skipped.append({"name": dist.name, "version": dist.version}) continue contents = dist.read_text("RECORD") if contents is None: raise ValueError(f"no wheel RECORD for {dist.name}") rows = list(csv.reader(io.StringIO(contents))) record_row = next(row for row in rows if row[0].endswith(".dist-info/RECORD")) for relative, _, _ in rows: if relative.endswith(".pyc"): continue src = (source_site / relative).resolve() dst = (target_site / relative).resolve() if not src.is_relative_to(source) or not dst.is_relative_to(target): raise ValueError(f"RECORD path leaves its prefix: {relative}") if not src.is_file(): raise FileNotFoundError(src) if dst.exists(): raise FileExistsError(f"refusing to overwrite {dst}") plans.append((dist.name, dist.version, rows, record_row[0])) report = {"source": str(source), "target": str(target), "abi": info["abi"], "method": "independent_RECORD_file_copies", "skipped_build_tools": skipped, "packages": [], "bytes_copied": 0, "entry_points_relocated": []} for name, version, rows, record_name in plans: new_rows = [] for relative, checksum, size in rows: if relative.endswith(".pyc"): continue src = (source_site / relative).resolve() dst = (target_site / relative).resolve() if relative != record_name: dst.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(src, dst) if dst.parent == target / "bin": data = dst.read_bytes() first, separator, rest = data.partition(b"\n") if first.startswith(b"#!") and b"python" in first: data = b"#!" + os.fsencode(target / "bin/python") + b"\n" + rest dst.write_bytes(data) checksum = "sha256=" + base64.urlsafe_b64encode( hashlib.sha256(data).digest()).decode().rstrip("=") size = str(len(data)) report["entry_points_relocated"].append(str(dst)) report["bytes_copied"] += dst.stat().st_size new_rows.append([relative, checksum, size]) record = (target_site / record_name).resolve() with record.open("w", newline="", encoding="utf-8") as stream: csv.writer(stream).writerows(new_rows) report["packages"].append({"name": name, "version": version}) print(f"Reused {name}=={version}", flush=True) args.report.parent.mkdir(parents=True, exist_ok=True) args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") print(json.dumps({"packages_reused": len(plans), "gib_copied": round(report["bytes_copied"] / 2**30, 3), "report": str(args.report)}, indent=2)) if __name__ == "__main__": main()