|
| 1 | +#!/usr/bin/env python3 |
| 2 | +from __future__ import annotations |
| 3 | +import argparse |
| 4 | +import shutil |
| 5 | +import subprocess |
| 6 | +import sys |
| 7 | +import zipfile |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | +# ---- small helpers |
| 11 | + |
| 12 | +def run(cmd: list[str], cwd: Path | None = None, env: dict[str, str] | None = None) -> None: |
| 13 | + where = f" (cwd={cwd})" if cwd else "" |
| 14 | + print("+", " ".join(cmd) + where, flush=True) |
| 15 | + subprocess.run(cmd, cwd=str(cwd) if cwd else None, env=env, check=True) |
| 16 | + |
| 17 | +def read_pyproject_name(pp: Path) -> str | None: |
| 18 | + try: |
| 19 | + try: |
| 20 | + import tomllib # 3.11+ |
| 21 | + except ModuleNotFoundError: # pragma: no cover |
| 22 | + import tomli as tomllib # type: ignore |
| 23 | + data = tomllib.loads(pp.read_text(encoding="utf-8")) |
| 24 | + proj = data.get("project", {}) |
| 25 | + name = proj.get("name") |
| 26 | + return name if isinstance(name, str) else None |
| 27 | + except Exception: |
| 28 | + return None |
| 29 | + |
| 30 | +def select_best_wheel(dist_dir: Path) -> Path: |
| 31 | + wheels = sorted(dist_dir.glob("*.whl")) |
| 32 | + if not wheels: |
| 33 | + raise SystemExit(f"No wheels found in {dist_dir}") |
| 34 | + # Prefer the wheel that best matches current interpreter & platform |
| 35 | + try: |
| 36 | + from packaging import tags |
| 37 | + supported = list(tags.sys_tags()) |
| 38 | + def score(p: Path) -> int: |
| 39 | + n = p.name |
| 40 | + for i, t in enumerate(supported): |
| 41 | + tag = f"{t.interpreter}-{t.abi}-{t.platform}" |
| 42 | + # allow -any platform too |
| 43 | + if tag in n or f"{t.interpreter}-{t.abi}-any" in n: |
| 44 | + return -i |
| 45 | + return 10**9 |
| 46 | + return sorted(wheels, key=score)[0] |
| 47 | + except Exception: |
| 48 | + # Fallback: newest by mtime |
| 49 | + return max(wheels, key=lambda p: p.stat().st_mtime) |
| 50 | + |
| 51 | +def extract_extension_from_wheel(wheel: Path, dest_pkg_dir: Path) -> Path: |
| 52 | + # Discouraged pattern—only if you truly need the .so in-tree (e.g. docs hack). |
| 53 | + with zipfile.ZipFile(wheel) as zf: |
| 54 | + members = [m for m in zf.namelist() |
| 55 | + if m.replace("\\", "/").startswith(f"{dest_pkg_dir.name}/fortran/") |
| 56 | + and m.endswith((".so", ".dylib", ".pyd"))] |
| 57 | + if not members: |
| 58 | + raise SystemExit("No compiled extension found inside wheel.") |
| 59 | + member = members[0] |
| 60 | + out = dest_pkg_dir / "fortran" / Path(member).name |
| 61 | + out.parent.mkdir(parents=True, exist_ok=True) |
| 62 | + out.write_bytes(zf.read(member)) |
| 63 | + print(f"Extracted {member} -> {out}") |
| 64 | + return out |
| 65 | + |
| 66 | +# ---- main script |
| 67 | + |
| 68 | +def main() -> int: |
| 69 | + parser = argparse.ArgumentParser( |
| 70 | + description="Build wheel (and sdist), install into a fresh venv, run tests. Optionally extract the compiled extension back to source." |
| 71 | + ) |
| 72 | + parser.add_argument("-c", "--clean", action="store_true", help="Remove build artifacts before building") |
| 73 | + parser.add_argument("-s", "--sdist", action="store_true", help="Also build an sdist") |
| 74 | + parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1], |
| 75 | + help="Project root (default: the parent of this script)") |
| 76 | + parser.add_argument("--package-name", default=None, |
| 77 | + help="Package name to install from wheel (default: read from pyproject.toml)") |
| 78 | + parser.add_argument("--tests", type=Path, default=None, |
| 79 | + help="Path to test directory (default: <root>/tests if exists)") |
| 80 | + parser.add_argument("--extract", action="store_true", |
| 81 | + help="Extract the compiled extension from the wheel back into the source tree") |
| 82 | + parser.add_argument("--pytest-args", nargs=argparse.REMAINDER, |
| 83 | + help="Extra args to pass to pytest (use after `--`)") |
| 84 | + args = parser.parse_args() |
| 85 | + |
| 86 | + root = args.root.resolve() |
| 87 | + dist = root / "dist" |
| 88 | + build_dir = root / "build" |
| 89 | + egg_info = next(root.glob("*.egg-info"), None) |
| 90 | + pkg_name = args.package_name or read_pyproject_name(root / "pyproject.toml") or "" |
| 91 | + if not pkg_name: |
| 92 | + raise SystemExit("Cannot determine package name; use --package-name or set [project].name in pyproject.toml.") |
| 93 | + |
| 94 | + tests_dir = args.tests or (root / "tests" if (root / "tests").is_dir() else None) |
| 95 | + |
| 96 | + if args.clean: |
| 97 | + for p in (dist, build_dir, root / ".pytest_cache"): |
| 98 | + if p.exists(): |
| 99 | + print(f"Removing {p}") |
| 100 | + shutil.rmtree(p, ignore_errors=True) |
| 101 | + if egg_info and egg_info.exists(): |
| 102 | + print(f"Removing {egg_info}") |
| 103 | + shutil.rmtree(egg_info, ignore_errors=True) |
| 104 | + |
| 105 | + # Build artifacts |
| 106 | + build_cmd = [sys.executable, "-m", "build", "--wheel"] |
| 107 | + if args.sdist: |
| 108 | + build_cmd.append("--sdist") |
| 109 | + build_cmd.append(str(root)) |
| 110 | + run(build_cmd) |
| 111 | + |
| 112 | + wheel = select_best_wheel(dist) |
| 113 | + print(f"Selected wheel: {wheel.name}") |
| 114 | + |
| 115 | + # Optional: extract compiled extension back into source (not recommended) |
| 116 | + if args.extract: |
| 117 | + extract_extension_from_wheel(wheel, root / pkg_name) |
| 118 | + |
| 119 | + # Run tests (if any) |
| 120 | + if tests_dir and tests_dir.exists(): |
| 121 | + cmd = [sys.executable, "-m", "pytest", str(tests_dir)] |
| 122 | + if args.pytest_args: |
| 123 | + cmd = [*cmd, *args.pytest_args] |
| 124 | + run(cmd) |
| 125 | + else: |
| 126 | + print("No tests directory found; skipping pytest.") |
| 127 | + |
| 128 | + print("All done.") |
| 129 | + return 0 |
| 130 | + |
| 131 | +if __name__ == "__main__": |
| 132 | + raise SystemExit(main()) |
0 commit comments