76 lines
2.4 KiB
Python
76 lines
2.4 KiB
Python
|
|
"""Bundle Cargo's C ABI library in a platform wheel, without a Python ABI tie."""
|
||
|
|
import json
|
||
|
|
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 setuptools.command.sdist import sdist
|
||
|
|
from wheel.bdist_wheel import bdist_wheel
|
||
|
|
|
||
|
|
|
||
|
|
ROOT = Path(__file__).resolve().parent
|
||
|
|
VERSION = tomllib.loads((ROOT / "Cargo.toml").read_text())["package"]["version"]
|
||
|
|
|
||
|
|
|
||
|
|
def ensure_lockfile():
|
||
|
|
if not (ROOT / "Cargo.lock").is_file():
|
||
|
|
subprocess.run(["cargo", "generate-lockfile"], cwd=ROOT, check=True)
|
||
|
|
|
||
|
|
|
||
|
|
class CargoBuild(build_py):
|
||
|
|
def run(self):
|
||
|
|
ensure_lockfile()
|
||
|
|
super().run()
|
||
|
|
result = subprocess.run(
|
||
|
|
["cargo", "build", "--release", "--lib", "--locked", "--message-format=json"],
|
||
|
|
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"] == "klamath_rs_ext"
|
||
|
|
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:
|
||
|
|
raise RuntimeError("Cargo did not produce the klamath_rs_ext shared library")
|
||
|
|
shutil.copy2(library, Path(self.build_lib) / "klamath_rs_ext" / library.name)
|
||
|
|
|
||
|
|
|
||
|
|
class CargoSdist(sdist):
|
||
|
|
def run(self):
|
||
|
|
ensure_lockfile()
|
||
|
|
super().run()
|
||
|
|
|
||
|
|
|
||
|
|
class NativeDistribution(Distribution):
|
||
|
|
def has_ext_modules(self):
|
||
|
|
return True
|
||
|
|
|
||
|
|
|
||
|
|
class NativeWheel(bdist_wheel):
|
||
|
|
def get_tag(self):
|
||
|
|
# CFFI ABI mode needs the host platform, but no CPython extension ABI.
|
||
|
|
_, _, platform = super().get_tag()
|
||
|
|
return "py3", "none", platform
|
||
|
|
|
||
|
|
|
||
|
|
setup(
|
||
|
|
version=VERSION,
|
||
|
|
distclass=NativeDistribution,
|
||
|
|
cmdclass={"build_py": CargoBuild, "sdist": CargoSdist, "bdist_wheel": NativeWheel},
|
||
|
|
)
|