Repository navigation
Expand file tree
/
Copy pathwindows_build_python_instance.py
More file actions
305 lines (264 loc) · 10.6 KB
/
Copy pathwindows_build_python_instance.py
File metadata and controls
305 lines (264 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
from __future__ import annotations
import copy
from pathlib import Path
from os import environ
from build_python_instance_base import BuildPythonInstanceBase
from wheel_builder_utils import echo_check_call, push_dir, _remove_tree
class WindowsBuildPythonInstance(BuildPythonInstanceBase):
def clone(self):
# Pattern for generating a deep copy of the current object state as a new build instance
cls = self.__class__
new = cls.__new__(cls)
new.__dict__ = copy.deepcopy(self.__dict__)
return new
def prepare_build_env(self) -> None:
# Windows
# #############################################
# ### Setup build tools
self._build_type = "Release"
self._use_tbb: str = "ON"
self._tbb_dir = self.IPP_SOURCE_DIR / "oneTBB-prefix" / "lib" / "cmake" / "TBB"
self._cmake_executable = "cmake.exe"
self.venv_paths()
self.update_venv_itk_build_configurations()
self.cmake_compiler_configurations.update(
{
"CMAKE_MAKE_PROGRAM:FILEPATH": f"{self.venv_info_dict['ninja_executable']}",
}
)
self.cmake_itk_source_build_configurations.set(
"ITK_BINARY_DIR:PATH", str(self.IPP_SOURCE_DIR / f"ITK-win_{self.py_env}")
)
def post_build_fixup(self) -> None:
# append the oneTBB-prefix\\bin directory for fixing wheels built with local oneTBB
search_lib_paths = (
[s for s in str(self.windows_extra_lib_paths[0]).rstrip(";") if s]
if self.windows_extra_lib_paths
else []
)
search_lib_paths.append(str(self.IPP_SOURCE_DIR / "oneTBB-prefix" / "bin"))
search_lib_paths_str: str = ";".join(map(str, search_lib_paths))
self.fixup_wheels(search_lib_paths_str)
def post_build_cleanup(self) -> None:
"""Clean Windows build artifacts (leave dist/ intact).
Mirrors the intent of dockcross-manylinux-cleanup.sh for Windows:
- remove oneTBB-prefix (symlink/dir)
- remove ITKPythonPackage/, tools/, _skbuild/, build/
- remove top-level *.egg-info
- remove ITK-win_* build trees
- remove ITKPythonBuilds-win*.tar.zst if present
- remove any module prereq clones from ITK_MODULE_PREQ env/config
"""
base = Path(self.IPP_SOURCE_DIR)
def rm(p: Path):
try:
_remove_tree(p)
except Exception:
pass
# oneTBB-prefix
tbb = base / "oneTBB-prefix"
try:
if tbb.is_symlink() or tbb.is_file():
tbb.unlink(missing_ok=True) # type: ignore[arg-type]
elif tbb.exists():
rm(tbb)
except Exception:
pass
# Common build dirs
for rel in ("ITKPythonPackage", "tools", "_skbuild", "build"):
rm(base / rel)
# egg-info
for p in base.glob("*.egg-info"):
rm(p)
# ITK build tree(s)
for p in base.glob("ITK-win_*"):
rm(p)
# Tarballs (if used on Windows)
for p in base.glob("ITKPythonBuilds-win*.tar.zst"):
rm(p)
# Module prerequisites
itk_preq = self.package_env_config.get("ITK_MODULE_PREQ") or environ.get(
"ITK_MODULE_PREQ", ""
)
if itk_preq:
for entry in itk_preq.split(":"):
entry = entry.strip()
if not entry:
continue
try:
module_name = entry.split("@", 1)[0].split("/", 1)[1]
except Exception:
continue
rm(base / module_name)
def final_import_test(self) -> None:
self._final_import_test_fn(self.py_env, Path(self.dist_dir))
def fixup_wheel(self, filepath, lib_paths: str = "") -> None:
# Windows fixup_wheel
lib_paths = lib_paths.strip()
lib_paths = (
lib_paths + ";" if lib_paths else ""
) + "C:/P/IPP/oneTBB-prefix/bin"
print(f"Library paths for fixup: {lib_paths}")
delve_wheel = (
self.IPP_SOURCE_DIR / f"venv-{self.py_env}" / "Scripts" / "delvewheel.exe"
)
cmd = [
str(delve_wheel),
"repair",
"--no-mangle-all",
"--add-path",
lib_paths,
"--ignore-in-wheel",
"-w",
str(self.IPP_SOURCE_DIR / "dist"),
str(filepath),
]
echo_check_call(cmd)
def venv_paths(self) -> None:
# Create venv related paths
venv_executable = f"C:/Python{self.py_env}/Scripts/virtualenv.exe"
venv_base_dir = Path(self.ITK_SOURCE_DIR) / f"venv-{self.py_env}"
if not venv_base_dir.exists():
echo_check_call([venv_executable, str(venv_base_dir)])
local_pip_executable = venv_base_dir / "Scripts" / "pip.exe"
# Install required tools into each venv
self._pip_uninstall_itk_wildcard(self.venv_info_dict["pip_executable"])
echo_check_call([local_pip_executable, "install", "--upgrade", "pip"])
echo_check_call(
[
local_pip_executable,
"install",
"--upgrade",
"build",
"ninja",
"numpy",
"scikit-build-core",
# os-specific tools below
"delvewheel",
"pkginfo",
]
)
# Install dependencies
echo_check_call(
[
local_pip_executable,
"install",
"--upgrade",
"-r",
str(self.IPP_SOURCE_DIR / "requirements-dev.txt"),
]
)
pip_executable = venv_base_dir / "Scripts" / "pip.exe"
python_executable = venv_base_dir / "Scripts" / "python.exe"
python_include_dir = f"C:/Python{self.py_env}/include"
# XXX It should be possible to query skbuild for the library dir associated
# with a given interpreter.
xy_ver = self.py_env.split("-")[0]
if int(self.py_env.split("-")[0][1:]) >= 11:
# Stable ABI
python_library = f"C:/Python{self.py_env}/libs/python3.lib"
else:
python_library = f"C:/Python{self.py_env}/libs/python{xy_ver}.lib"
# Update PATH
venv_bin_path = venv_base_dir / "Scripts"
ninja_executable = venv_bin_path / "ninja.exe"
self.venv_info_dict = {
"python_executable": python_executable,
"python_include_dir": python_include_dir,
"python_library": python_library,
"pip_executable": pip_executable,
"ninja_executable": ninja_executable,
"venv_bin_path": venv_bin_path,
"venv_base_dir": venv_base_dir,
}
def build_tarball(self):
"""Create an archive of the ITK Python package build tree (Windows).
Mirrors scripts/windows-build-tarball.ps1 behavior:
- Remove contents of IPP\dist
- Use 7-Zip, when present, to archive the full IPP tree into
ITKPythonBuilds-windows.zip at the parent directory of IPP (e.g., C:\P)
- Fallback to Python's zip archive creation if 7-Zip is unavailable
"""
ipp_dir = Path(self.IPP_SOURCE_DIR)
base_dir = ipp_dir.parent # e.g., C:\P
out_zip = base_dir / "ITKPythonBuilds-windows.zip"
# 1) Clean IPP/dist contents (do not remove the directory itself)
dist_dir = ipp_dir / "dist"
if dist_dir.exists():
for p in dist_dir.glob("*"):
try:
if p.is_dir():
# shutil.rmtree alternative without importing here
for sub in p.rglob("*"):
# best-effort clean
try:
if sub.is_file() or sub.is_symlink():
sub.unlink(missing_ok=True)
except Exception:
pass
try:
p.rmdir()
except Exception:
pass
else:
p.unlink(missing_ok=True)
except Exception:
# best-effort cleanup; ignore errors to continue packaging
pass
# 2) Try to use 7-Zip if available
seven_zip_candidates = [
Path(r"C:\\7-Zip\\7z.exe"),
Path(r"C:\\Program Files\\7-Zip\\7z.exe"),
Path(r"C:\\Program Files (x86)\\7-Zip\\7z.exe"),
]
seven_zip = None
for cand in seven_zip_candidates:
if cand.exists():
seven_zip = cand
break
if seven_zip is None:
# Try PATH lookup using where/which behavior from shutil
import shutil as _shutil
found = _shutil.which("7z.exe") or _shutil.which("7z")
if found:
seven_zip = Path(found)
if seven_zip is not None:
# Match the PS1: run from C:\P and create archive of IPP directory
with push_dir(base_dir):
# Using -t7z in the PS1 but naming .zip; preserve behavior
cmd = [
str(seven_zip),
"a",
"-t7z",
"-r",
str(out_zip),
"-w",
str(ipp_dir),
]
echo_check_call(cmd)
return
# 3) Fallback: create a .zip using Python's shutil
# This will create a zip archive named ITKPythonBuilds-windows.zip
import shutil as _shutil
if out_zip.exists():
try:
out_zip.unlink()
except Exception:
pass
# make_archive requires base name without extension
base_name = str(out_zip.with_suffix("").with_suffix(""))
# shutil.make_archive will append .zip
_shutil.make_archive(
base_name, "zip", root_dir=str(base_dir), base_dir=str(ipp_dir.name)
)
def discover_python_venvs(
self, platform_os_name: str, platform_architechure: str
) -> list[str]:
default_py_envs = [
f"39-{platform_architechure}",
f"310-{platform_architechure}",
f"311-{platform_architechure}",
]
return default_py_envs
def _final_import_test_fn(self, py_env, param):
pass