diff --git a/docs/Build_ITK_Python_packages.rst b/docs/Build_ITK_Python_packages.rst index c16468cd..c2191dab 100644 --- a/docs/Build_ITK_Python_packages.rst +++ b/docs/Build_ITK_Python_packages.rst @@ -32,10 +32,12 @@ seven sequential steps: 6. *(optional)* Build a remote module against the ITK build 7. *(optional)* Create a reusable ITK build tarball cache -Step state is persisted to ``/dist/build_log_.json`` so that a +Step state is persisted to ``/dist/build_log_.json``, or +``build_log__.json`` for a remote module, so that a build interrupted part-way through can be resumed by re-running the same command. -The log also records the build's inputs: the ITK commit, the package version, -a fingerprint of the build scripts, CMake settings, and ``pixi.lock``, and for a +The log also records the build's inputs: the ITK commit and its uncommitted +changes, the package version, a fingerprint of the build scripts, CMake +settings, and ``pixi.lock``, and for a remote module its git commit and uncommitted changes. When any of them differs from the recorded run, every step runs again. ``CFLAGS`` and ``CXXFLAGS`` (and ``LDFLAGS`` on Linux and macOS) reach CMake as ``CMAKE_*_FLAGS`` diff --git a/scripts/build_inputs.py b/scripts/build_inputs.py index 146718ba..c84ab415 100644 --- a/scripts/build_inputs.py +++ b/scripts/build_inputs.py @@ -51,11 +51,50 @@ def build_fingerprint(ipp_dir: Path, settings: Mapping[str, str]) -> str: return digest.hexdigest() +#: What `uncommitted_changes` returns for a tree without changes. +NO_CHANGES: str = hashlib.sha256().hexdigest() + + +def uncommitted_changes( + directory: Path, + git: str, + env: Mapping[str, str], + skip: frozenset[str] = frozenset(), +) -> str: + """Return a hash of the uncommitted changes in the repository at *directory*. + + It covers the changes to tracked files and the untracked files git does + not ignore, except those under a top-level name in *skip*. + """ + diff = subprocess.run( + [git, "diff", "HEAD", "--binary"], + cwd=directory, + env=env, + capture_output=True, + check=True, + ) + digest = hashlib.sha256(diff.stdout) + untracked = subprocess.run( + [git, "ls-files", "--others", "--exclude-standard", "-z"], + cwd=directory, + env=env, + capture_output=True, + check=True, + ) + for name in sorted(untracked.stdout.decode().split("\0")): + if name and name.split("/")[0] not in skip: + digest.update(name.encode() + b"\0") + with (Path(directory) / name).open("rb") as f: + digest.update(hashlib.file_digest(f, "sha256").digest()) + return digest.hexdigest() + + def resolved_itk_commit(itk_source_dir: Path, fallback: str, git: str = "git") -> str: """Return the commit checked out in *itk_source_dir*, else *fallback*. A branch name is not enough: the same name builds a new commit each day. A tree restored from a build cache has no repository, hence the fallback. + Uncommitted changes add ``+``, as they change what is built. """ env = os.environ.copy() # A cache-restored tree must not report an enclosing repository's commit. @@ -71,7 +110,14 @@ def resolved_itk_commit(itk_source_dir: Path, fallback: str, git: str = "git") - ) except OSError: return fallback - return result.stdout.strip() if result.returncode == 0 else fallback + if result.returncode != 0: + return fallback + commit = result.stdout.strip() + try: + changes = uncommitted_changes(itk_source_dir, git, env) + except (OSError, subprocess.CalledProcessError): + return commit + return commit if changes == NO_CHANGES else f"{commit}+{changes}" #: Names a module build writes into, or that hold caches, inside a module tree. @@ -105,14 +151,7 @@ def module_source_state(module_dir: Path, git: str = "git") -> str: check=False, ) if head.returncode == 0: - diff = subprocess.run( - [git, "diff", "HEAD", "--binary"], - cwd=module_dir, - env=env, - capture_output=True, - check=True, - ) - changes = hashlib.sha256(diff.stdout).hexdigest() + changes = uncommitted_changes(module_dir, git, env, MODULE_STATE_SKIP) return f"{head.stdout.decode().strip()}+{changes}" except (OSError, subprocess.CalledProcessError): pass diff --git a/scripts/build_python_instance_base.py b/scripts/build_python_instance_base.py index df49a977..c7091ed3 100644 --- a/scripts/build_python_instance_base.py +++ b/scripts/build_python_instance_base.py @@ -291,6 +291,11 @@ def __init__( cache_exe, compiler_cache_max_size(cache_tool, os.environ), ) + elif not self.skip_itk_build: + # A reused ITK build tree keeps the launcher an earlier build cached. + self.cmake_compiler_configurations.update( + compiler_cache_definitions("", "") + ) user_defs = self.cmake_cmdline_definitions flag_defs = self.compiler_flag_definitions(user_defs, compile_roots) @@ -406,7 +411,7 @@ def run(self) -> None: python_package_build_steps = self.build_step_table() self.dist_dir.mkdir(parents=True, exist_ok=True) - build_report_fn: Path = self.dist_dir / f"build_log_{self.platform_env}.json" + build_report_fn: Path = self.build_report_path() build_manager: BuildManager = BuildManager( build_report_fn, list(python_package_build_steps.keys()), @@ -430,6 +435,13 @@ def run(self) -> None: for cmd in cache_after: self.echo_check_call(cmd, use_pixi_env=False) + def build_report_path(self) -> Path: + """Return the step report; each module's is apart from the ITK build's.""" + name = f"build_log_{self.platform_env}" + if self.module_source_dir is not None: + name += f"_{Path(self.module_source_dir).name}" + return self.dist_dir / f"{name}.json" + def build_dependency_module(self, module_source_dir: Path) -> None: """Build the wheel of a dependency module with a copy of this builder.""" dependency_build = self.clone() @@ -449,10 +461,18 @@ def build_inputs(self) -> dict[str, str]: settings.update({f"{group}:{k}": str(v) for k, v in definitions.items()}) for key in ("USE_CCACHE", "MANYLINUX_VERSION", "CONTAINER_SOURCE"): settings[key] = cfg.get(key, "") + # The platform builders' wheel repair options. + for option in ( + "windows_extra_lib_paths", + "windows_exclude_libs", + "exclude_libs", + ): + settings[option] = str(getattr(self, option, "")) git = str(self.config.git_executable) module_state = None if self.module_source_dir is not None: settings["itk_module_deps"] = str(self.itk_module_deps or "") + settings["module_itk_dir"] = self.module_itk_dir module_state = module_source_state(Path(self.module_source_dir), git) return build_inputs( itk_commit=resolved_itk_commit( diff --git a/scripts/build_wheels.py b/scripts/build_wheels.py index 0a1cf4fb..c09ebb79 100755 --- a/scripts/build_wheels.py +++ b/scripts/build_wheels.py @@ -310,9 +310,14 @@ def build_argument_parser(os_name: OS, ipp_dir: Path) -> argparse.ArgumentParser parser = argparse.ArgumentParser( description="Driver script to build ITK Python wheels." ) + # The environment guard requires the active pixi environment itself, which + # get_default_platform_build renames for manylinux. + default_env = os.environ.get("PIXI_ENVIRONMENT_NAME", "") + if "-" not in default_env: + default_env = get_default_platform_build("py311") parser.add_argument( "--platform-env", - default=get_default_platform_build("py311"), + default=default_env, help=( """A platform environment name or path: linux-py311, @@ -346,10 +351,14 @@ def build_argument_parser(os_name: OS, ipp_dir: Path) -> argparse.ArgumentParser nargs=1, default="", help=( - 'Windows only: semicolon-delimited DLL names delvewheel must not bundle, e.g. "nvcuda.dll"' + "Windows and Linux: semicolon-delimited library names delvewheel or " + 'auditwheel must not bundle, e.g. "nvcuda.dll" or "libcuda.so.1"' ), ) _cmake_options_default = remote_module_build_dict["CMAKE_OPTIONS"] + if os_name is OS.WINDOWS: + # shlex takes a backslash for an escape; keep those of Windows paths. + _cmake_options_default = _cmake_options_default.replace("\\", "\\\\") parser.add_argument( "cmake_options", nargs="*", @@ -622,7 +631,7 @@ def sync_itk_source_tree(args: argparse.Namespace, ipp_dir: Path) -> None: # any other value is used as given, as a cache-restored tree has no repository. if derives_package_version(args.itk_package_version): args.itk_package_version = compute_itk_package_version( - args.itk_source_dir, args.itk_git_tag, os.environ + args.itk_source_dir, args.itk_git_tag, itk_git_env(args.itk_source_dir) ) @@ -751,7 +760,9 @@ def make_builder( else: from linux_build_python_instance import LinuxBuildPythonInstance - builder_cls = LinuxBuildPythonInstance + builder_cls = functools.partial( + LinuxBuildPythonInstance, exclude_libs=args.exclude_libs + ) return builder_cls( platform_env=args.platform_env, build_dir_root=args.build_dir_root, diff --git a/scripts/dockcross-manylinux-build-module-wheels.sh b/scripts/dockcross-manylinux-build-module-wheels.sh index 6f57de0b..7d93266b 100755 --- a/scripts/dockcross-manylinux-build-module-wheels.sh +++ b/scripts/dockcross-manylinux-build-module-wheels.sh @@ -163,6 +163,10 @@ if [[ -n ${LD_LIBRARY_PATH} ]]; then done fi export LD_LIBRARY_PATH="${DOCKER_LD_LIBRARY_PATH}" +# auditwheel in the container finds the libraries of mounted directories here. +if [[ -n ${LD_LIBRARY_PATH} ]]; then + DOCKER_ARGS+=" -e LD_LIBRARY_PATH=${LD_LIBRARY_PATH} " +fi # To build tarballs in manylinux, use 'export BUILD_WHEELS_EXTRA_FLAGS=" --build-itk-tarball-cache "' BUILD_WHEELS_EXTRA_FLAGS=${BUILD_WHEELS_EXTRA_FLAGS:=""} # No tarball by default diff --git a/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh b/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh index 79c28441..b5ffb18a 100755 --- a/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh +++ b/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh @@ -42,7 +42,7 @@ usage() { dockcross-manylinux-download-cache-and-build-module-wheels [ -h | --help ] show usage [ -c | --cmake_options ] space-delimited string containing CMake options to forward to the module (e.g. \"-DBUILD_TESTING=OFF\") - [ -x | --exclude_libs ] accepted for compatibility and ignored; nothing excludes libraries from the repair + [ -x | --exclude_libs ] semicolon-delimited library names auditwheel must not bundle (e.g. \"libcuda.so.1\") [ python_version ] build wheel for a specific python version. (e.g. cp311)" exit 2 } @@ -73,11 +73,11 @@ while [ $# -gt 0 ]; do ;; -x | --exclude_libs | -exclude_libs) option_value "$@" - echo "WARNING: --exclude_libs '$2' is ignored; no library is excluded from the wheel repair." + export BUILD_WHEELS_EXTRA_FLAGS="${BUILD_WHEELS_EXTRA_FLAGS} --exclude-libs $2" shift 2 ;; --exclude_libs=* | -exclude_libs=*) - echo "WARNING: --exclude_libs '${1#*=}' is ignored; no library is excluded from the wheel repair." + export BUILD_WHEELS_EXTRA_FLAGS="${BUILD_WHEELS_EXTRA_FLAGS} --exclude-libs ${1#*=}" shift ;; --) @@ -108,6 +108,11 @@ ITK_GIT_TAG=${ITK_GIT_TAG:=${ITK_PACKAGE_VERSION}} # Set default values MANYLINUX_VERSION=${MANYLINUX_VERSION:-_2_28} TARGET_ARCH=${TARGET_ARCH:-x64} +# ITKPythonBuilds has caches for manylinux_2_28 only; manylinux2014 is no longer built. +if [ "${MANYLINUX_VERSION}" != "_2_28" ]; then + echo "ERROR: MANYLINUX_VERSION=${MANYLINUX_VERSION} is not built; module wheels are manylinux_2_28 only." + exit 1 +fi ITKPYTHONPACKAGE_ORG=${ITKPYTHONPACKAGE_ORG:-InsightSoftwareConsortium} ITKPYTHONPACKAGE_TAG=${ITKPYTHONPACKAGE_TAG:-main} @@ -116,7 +121,7 @@ ITKPYTHONPACKAGE_TAG=${ITKPYTHONPACKAGE_TAG:-main} # Download and extract cache echo "Fetching https://raw.githubusercontent.com/${ITKPYTHONPACKAGE_ORG}/ITKPythonPackage/${ITKPYTHONPACKAGE_TAG}/scripts/dockcross-manylinux-download-cache.sh" -curl -L "https://raw.githubusercontent.com/${ITKPYTHONPACKAGE_ORG}/ITKPythonPackage/${ITKPYTHONPACKAGE_TAG}/scripts/dockcross-manylinux-download-cache.sh" -O +curl -fL "https://raw.githubusercontent.com/${ITKPYTHONPACKAGE_ORG}/ITKPythonPackage/${ITKPYTHONPACKAGE_TAG}/scripts/dockcross-manylinux-download-cache.sh" -O || exit 1 chmod u+x dockcross-manylinux-download-cache.sh _download_cmd="ITK_GIT_TAG=${ITK_GIT_TAG} \ ITK_PACKAGE_VERSION=${ITK_PACKAGE_VERSION} \ @@ -127,7 +132,7 @@ _download_cmd="ITK_GIT_TAG=${ITK_GIT_TAG} \ bash -x \ ${download_script_dir}/dockcross-manylinux-download-cache.sh $1" echo "Running: ${_download_cmd}" -eval "${_download_cmd}" +eval "${_download_cmd}" || exit 1 #NOTE: in this scenario, untarred_ipp_dir is extracted from tarball # during ${download_script_dir}/dockcross-manylinux-download-cache.sh diff --git a/scripts/linux_build_python_instance.py b/scripts/linux_build_python_instance.py index d95e8e7e..f26a12b5 100644 --- a/scripts/linux_build_python_instance.py +++ b/scripts/linux_build_python_instance.py @@ -2,6 +2,7 @@ import os import shutil from pathlib import Path +from typing import Any from posix_build_python_instance import PosixBuildPythonInstance from wheel_builder_utils import ( @@ -16,6 +17,14 @@ class LinuxBuildPythonInstance(PosixBuildPythonInstance): Linux-specific compiler/target triple configuration. """ + #: ``--exclude-libs``: libraries ``auditwheel`` must not bundle. + exclude_libs: list[str] | str = "" + + def __init__(self, *, exclude_libs: list[str] | str = "", **kwargs: Any) -> None: + """Take ``--exclude-libs``; the rest are the base's.""" + super().__init__(**kwargs) + self.exclude_libs = exclude_libs + def builds_manylinux(self) -> bool: """True when the wheels are repaired and tagged for manylinux.""" return bool(self.target.manylinux_version) @@ -157,6 +166,12 @@ def fixup_wheel(self, filepath: str, remote_module_wheel: bool = False) -> None: "--plat", self.target.wheel_plat_tag, ] + excludes = self.exclude_libs + if isinstance(excludes, list): + excludes = ";".join(excludes) + for lib in excludes.split(";"): + if lib: + cmd += ["--exclude", lib] cmd += [str(filepath), "-w", str(output_dir)] # Provide LD_LIBRARY_PATH for oneTBB and common system paths extra_lib = str(self._tbb_prefix / "lib") diff --git a/scripts/macpython-download-cache-and-build-module-wheels.sh b/scripts/macpython-download-cache-and-build-module-wheels.sh index 52a36302..39df56a5 100755 --- a/scripts/macpython-download-cache-and-build-module-wheels.sh +++ b/scripts/macpython-download-cache-and-build-module-wheels.sh @@ -51,6 +51,10 @@ while [ $# -gt 0 ]; do shift break ;; + -*) + echo "Unexpected option: $1." + usage + ;; *) break ;; @@ -185,5 +189,5 @@ for py_indicator in "$@"; do --no-use-ccache \ --skip-itk-build \ --skip-itk-wheel-build \ - ${CMAKE_OPTIONS:+-- ${CMAKE_OPTIONS}} + ${CMAKE_OPTIONS:+-- ${CMAKE_OPTIONS}} || exit done diff --git a/scripts/module_wheel_init.py b/scripts/module_wheel_init.py index 7918ed30..10cc078e 100644 --- a/scripts/module_wheel_init.py +++ b/scripts/module_wheel_init.py @@ -9,6 +9,7 @@ from __future__ import annotations import email.parser +import re import zipfile from typing import TYPE_CHECKING @@ -16,12 +17,17 @@ from pathlib import Path ITK_INIT = "itk/__init__.py" +_CONFIG = re.compile(r"^itk/Configuration/(?P[^/]+)Config\.py$") def module_init_name(wheel: Path) -> str: """Return the ``itk/__init___.py`` member ITK runs for *wheel*.""" with zipfile.ZipFile(wheel) as zf: - metadata = next(n for n in zf.namelist() if n.endswith(".dist-info/METADATA")) + names = zf.namelist() + modules = sorted(m["module"] for n in names if (m := _CONFIG.match(n))) + if modules: + return f"itk/__init_{modules[0].lower()}__.py" + metadata = next(n for n in names if n.endswith(".dist-info/METADATA")) name = email.parser.Parser().parsestr(zf.read(metadata).decode())["Name"] module = name.lower().removeprefix("itk-").split("-")[0] return f"itk/__init_{module}__.py" diff --git a/scripts/wheel_builder_utils.py b/scripts/wheel_builder_utils.py index abf460ed..2f96f3e9 100644 --- a/scripts/wheel_builder_utils.py +++ b/scripts/wheel_builder_utils.py @@ -435,8 +435,11 @@ def compute_itk_package_version( env=env, ) if fetch_result.returncode != 0: - msg = f"git fetch --tags failed in {itk_dir}: {fetch_result.stderr}" - raise RuntimeError(msg) + # Offline, the local tags still describe the revision sync_itk_source found. + print( + f"WARNING: git fetch --tags failed in {itk_dir}; describing the " + f"version with the local tags: {fetch_result.stderr}" + ) checkout_result = run_command( ["git", "checkout", itk_git_tag], cwd=itk_dir, diff --git a/scripts/wheel_packaging.py b/scripts/wheel_packaging.py index 944040fd..84264cf7 100644 --- a/scripts/wheel_packaging.py +++ b/scripts/wheel_packaging.py @@ -82,7 +82,9 @@ def rm(tree_path: Path) -> None: # 2) standard build directories for rel in ("ITKPythonPackage", "tools", "_skbuild", "build"): - rm(base / rel) + # A build root inside the checkout, such as /build, holds dist/. + if not build_dir_root.resolve().is_relative_to((base / rel).resolve()): + rm(base / rel) # 3) egg-info folders at top-level for p in base.glob("*.egg-info"): diff --git a/scripts/windows-download-cache-and-build-module-wheels.ps1 b/scripts/windows-download-cache-and-build-module-wheels.ps1 index b09a317c..7f6f1660 100644 --- a/scripts/windows-download-cache-and-build-module-wheels.ps1 +++ b/scripts/windows-download-cache-and-build-module-wheels.ps1 @@ -293,7 +293,8 @@ if ($setup_options.Length -gt 0) { if ($cmake_options.Length -gt 0) { $buildArgs += @("--") - $buildArgs += $cmake_options.Split(" ") + # The CI action quotes each option ("-DA=1" "-DB=2"); the quotes are not part of it. + $buildArgs += $cmake_options.Split(" ", [StringSplitOptions]::RemoveEmptyEntries) | ForEach-Object { $_.Trim('"') } } echo "Building target module..." diff --git a/scripts/windows_build_python_instance.py b/scripts/windows_build_python_instance.py index 8bebf34f..2c8241e0 100644 --- a/scripts/windows_build_python_instance.py +++ b/scripts/windows_build_python_instance.py @@ -28,6 +28,13 @@ "*.pdb", ) +#: Where ``build_tarball`` looks for 7-Zip before ``PATH``. +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"), +) + def _archive_excluded(relative: PurePath) -> bool: """Return True when *relative* matches an ``ARCHIVE_EXCLUDES`` pattern.""" @@ -81,6 +88,10 @@ def python_build_generator_args(self) -> list[str]: def post_build_fixup(self) -> None: """Repair wheels with ``delvewheel``, including oneTBB library paths.""" + self.fixup_wheels(self._delvewheel_lib_paths()) + + def _delvewheel_lib_paths(self) -> str: + """Return the ``--lib-paths`` directories and oneTBB's, semicolon-delimited.""" # append the oneTBB-prefix\\bin directory for fixing wheels built with local oneTBB search_lib_paths = ( [ @@ -92,8 +103,7 @@ def post_build_fixup(self) -> None: else [] ) search_lib_paths.append(str(self._tbb_prefix / "bin")) - search_lib_paths_str: str = ";".join(map(str, search_lib_paths)) - self.fixup_wheels(search_lib_paths_str) + return ";".join(map(str, search_lib_paths)) def fixup_wheels(self, lib_paths: str = "") -> None: """Repair the ``itk_core`` wheels, which link oneTBB.""" @@ -104,7 +114,9 @@ def fixup_wheels(self, lib_paths: str = "") -> None: def fixup_module_wheel(self, filepath: str) -> None: """Repair a remote module's wheel into the module's ``dist/``.""" - self.fixup_wheel(filepath, remote_module_wheel=True) + self.fixup_wheel( + filepath, self._delvewheel_lib_paths(), remote_module_wheel=True + ) def fixup_wheel( self, filepath: str, lib_paths: str = "", remote_module_wheel: bool = False @@ -186,14 +198,8 @@ def build_tarball(self) -> None: self.ipp_dir, ] - 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: + for cand in SEVEN_ZIP_CANDIDATES: if cand.exists(): seven_zip = cand break @@ -204,6 +210,8 @@ def build_tarball(self) -> None: seven_zip = Path(found) if seven_zip is not None: + # "7z a" adds to an existing archive, keeping files since deleted. + out_zip.unlink(missing_ok=True) # No -r: it would match build/ recursively and sweep in a module's tree. cmd = [ str(seven_zip), diff --git a/tests/bash.py b/tests/bash.py new file mode 100644 index 00000000..e5707283 --- /dev/null +++ b/tests/bash.py @@ -0,0 +1,28 @@ +"""The bash that runs the shell script tests.""" + +import os +import shutil +from pathlib import Path + + +def find_bash() -> str: + """Return the path of bash, or an empty string when there is none. + + On Windows, System32\\bash.exe starts WSL, which fails without an + installed distribution, and process creation finds it before PATH; + use the bash that comes with Git for Windows instead. + """ + if os.name != "nt": + return shutil.which("bash") or "" + git = shutil.which("git") + if git is None: + return "" + # git.exe is in cmd/, bin/, or mingw64/bin/ of the Git installation. + for root in Path(git).resolve().parents[1:3]: + bash = root / "bin" / "bash.exe" + if bash.is_file(): + return str(bash) + return "" + + +BASH = find_bash() diff --git a/tests/test_build_config.py b/tests/test_build_config.py index 842d1a7b..fbe49fcc 100644 --- a/tests/test_build_config.py +++ b/tests/test_build_config.py @@ -50,28 +50,33 @@ def _config( return _build(target, env or {}, _args(**overrides)) +def _host_path(path: str) -> str: + """*path* as the host writes it: with backslashes on Windows.""" + return str(Path(path)) + + COMMON_TAIL = [ ("ITK_MODULE_PREQ", ""), ("ITK_MODULE_NO_CLEANUP", "1"), ("USE_CCACHE", "OFF"), ("DEAD_STRIP", "ON"), - ("PIXI_EXECUTABLE", "/px/pixi"), - ("CMAKE_EXECUTABLE", "/env/bin/cmake"), - ("NINJA_EXECUTABLE", "/env/bin/ninja"), - ("DOXYGEN_EXECUTABLE", "/env/bin/doxygen"), - ("GIT_EXECUTABLE", "/env/bin/git"), - ("PYTHON_EXECUTABLE", "/env/bin/python"), + ("PIXI_EXECUTABLE", _host_path("/px/pixi")), + ("CMAKE_EXECUTABLE", _host_path("/env/bin/cmake")), + ("NINJA_EXECUTABLE", _host_path("/env/bin/ninja")), + ("DOXYGEN_EXECUTABLE", _host_path("/env/bin/doxygen")), + ("GIT_EXECUTABLE", _host_path("/env/bin/git")), + ("PYTHON_EXECUTABLE", _host_path("/env/bin/python")), ("OCI_EXE", "docker"), ] def _head(os_name: str, arch: str) -> list[tuple[str, str]]: return [ - ("ITK_SOURCE_DIR", "/bdr/ITK"), - ("IPP_SUPERBUILD_BINARY_DIR", "/bdr/build/ITK-support-bld"), + ("ITK_SOURCE_DIR", _host_path("/bdr/ITK")), + ("IPP_SUPERBUILD_BINARY_DIR", _host_path("/bdr/build/ITK-support-bld")), ("OS_NAME", os_name), ("ARCH", arch), - ("BUILD_DIR_ROOT", "/bdr"), + ("BUILD_DIR_ROOT", _host_path("/bdr")), ("ITK_GIT_TAG", "v6.0b02"), ("ITK_PACKAGE_VERSION", "6.0.0b2"), ] diff --git a/tests/test_build_inputs.py b/tests/test_build_inputs.py index 057d4db7..a2e06c80 100644 --- a/tests/test_build_inputs.py +++ b/tests/test_build_inputs.py @@ -53,6 +53,21 @@ def test_a_branch_name_resolves_to_the_commit_it_builds(itk_source: Path) -> Non assert resolved_itk_commit(itk_source, "main") == after != before +def test_uncommitted_itk_changes_change_the_commit(itk_source: Path) -> None: + """A build of edited sources must not reuse the build of the commit.""" + commit = resolved_itk_commit(itk_source, "main") + new_file = itk_source / "itkNew.h" + new_file.write_text("// new\n") + untracked = resolved_itk_commit(itk_source, "main") + _git(itk_source, "add", "itkNew.h") + staged = resolved_itk_commit(itk_source, "main") + new_file.write_text("// edited\n") + edited = resolved_itk_commit(itk_source, "main") + assert "+" not in commit + assert len({commit, untracked, staged, edited}) == 4 + assert all(r.startswith(f"{commit}+") for r in (untracked, staged, edited)) + + def test_a_tree_without_a_repository_reports_the_requested_revision( tmp_path: Path, ) -> None: @@ -172,6 +187,21 @@ def test_a_new_package_version_runs_every_step_again( assert ran == ["01_superbuild", "02_build_itk", "03_build_wheels"] +def test_new_wheel_repair_options_run_every_step_again( + monkeypatch: pytest.MonkeyPatch, + linux_builder: LinuxBuildPythonInstance, + tmp_path: Path, + ipp_dir: Path, + itk_source: Path, +) -> None: + _wire_run(monkeypatch, linux_builder, tmp_path, ipp_dir, itk_source) + linux_builder.run() + linux_builder.exclude_libs = ["libcuda.so.1"] + ran = _wire_run(monkeypatch, linux_builder, tmp_path, ipp_dir, itk_source) + linux_builder.run() + assert ran == ["01_superbuild", "02_build_itk", "03_build_wheels"] + + @pytest.fixture def module_source(tmp_path: Path) -> Path: module = tmp_path / "ITKFoo" @@ -197,6 +227,13 @@ def test_module_state_follows_commits_and_uncommitted_edits( assert committed not in (first, edited) +def test_a_new_module_file_changes_the_module_state(module_source: Path) -> None: + before = module_source_state(module_source) + (module_source / "include").mkdir() + (module_source / "include" / "itkNew.h").write_text("int a;\n") + assert module_source_state(module_source) != before + + def test_module_state_ignores_what_the_module_build_writes(module_source: Path) -> None: before = module_source_state(module_source) (module_source / "dist").mkdir() diff --git a/tests/test_build_jobs.py b/tests/test_build_jobs.py index bec6bba2..977675a7 100644 --- a/tests/test_build_jobs.py +++ b/tests/test_build_jobs.py @@ -92,7 +92,7 @@ def _fake_open(mapping: Mapping[str, str]) -> Callable[..., IO[str]]: real_open = Path.open def fake(path: Path, *args: Any, **kwargs: Any) -> IO[str]: - key = str(path) + key = path.as_posix() if key in mapping: import io diff --git a/tests/test_build_steps.py b/tests/test_build_steps.py index 1627ecc1..1c2b9229 100644 --- a/tests/test_build_steps.py +++ b/tests/test_build_steps.py @@ -150,3 +150,16 @@ def second() -> object: assert list(skipped) == ["01_a", "02_b_skipped"] assert skipped["01_a"] is first assert skipped["02_b_skipped"]() is None + + +def test_a_module_build_keeps_its_own_step_report( + linux_builder: LinuxBuildPythonInstance, +) -> None: + """A module's inputs differ from ITK's, so a shared report reran every step.""" + builder = _configure(linux_builder) + builder.dist_dir = Path("dist") + assert builder.build_report_path().name == "build_log_manylinux228-py311.json" + builder.module_source_dir = Path("modules") / "BioCell" + assert ( + builder.build_report_path().name == "build_log_manylinux228-py311_BioCell.json" + ) diff --git a/tests/test_cmake_define_args.py b/tests/test_cmake_define_args.py index 0ed8fc4a..d9b5ce7f 100644 --- a/tests/test_cmake_define_args.py +++ b/tests/test_cmake_define_args.py @@ -1,9 +1,11 @@ import argparse from collections.abc import Sequence +from pathlib import Path import pytest -from build_wheels import parse_args_with_cmake_defines +from build_wheels import build_argument_parser, parse_args_with_cmake_defines from cmake_argument_builder import definitions_from_cmake_options +from target_platform import OS def _parser(default: Sequence[str] = ()) -> argparse.ArgumentParser: @@ -78,3 +80,20 @@ def test_options_that_are_not_definitions_are_refused(option: str) -> None: """Anything but a ``-D=`` definition is an error.""" with pytest.raises(ValueError, match="not a -D= definition"): definitions_from_cmake_options(["-DA:BOOL=ON", option]) + + +def test_the_default_platform_env_is_the_active_manylinux_environment( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The environment guard requires exactly the active environment.""" + monkeypatch.setenv("PIXI_ENVIRONMENT_NAME", "manylinux228-py311") + args = build_argument_parser(OS.LINUX, Path("IPP")).parse_args([]) + assert args.platform_env == "manylinux228-py311" + + +def test_windows_cmake_options_keep_their_backslashes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("CMAKE_OPTIONS", r'-DA_DIR=C:\deps\a "-DB_DIR=C:\b c"') + args = build_argument_parser(OS.WINDOWS, Path("IPP")).parse_args([]) + assert args.cmake_options == [r"-DA_DIR=C:\deps\a", r"-DB_DIR=C:\b c"] diff --git a/tests/test_download_cache_archive.py b/tests/test_download_cache_archive.py index 4a86ea44..70bc702b 100644 --- a/tests/test_download_cache_archive.py +++ b/tests/test_download_cache_archive.py @@ -8,6 +8,8 @@ import pytest +from tests.bash import BASH + SCRIPT = ( Path(__file__).resolve().parent.parent / "scripts" @@ -24,7 +26,7 @@ """ pytestmark = pytest.mark.skipif( - shutil.which("bash") is None + not BASH or shutil.which("zstd") is None or shutil.which("unzstd") is None or shutil.which("rsync") is None, @@ -63,7 +65,7 @@ def test_a_local_archive_is_extracted(tmp_path: Path, symlinked: bool) -> None: "TARGET_ARCH": "x64", } result = subprocess.run( - ["bash", str(SCRIPT)], + [BASH, str(SCRIPT)], cwd=work, env=env, capture_output=True, diff --git a/tests/test_itk_source_without_git.py b/tests/test_itk_source_without_git.py index 2b91eb70..7ca78822 100644 --- a/tests/test_itk_source_without_git.py +++ b/tests/test_itk_source_without_git.py @@ -1,5 +1,6 @@ """A cache-restored ITK tree has no .git and must not abort the build.""" +import argparse import subprocess from collections.abc import Mapping, Sequence from pathlib import Path @@ -175,3 +176,15 @@ def not_a_repository( monkeypatch.setattr(wheel_builder_utils, "run_command", not_a_repository) with pytest.raises(RuntimeError, match="Pass --itk-package-version"): wheel_builder_utils.compute_itk_package_version(tmp_path, "v6.0.0", {}) + + +def test_version_derivation_ignores_an_enclosing_repository(tmp_path: Path) -> None: + """A cache-restored tree inside another checkout must not take its version.""" + subprocess.run(["git", "init", "--quiet", str(tmp_path)], check=True) + itk = tmp_path / "restored" / "ITK" + itk.mkdir(parents=True) + args = argparse.Namespace( + itk_source_dir=itk, itk_git_tag="v6.0.0", itk_package_version="gitauto" + ) + with pytest.raises(RuntimeError, match="Pass --itk-package-version"): + build_wheels.sync_itk_source_tree(args, tmp_path) diff --git a/tests/test_module_script_arguments.py b/tests/test_module_script_arguments.py index 38b9a841..3d77115b 100644 --- a/tests/test_module_script_arguments.py +++ b/tests/test_module_script_arguments.py @@ -1,19 +1,20 @@ """Argument parsing of the Linux module script, which also runs on macOS.""" import os -import shutil import subprocess from pathlib import Path import pytest +from tests.bash import BASH + SCRIPT = ( Path(__file__).resolve().parent.parent / "scripts" / "dockcross-manylinux-download-cache-and-build-module-wheels.sh" ) -pytestmark = pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash") +pytestmark = pytest.mark.skipif(not BASH, reason="needs bash") def _run(tmp_path: Path, *args: str) -> subprocess.CompletedProcess[str]: @@ -28,7 +29,7 @@ def _run(tmp_path: Path, *args: str) -> subprocess.CompletedProcess[str]: "MODULE_DEPS_DIR": str(tmp_path / "deps"), } return subprocess.run( - ["bash", str(SCRIPT), *args], + [BASH, str(SCRIPT), *args], env=env, capture_output=True, text=True, diff --git a/tests/test_module_script_docker_args.py b/tests/test_module_script_docker_args.py index 66d2ff0a..bd028a72 100644 --- a/tests/test_module_script_docker_args.py +++ b/tests/test_module_script_docker_args.py @@ -7,9 +7,11 @@ import pytest +from tests.bash import BASH + SCRIPTS = Path(__file__).resolve().parent.parent / "scripts" -pytestmark = pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash") +pytestmark = pytest.mark.skipif(not BASH, reason="needs bash") # Records each argument on its own line. Asked for the dockcross runner # (``run --rm ``), it prints a runner that records its arguments too. @@ -42,10 +44,11 @@ def _run(tmp_path: Path, arch: str, cmake_options: str) -> list[str]: "MODULE_DEPS_DIR": str(tmp_path / "deps"), "CMAKE_OPTIONS": cmake_options, } - if "CONTAINER_DNS" in os.environ: - env["CONTAINER_DNS"] = os.environ["CONTAINER_DNS"] + for name in ("CONTAINER_DNS", "LD_LIBRARY_PATH"): + if name in os.environ: + env[name] = os.environ[name] result = subprocess.run( - ["bash", str(ipp / "scripts" / "dockcross-manylinux-build-module-wheels.sh")], + [BASH, str(ipp / "scripts" / "dockcross-manylinux-build-module-wheels.sh")], env=env, capture_output=True, text=True, @@ -83,3 +86,15 @@ def test_host_networking_without_container_dns(tmp_path: Path, arch: str) -> Non args = " ".join(_run(tmp_path, arch, "")) assert "--network=host" in args assert "--dns" not in args + + +@pytest.mark.skipif(os.name == "nt", reason="a drive letter's colon splits the path") +@pytest.mark.parametrize("arch", ["x64", "aarch64"]) +def test_ld_library_path_reaches_the_container( + tmp_path: Path, arch: str, monkeypatch: pytest.MonkeyPatch +) -> None: + libs = tmp_path / "cuda-lib64" + libs.mkdir() + monkeypatch.setenv("LD_LIBRARY_PATH", str(libs)) + args = " ".join(_run(tmp_path, arch, "")) + assert "-e LD_LIBRARY_PATH=/usr/lib64/cuda-lib64:" in args diff --git a/tests/test_module_wheel_init.py b/tests/test_module_wheel_init.py index 12bda623..1aa8d979 100644 --- a/tests/test_module_wheel_init.py +++ b/tests/test_module_wheel_init.py @@ -20,13 +20,19 @@ def _wheel(path: Path, name: str, members: dict[str, str]) -> Path: return path -def test_the_init_name_comes_from_the_distribution_name(tmp_path: Path) -> None: +def test_the_init_name_falls_back_to_the_distribution_name(tmp_path: Path) -> None: wheel = _wheel(tmp_path / "w.whl", "itk-RTK", {}) assert module_init_name(wheel) == "itk/__init_rtk__.py" wheel = _wheel(tmp_path / "x.whl", "itk-foo-bar", {}) assert module_init_name(wheel) == "itk/__init_foo__.py" +def test_the_init_name_comes_from_the_wrapped_module(tmp_path: Path) -> None: + config = {"itk/Configuration/VkFFTBackendConfig.py": "depends = ()\n"} + wheel = _wheel(tmp_path / "w.whl", "itk-vkfft", config) + assert module_init_name(wheel) == "itk/__init_vkfftbackend__.py" + + def test_a_rename_moves_the_member_and_its_record_line(tmp_path: Path) -> None: wheel = _wheel(tmp_path / "w.whl", "itk-a", {"itk/__init__.py": "x = 1\n"}) assert rename_wheel_member(wheel, "itk/__init__.py", "itk/__init_a__.py") diff --git a/tests/test_platform_builders.py b/tests/test_platform_builders.py index 9c94c52f..387dc977 100644 --- a/tests/test_platform_builders.py +++ b/tests/test_platform_builders.py @@ -254,6 +254,23 @@ def fake_repair(cmd: Sequence[str | Path], env: Mapping[str, str]) -> int: return captured_env +def test_excluded_libraries_go_to_auditwheel_exclude( + tmp_path: Path, linux_builder: LinuxBuildPythonInstance +) -> None: + linux_builder.exclude_libs = ["libcuda.so.1;libnvrtc.so.12"] + wheel, repaired = _prepare_linux_fixup(linux_builder, tmp_path) + commands: list[list[str]] = [] + + def fake_repair(cmd: Sequence[str | Path], env: Mapping[str, str]) -> int: + commands.append([str(c) for c in cmd]) + repaired.touch() + return 0 + + with patch.object(linux_builder, "echo_check_call", side_effect=fake_repair): + linux_builder.fixup_wheel(str(wheel)) + assert " --exclude libcuda.so.1 --exclude libnvrtc.so.12 " in " ".join(commands[0]) + + def test_fixup_wheel_ld_library_path_starts_with_the_build_env_lib_dir( tmp_path: Path, linux_builder: LinuxBuildPythonInstance, @@ -757,7 +774,8 @@ def test_module_wheels_are_repaired_into_the_module_dist( for builder in (linux_builder, windows_builder): with patch.object(builder, "fixup_wheel") as fixed: builder.fixup_module_wheel("mod.whl") - fixed.assert_called_once_with("mod.whl", remote_module_wheel=True) + assert fixed.call_args.args[0] == "mod.whl" + assert fixed.call_args.kwargs == {"remote_module_wheel": True} def test_macos_repairs_module_wheels_in_place( diff --git a/tests/test_require_env_vars.py b/tests/test_require_env_vars.py index 5051d0ee..c8d4f003 100644 --- a/tests/test_require_env_vars.py +++ b/tests/test_require_env_vars.py @@ -1,16 +1,17 @@ -import shutil import subprocess from pathlib import Path import pytest +from tests.bash import BASH + HELPER = Path(__file__).resolve().parent.parent / "scripts" / "require_env_vars.sh" def _run(env: dict[str, str], *names: str) -> subprocess.CompletedProcess[str]: script = f'source "{HELPER}"; require_env_vars {" ".join(names)}; echo reached' return subprocess.run( - ["bash", "-c", script], + [BASH, "-c", script], env={"PATH": "/usr/bin:/bin", **env}, capture_output=True, text=True, @@ -18,7 +19,7 @@ def _run(env: dict[str, str], *names: str) -> subprocess.CompletedProcess[str]: ) -@pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash") +@pytest.mark.skipif(not BASH, reason="needs bash") def test_every_missing_variable_is_reported_before_exiting() -> None: result = _run({"SET": "1", "EMPTY": ""}, "SET", "EMPTY", "UNSET") assert result.returncode == 1 @@ -29,7 +30,7 @@ def test_every_missing_variable_is_reported_before_exiting() -> None: ] -@pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash") +@pytest.mark.skipif(not BASH, reason="needs bash") def test_set_variables_pass() -> None: result = _run({"A": "1", "B": "2"}, "A", "B") assert result.returncode == 0 diff --git a/tests/test_wheel_builder_utils.py b/tests/test_wheel_builder_utils.py index b7fc3a47..eee93a6f 100644 --- a/tests/test_wheel_builder_utils.py +++ b/tests/test_wheel_builder_utils.py @@ -113,22 +113,23 @@ def fake_run( assert version.startswith("6.0") -def test_compute_itk_package_version_raises_when_fetch_fails(tmp_path: Path) -> None: +def test_compute_itk_package_version_works_offline(tmp_path: Path) -> None: + """sync_itk_source accepts a failed fetch when the revision is present.""" + def fake_run( cmd: Sequence[str | Path], cwd: Path | None = None, env: Mapping[str, str] | None = None, check: bool = False, ) -> subprocess.CompletedProcess[str]: - if str(cmd[1]) == "rev-parse" and "--git-dir" in [str(c) for c in cmd]: - return _completed(0, ".git") - return _completed(1, "", "network down") + if str(cmd[1]) == "fetch": + return _completed(1, "", "network down") + if str(cmd[1]) == "describe": + return _completed(0, "v6.0.0-0-gabc1234") + return _completed(0, ".git") - with ( - patch.object(wheel_builder_utils, "run_command", fake_run), - pytest.raises(RuntimeError, match="git fetch"), - ): - compute_itk_package_version(tmp_path, "v6.0.0", {}) + with patch.object(wheel_builder_utils, "run_command", fake_run): + assert compute_itk_package_version(tmp_path, "v6.0.0", {}) == "6.0.0" def test_streamed_output_is_also_returned(capsys: pytest.CaptureFixture[str]) -> None: diff --git a/tests/test_wheel_packaging.py b/tests/test_wheel_packaging.py index 0eb370db..3b1cfea9 100644 --- a/tests/test_wheel_packaging.py +++ b/tests/test_wheel_packaging.py @@ -37,6 +37,15 @@ def _run_cleanup(build_root: Path, arch: str) -> set[str]: return survivors +def test_cleanup_keeps_a_build_root_inside_the_checkout(tmp_path: Path) -> None: + """--build-dir-root /build must not lose its wheels.""" + build_root = tmp_path / "build" + (build_root / "dist").mkdir(parents=True) + (build_root / "dist" / "itk_core-6.0.0-cp311-abi3.whl").touch() + post_build_cleanup(build_root, "x64", tmp_path, "") + assert (build_root / "dist" / "itk_core-6.0.0-cp311-abi3.whl").exists() + + def test_cleanup_selects_build_dirs_and_archives(tmp_path: Path) -> None: (tmp_path / "build").mkdir() (tmp_path / "dist").mkdir() diff --git a/tests/test_windows_wheel_builder.py b/tests/test_windows_wheel_builder.py index f063b7a7..d99541be 100644 --- a/tests/test_windows_wheel_builder.py +++ b/tests/test_windows_wheel_builder.py @@ -118,6 +118,17 @@ def test_a_module_wheel_never_ships_itk_init( assert "itk/__init_biocell__.py," in record +def test_a_module_wheel_is_repaired_with_lib_paths_and_onetbb( + windows_builder: WindowsBuildPythonInstance, +) -> None: + """delvewheel looks for a module's DLLs where it looks for itk-core's.""" + windows_builder.windows_extra_lib_paths = ["C:/CUDA/bin"] + with patch.object(windows_builder, "fixup_wheel") as fixup: + windows_builder.fixup_module_wheel("module.whl") + tbb_bin = str(windows_builder.build_dir_root / "build" / "oneTBB-prefix" / "bin") + assert fixup.call_args.args[1] == f"C:/CUDA/bin;{tbb_bin}" + + def test_non_remote_repaired_wheel_lands_in_the_build_dist( tmp_path: Path, windows_builder: WindowsBuildPythonInstance ) -> None: @@ -252,6 +263,15 @@ def test_seven_zip_archives_absolute_roots_not_bare_names( assert str(windows_builder.ipp_dir) in cmd +def test_seven_zip_starts_a_new_archive( + tmp_path: Path, windows_builder: WindowsBuildPythonInstance +) -> None: + stale = windows_builder.build_dir_root / "ITKPythonBuilds-windows.zip" + stale.write_text("an archive from an earlier build") + _run_build_tarball(windows_builder, tmp_path) + assert not stale.exists() + + def test_zip_fallback_archives_the_seven_zip_roots( tmp_path: Path, windows_builder: WindowsBuildPythonInstance ) -> None: @@ -274,6 +294,7 @@ def test_zip_fallback_archives_the_seven_zip_roots( path.write_text("x") with ( + patch("windows_build_python_instance.SEVEN_ZIP_CANDIDATES", ()), patch("windows_build_python_instance.shutil.which", return_value=None), patch.object(windows_builder, "echo_check_call") as call, ):