79 lines
2.8 KiB
Python
79 lines
2.8 KiB
Python
"""Bundle Cargo's C ABI library in a platform wheel, without a Python ABI tie."""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tomllib
|
|
|
|
from setuptools import Distribution, setup
|
|
from setuptools.command.build_py import build_py
|
|
from wheel.bdist_wheel import bdist_wheel
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parent
|
|
VERSION = tomllib.loads((ROOT / "Cargo.toml").read_text())["package"]["version"]
|
|
BUILD_TARGET = os.environ.get("PHEON_BUILD_TARGET")
|
|
WINDOWS_TARGET = "x86_64-pc-windows-gnu"
|
|
|
|
if BUILD_TARGET is not None and BUILD_TARGET != WINDOWS_TARGET:
|
|
raise ValueError(f"PHEON_BUILD_TARGET must be {WINDOWS_TARGET}, got {BUILD_TARGET!r}")
|
|
|
|
|
|
if not (ROOT / "Cargo.lock").is_file():
|
|
raise FileNotFoundError("Source builds require the supplied Cargo.lock")
|
|
|
|
|
|
class CargoBuild(build_py):
|
|
def run(self):
|
|
super().run()
|
|
command = ["cargo", "build", "--release", "--lib", "--locked", "--message-format=json"]
|
|
if BUILD_TARGET:
|
|
command.extend(["--target", BUILD_TARGET])
|
|
result = subprocess.run(
|
|
command,
|
|
cwd=ROOT, capture_output=True, text=True,
|
|
)
|
|
sys.stderr.write(result.stderr)
|
|
library = None
|
|
for line in result.stdout.splitlines():
|
|
try:
|
|
message = json.loads(line)
|
|
except json.JSONDecodeError:
|
|
print(line, file=sys.stderr)
|
|
continue
|
|
if message.get("reason") == "compiler-message":
|
|
sys.stderr.write(message["message"].get("rendered") or "")
|
|
if (message.get("reason") == "compiler-artifact"
|
|
and message["target"]["name"] == "pheon"
|
|
and "cdylib" in message["target"]["crate_types"]):
|
|
for filename in message["filenames"]:
|
|
if Path(filename).suffix in (".so", ".dylib", ".dll"):
|
|
library = Path(filename)
|
|
result.check_returncode()
|
|
if library is None or (BUILD_TARGET and library.name != "pheon.dll"):
|
|
raise RuntimeError("Cargo did not produce the expected Pheon shared library")
|
|
shutil.copy2(library, Path(self.build_lib) / "pheon" / library.name)
|
|
|
|
|
|
class NativeDistribution(Distribution):
|
|
def has_ext_modules(self):
|
|
return True
|
|
|
|
|
|
class NativeWheel(bdist_wheel):
|
|
def get_tag(self):
|
|
# CFFI ABI mode needs a platform tag and no CPython extension ABI.
|
|
if BUILD_TARGET == WINDOWS_TARGET:
|
|
return "py3", "none", "win_amd64"
|
|
_, _, platform = super().get_tag()
|
|
return "py3", "none", platform
|
|
|
|
|
|
setup(
|
|
version=VERSION,
|
|
distclass=NativeDistribution,
|
|
cmdclass={"build_py": CargoBuild, "bdist_wheel": NativeWheel},
|
|
options={"build": {"build_base": f"build/{BUILD_TARGET}"}} if BUILD_TARGET else {},
|
|
)
|