|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from os import chdir, curdir, environ, system as system_call |
| 4 | +from pathlib import Path |
| 5 | +from platform import machine as platform_machine |
| 6 | +from shutil import which |
| 7 | +from sys import platform as sys_platform |
| 8 | +from typing import List, Literal, Optional |
| 9 | + |
| 10 | +from pydantic import BaseModel, Field, field_validator |
| 11 | + |
| 12 | +__all__ = ( |
| 13 | + "HatchRustBuildConfig", |
| 14 | + "HatchRustBuildPlan", |
| 15 | +) |
| 16 | + |
| 17 | +BuildType = Literal["debug", "release"] |
| 18 | +CompilerToolchain = Literal["gcc", "clang", "msvc"] |
| 19 | +Language = Literal["c", "c++"] |
| 20 | +Binding = Literal["cpython", "pybind11", "nanobind", "generic"] |
| 21 | +Platform = Literal["linux", "darwin", "win32"] |
| 22 | + |
| 23 | + |
| 24 | +class HatchRustBuildConfig(BaseModel): |
| 25 | + """Build config values for Hatch Rust Builder.""" |
| 26 | + |
| 27 | + verbose: Optional[bool] = Field(default=False) |
| 28 | + name: Optional[str] = Field(default=None) |
| 29 | + |
| 30 | + module: str = Field(description="Python module name for the Rust extension.") |
| 31 | + path: Optional[Path] = Field(default=None, description="Path to the project root directory.") |
| 32 | + |
| 33 | + target: Optional[str] = Field( |
| 34 | + default=None, |
| 35 | + description="Target platform for the build. If not specified, it will be determined automatically.", |
| 36 | + ) |
| 37 | + |
| 38 | + # Validate path |
| 39 | + @field_validator("path", mode="before") |
| 40 | + @classmethod |
| 41 | + def validate_path(cls, path: Optional[Path]) -> Path: |
| 42 | + if path is None: |
| 43 | + return Path.cwd() |
| 44 | + if not isinstance(path, Path): |
| 45 | + path = Path(path) |
| 46 | + if not path.is_dir(): |
| 47 | + raise ValueError(f"Path '{path}' is not a valid directory.") |
| 48 | + return path |
| 49 | + |
| 50 | + |
| 51 | +class HatchRustBuildPlan(HatchRustBuildConfig): |
| 52 | + build_type: BuildType = "release" |
| 53 | + commands: List[str] = Field(default_factory=list) |
| 54 | + |
| 55 | + def generate(self): |
| 56 | + self.commands = [] |
| 57 | + |
| 58 | + # Construct build command |
| 59 | + platform = environ.get("HATCH_RUST_PLATFORM", sys_platform) |
| 60 | + machine = environ.get("HATCH_RUST_MACHINE", platform_machine()) |
| 61 | + |
| 62 | + build_command = "cargo rustc" |
| 63 | + |
| 64 | + if self.build_type == "release": |
| 65 | + build_command += " --release" |
| 66 | + |
| 67 | + if not self.target: |
| 68 | + if platform == "win32": |
| 69 | + if machine == "x86_64": |
| 70 | + self.target = "x86_64-pc-windows-msvc" |
| 71 | + elif machine == "i686": |
| 72 | + self.target = "i686-pc-windows-msvc" |
| 73 | + elif machine in ("arm64", "aarch64"): |
| 74 | + self.target = "aarch64-pc-windows-msvc" |
| 75 | + else: |
| 76 | + raise ValueError(f"Unsupported machine type: {machine} for Windows platform") |
| 77 | + elif platform == "darwin": |
| 78 | + if machine == "x86_64": |
| 79 | + self.target = "x86_64-apple-darwin" |
| 80 | + elif machine in ("arm64", "aarch64"): |
| 81 | + self.target = "aarch64-apple-darwin" |
| 82 | + else: |
| 83 | + raise ValueError(f"Unsupported machine type: {machine} for macOS platform") |
| 84 | + elif platform == "linux": |
| 85 | + if machine == "x86_64": |
| 86 | + self.target = "x86_64-unknown-linux-gnu" |
| 87 | + elif machine == "i686": |
| 88 | + self.target = "i686-unknown-linux-gnu" |
| 89 | + elif machine in ("arm64", "aarch64"): |
| 90 | + self.target = "aarch64-unknown-linux-gnu" |
| 91 | + else: |
| 92 | + raise ValueError(f"Unsupported machine type: {machine} for Linux platform") |
| 93 | + else: |
| 94 | + raise ValueError(f"Unsupported platform: {platform}") |
| 95 | + build_command += f" --target {self.target}" |
| 96 | + |
| 97 | + if "apple" in build_command: |
| 98 | + build_command += " -- -C link-arg=-undefined -C link-arg=dynamic_lookup" |
| 99 | + |
| 100 | + self.commands.append(build_command) |
| 101 | + |
| 102 | + # Add copy commands after build |
| 103 | + return self.commands |
| 104 | + |
| 105 | + def execute(self): |
| 106 | + """Execute the build commands.""" |
| 107 | + # First navigate to the project path |
| 108 | + |
| 109 | + cwd = Path(curdir).resolve() |
| 110 | + chdir(self.path) |
| 111 | + |
| 112 | + for command in self.commands: |
| 113 | + system_call(command) |
| 114 | + |
| 115 | + # Go back to original path |
| 116 | + chdir(str(cwd)) |
| 117 | + |
| 118 | + # After executing commands, grab the build artifacts in the target directory |
| 119 | + # and copy them to the current directory. |
| 120 | + target_path = Path(self.path) / "target" / self.target / self.build_type |
| 121 | + if not target_path.exists(): |
| 122 | + raise FileNotFoundError(f"Target path '{target_path}' does not exist.") |
| 123 | + if not target_path.is_dir(): |
| 124 | + raise NotADirectoryError(f"Target path '{target_path}' is not a directory.") |
| 125 | + |
| 126 | + platform = environ.get("HATCH_RUST_PLATFORM", sys_platform) |
| 127 | + if platform == "win32": |
| 128 | + files = list(target_path.glob("*.dll")) + list(target_path.glob("*.pyd")) |
| 129 | + elif platform == "linux": |
| 130 | + files = list(target_path.glob("*.so")) |
| 131 | + elif platform == "darwin": |
| 132 | + files = list(target_path.glob("*.dylib")) |
| 133 | + else: |
| 134 | + raise ValueError(f"Unsupported platform machine: {platform_machine()}") |
| 135 | + |
| 136 | + if not files: |
| 137 | + raise FileNotFoundError(f"No build artifacts found in '{target_path}'.") |
| 138 | + |
| 139 | + for file in files: |
| 140 | + if not file.is_file(): |
| 141 | + continue |
| 142 | + |
| 143 | + # Convert the filename to module format |
| 144 | + file_name = file.stem.replace("lib", "", 1) # Remove 'lib' prefix if present |
| 145 | + |
| 146 | + # Copy each file to the current directory |
| 147 | + if sys_platform == "win32": |
| 148 | + copy_command = f"copy {file} {cwd}\\{self.module}\\{file_name}.pyd" |
| 149 | + else: |
| 150 | + if which("cp") is None: |
| 151 | + raise EnvironmentError("cp command not found. Ensure it is installed and available in PATH.") |
| 152 | + copy_command = f"cp -f {file} {cwd}/{self.module}/{file_name}.so" |
| 153 | + print(copy_command) |
| 154 | + system_call(copy_command) |
| 155 | + |
| 156 | + return self.commands |
| 157 | + |
| 158 | + def cleanup(self): |
| 159 | + ... |
| 160 | + # if self.platform.platform == "win32": |
| 161 | + # for temp_obj in Path(".").glob("*.obj"): |
| 162 | + # temp_obj.unlink() |
0 commit comments