From 6287cf5dbbc16fde49d1d2858a0c5670428af4ac Mon Sep 17 00:00:00 2001 From: "Hans J. Johnson" Date: Wed, 25 Nov 2026 20:13:18 -0600 Subject: [PATCH 1/8] BUG: Pass a clean LD_LIBRARY_PATH to the Linux module container Each mounted directory was added as ":" onto everything so far, so two directories gave /a:/b:/a: and the value always ended in ":". An empty entry in LD_LIBRARY_PATH means the current directory, so auditwheel searched wherever it was run from. Join the container paths with ":" between them only, and start from an empty value rather than one inherited from the environment. --- scripts/dockcross-manylinux-build-module-wheels.sh | 3 ++- tests/test_module_script_docker_args.py | 13 +++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/scripts/dockcross-manylinux-build-module-wheels.sh b/scripts/dockcross-manylinux-build-module-wheels.sh index 7d93266b..7819d8e8 100755 --- a/scripts/dockcross-manylinux-build-module-wheels.sh +++ b/scripts/dockcross-manylinux-build-module-wheels.sh @@ -153,12 +153,13 @@ for _var in ITK_BUILD_JOBS ITK_BUILD_LOAD_LIMIT ITK_BUILD_LINK_JOBS; do done # Mount shared libraries if LD_LIBRARY_PATH is set +DOCKER_LD_LIBRARY_PATH="" if [[ -n ${LD_LIBRARY_PATH} ]]; then for libpath in ${LD_LIBRARY_PATH//:/ }; do DOCKER_LIBRARY_PATH="/usr/lib64/$(basename -- "${libpath}")" DOCKER_ARGS+=" -v ${libpath}:${DOCKER_LIBRARY_PATH}" if test -d "${libpath}"; then - DOCKER_LD_LIBRARY_PATH+="${DOCKER_LIBRARY_PATH}:${DOCKER_LD_LIBRARY_PATH}" + DOCKER_LD_LIBRARY_PATH="${DOCKER_LD_LIBRARY_PATH:+${DOCKER_LD_LIBRARY_PATH}:}${DOCKER_LIBRARY_PATH}" fi done fi diff --git a/tests/test_module_script_docker_args.py b/tests/test_module_script_docker_args.py index bd028a72..eca641a4 100644 --- a/tests/test_module_script_docker_args.py +++ b/tests/test_module_script_docker_args.py @@ -1,6 +1,7 @@ """What the Linux module script hands to the container runtime.""" import os +import re import shutil import subprocess from pathlib import Path @@ -93,8 +94,12 @@ def test_host_networking_without_container_dns(tmp_path: Path, arch: str) -> Non 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)) + cuda = tmp_path / "cuda-lib64" + cudnn = tmp_path / "cudnn-lib" + cuda.mkdir() + cudnn.mkdir() + monkeypatch.setenv("LD_LIBRARY_PATH", f"{cuda}:{cudnn}:") args = " ".join(_run(tmp_path, arch, "")) - assert "-e LD_LIBRARY_PATH=/usr/lib64/cuda-lib64:" in args + passed = re.search(r"-e LD_LIBRARY_PATH=(\S+)", args) + assert passed is not None + assert passed[1] == "/usr/lib64/cuda-lib64:/usr/lib64/cudnn-lib" From 2187f69c259b50e9e29a7812443c03f5f77e7c11 Mon Sep 17 00:00:00 2001 From: "Hans J. Johnson" Date: Wed, 25 Nov 2026 20:13:47 -0600 Subject: [PATCH 2/8] BUG: Keep every --exclude-libs and --lib-paths when one is repeated The Linux module script turns each -x into its own --exclude-libs, and argparse's nargs=1 kept only the last of them, so all but one library were bundled without a word. --lib-paths had the same shape. Append each occurrence and join them with ";" into the one-element list the builders already take. --- scripts/build_wheels.py | 25 ++++++++++++++++--------- tests/test_cmake_define_args.py | 10 ++++++++++ 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/scripts/build_wheels.py b/scripts/build_wheels.py index c09ebb79..ff47df28 100755 --- a/scripts/build_wheels.py +++ b/scripts/build_wheels.py @@ -340,19 +340,21 @@ def build_argument_parser(os_name: OS, ipp_dir: Path) -> argparse.ArgumentParser ) parser.add_argument( "--lib-paths", - nargs=1, - default="", + action="append", + default=[], help=( - "Windows only: semicolon-delimited library directories for delvewheel to include in module wheel" + "Windows only: semicolon-delimited library directories for delvewheel " + "to include in module wheel; may be repeated" ), ) parser.add_argument( "--exclude-libs", - nargs=1, - default="", + action="append", + default=[], help=( "Windows and Linux: semicolon-delimited library names delvewheel or " - 'auditwheel must not bundle, e.g. "nvcuda.dll" or "libcuda.so.1"' + 'auditwheel must not bundle, e.g. "nvcuda.dll" or "libcuda.so.1"; ' + "may be repeated" ), ) _cmake_options_default = remote_module_build_dict["CMAKE_OPTIONS"] @@ -737,6 +739,11 @@ def configure_linux_target(args: argparse.Namespace) -> TargetPlatform: return target +def semicolon_joined(values: list[str]) -> list[str]: + """Join a repeated option into the one-element list the builders take.""" + return [";".join(values)] if values else [] + + def make_builder( args: argparse.Namespace, os_name: OS, @@ -750,8 +757,8 @@ def make_builder( builder_cls = functools.partial( WindowsBuildPythonInstance, - windows_extra_lib_paths=args.lib_paths, - windows_exclude_libs=args.exclude_libs, + windows_extra_lib_paths=semicolon_joined(args.lib_paths), + windows_exclude_libs=semicolon_joined(args.exclude_libs), ) elif os_name is OS.DARWIN: from macos_build_python_instance import MacOSBuildPythonInstance @@ -761,7 +768,7 @@ def make_builder( from linux_build_python_instance import LinuxBuildPythonInstance builder_cls = functools.partial( - LinuxBuildPythonInstance, exclude_libs=args.exclude_libs + LinuxBuildPythonInstance, exclude_libs=semicolon_joined(args.exclude_libs) ) return builder_cls( platform_env=args.platform_env, diff --git a/tests/test_cmake_define_args.py b/tests/test_cmake_define_args.py index d9b5ce7f..a76cfe74 100644 --- a/tests/test_cmake_define_args.py +++ b/tests/test_cmake_define_args.py @@ -97,3 +97,13 @@ def test_windows_cmake_options_keep_their_backslashes( 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"] + + +def test_repeated_library_options_all_reach_the_builder() -> None: + from build_wheels import semicolon_joined + + args = build_argument_parser(OS.LINUX, Path("IPP")).parse_args( + ["--exclude-libs", "libcuda.so.1", "--exclude-libs", "libnvrtc.so.12"] + ) + assert semicolon_joined(args.exclude_libs) == ["libcuda.so.1;libnvrtc.so.12"] + assert semicolon_joined(args.lib_paths) == [] From a32c92b308a025a244a80c73b0af13fbc3a78a19 Mon Sep 17 00:00:00 2001 From: "Hans J. Johnson" Date: Wed, 25 Nov 2026 20:15:18 -0600 Subject: [PATCH 3/8] BUG: Skip build trees and keep every change in the ITK source state #315 hashed every untracked file in the ITK source into itk_commit, so a build could not reuse one made from different sources. Three cases broke it: - A CMake build tree inside the source, such as an IDE's cmake-build-release/, is untracked unless a .gitignore covers it. It was hashed in full on every run, and since each build rewrites it, ITK rebuilt every time. A directory holding CMakeCache.txt is now skipped. - git lists an untracked nested repository as one "/" entry. Opening it raised IsADirectoryError, which resolved_itk_commit caught and answered with the bare commit, dropping every other change. It now counts by its own HEAD and uncommitted changes. - A dangling symlink or an unreadable file failed the same way; the symlink now counts by its target, the unreadable file by its name. File names are read as bytes, so a name that is not UTF-8 no longer raises UnicodeDecodeError. --- scripts/build_inputs.py | 44 +++++++++++++++++++++++++---- tests/test_build_inputs.py | 58 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+), 6 deletions(-) diff --git a/scripts/build_inputs.py b/scripts/build_inputs.py index c84ab415..3df57640 100644 --- a/scripts/build_inputs.py +++ b/scripts/build_inputs.py @@ -64,7 +64,8 @@ def uncommitted_changes( """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*. + not ignore, except those under a top-level name in *skip* and those in a + CMake build tree, a directory holding ``CMakeCache.txt``. """ diff = subprocess.run( [git, "diff", "HEAD", "--binary"], @@ -81,14 +82,45 @@ def uncommitted_changes( 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()) + names = sorted(os.fsdecode(n) for n in untracked.stdout.split(b"\0") if n) + build_trees = tuple( + name.removesuffix("CMakeCache.txt") + for name in names + if name.endswith("/CMakeCache.txt") + ) + for name in names: + if name.split("/")[0] in skip or name.startswith(build_trees): + continue + digest.update(os.fsencode(name) + b"\0") + digest.update(_untracked_digest(Path(directory) / name, git, env)) return digest.hexdigest() +def _untracked_digest(path: Path, git: str, env: Mapping[str, str]) -> bytes: + """Return what identifies the content of the untracked *path*.""" + if path.is_symlink(): + return os.fsencode(path.readlink()) + if path.is_dir(): + # git lists a nested repository as one entry, "/". + head = subprocess.run( + [git, "rev-parse", "--verify", "HEAD"], + cwd=path, + env=env, + capture_output=True, + check=False, + ) + try: + changes = uncommitted_changes(path, git, env) + except subprocess.CalledProcessError as error: + changes = type(error).__name__ + return head.stdout + changes.encode() + try: + with path.open("rb") as f: + return hashlib.file_digest(f, "sha256").digest() + except OSError as error: + return type(error).__name__.encode() + + 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*. diff --git a/tests/test_build_inputs.py b/tests/test_build_inputs.py index a2e06c80..8df8cad9 100644 --- a/tests/test_build_inputs.py +++ b/tests/test_build_inputs.py @@ -1,7 +1,9 @@ """A run re-runs its steps when the ITK commit, version, or fingerprint changes.""" import functools +import os import subprocess +import sys from collections import OrderedDict from collections.abc import Callable from dataclasses import replace @@ -68,6 +70,62 @@ def test_uncommitted_itk_changes_change_the_commit(itk_source: Path) -> None: assert all(r.startswith(f"{commit}+") for r in (untracked, staged, edited)) +def test_an_untracked_cmake_build_tree_does_not_change_the_commit( + itk_source: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """ITK's .gitignore covers build*/ but not an IDE's cmake-build-*/.""" + monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull) + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path)) + commit = resolved_itk_commit(itk_source, "main") + build_tree = itk_source / "cmake-build-release" + build_tree.mkdir() + (build_tree / "CMakeCache.txt").write_text("CMAKE_BUILD_TYPE:STRING=Release\n") + (build_tree / "itkImage.o").write_bytes(b"\0" * 64) + assert resolved_itk_commit(itk_source, "main") == commit + + +def test_an_untracked_nested_repository_changes_the_commit(itk_source: Path) -> None: + commit = resolved_itk_commit(itk_source, "main") + nested = itk_source / "Modules" / "Remote" / "Foo" + nested.mkdir(parents=True) + _git(nested, "init", "--quiet", "--initial-branch=main") + _git(nested, "config", "user.email", "test@example.com") + _git(nested, "config", "user.name", "Test") + (nested / "itkFoo.h").write_text("// foo\n") + _git(nested, "add", "itkFoo.h") + _git(nested, "commit", "--quiet", "-m", "first") + with_nested = resolved_itk_commit(itk_source, "main") + (nested / "itkFoo.h").write_text("// edited\n") + edited = resolved_itk_commit(itk_source, "main") + assert with_nested.startswith(f"{commit}+") + assert len({commit, with_nested, edited}) == 3 + + +def test_an_unreadable_untracked_file_keeps_the_other_changes( + itk_source: Path, +) -> None: + commit = resolved_itk_commit(itk_source, "main") + (itk_source / "itkNew.h").write_text("// new\n") + try: + (itk_source / "dangling.h").symlink_to(itk_source / "missing.h") + except OSError: + pytest.skip("cannot create a symlink here") + (itk_source / "unreadable.h").write_text("// secret\n") + (itk_source / "unreadable.h").chmod(0) + try: + changed = resolved_itk_commit(itk_source, "main") + finally: + (itk_source / "unreadable.h").chmod(0o644) + assert changed.startswith(f"{commit}+") + + +@pytest.mark.skipif(sys.platform != "linux", reason="file names must be UTF-8 here") +def test_a_file_name_that_is_not_utf8_changes_the_commit(itk_source: Path) -> None: + commit = resolved_itk_commit(itk_source, "main") + (itk_source / os.fsdecode(b"\xff.h")).write_text("// latin-1\n") + assert resolved_itk_commit(itk_source, "main").startswith(f"{commit}+") + + def test_a_tree_without_a_repository_reports_the_requested_revision( tmp_path: Path, ) -> None: From bf5294f2321717729d55eb317042337b7e9e5a81 Mon Sep 17 00:00:00 2001 From: "Hans J. Johnson" Date: Wed, 25 Nov 2026 20:15:59 -0600 Subject: [PATCH 4/8] BUG: Default --platform-env only to an environment that builds wheels #315 took the active pixi environment as the --platform-env default whenever its name held a hyphen, and get_default_platform_build used the same test. An unrelated environment with a hyphen, such as dev-docs, passed the environment guard and failed later as an unknown platform. is_platform_env matches the names that build wheels, -pyNNN, and both places use it. --- scripts/build_wheels.py | 3 ++- scripts/wheel_builder_utils.py | 11 ++++++++++- tests/test_cmake_define_args.py | 10 ++++++++++ tests/test_wheel_builder_utils.py | 17 +++++++++++++++++ 4 files changed, 39 insertions(+), 2 deletions(-) diff --git a/scripts/build_wheels.py b/scripts/build_wheels.py index ff47df28..9a2d1813 100755 --- a/scripts/build_wheels.py +++ b/scripts/build_wheels.py @@ -17,6 +17,7 @@ abort_if_wrong_pixi_environment, compute_itk_package_version, get_default_platform_build, + is_platform_env, resolve_oci_exe, run_command, which_required, @@ -313,7 +314,7 @@ def build_argument_parser(os_name: OS, ipp_dir: Path) -> argparse.ArgumentParser # 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: + if not is_platform_env(default_env): default_env = get_default_platform_build("py311") parser.add_argument( "--platform-env", diff --git a/scripts/wheel_builder_utils.py b/scripts/wheel_builder_utils.py index 206e8d3f..9e1dfff2 100644 --- a/scripts/wheel_builder_utils.py +++ b/scripts/wheel_builder_utils.py @@ -516,6 +516,15 @@ def resolve_oci_exe(env: dict[str, str]) -> str: return "docker" +#: A pixi environment that builds wheels, such as ``manylinux228-py311``. +PLATFORM_ENV_NAME = re.compile(r"(linux|manylinux\d+|macosx|windows)-py\d+") + + +def is_platform_env(name: str) -> bool: + """True when *name* is a pixi environment that builds wheels.""" + return PLATFORM_ENV_NAME.fullmatch(name) is not None + + def get_default_platform_build(default_python_version: str = "py311") -> str: """Return a default ``-`` build identifier. @@ -534,7 +543,7 @@ def get_default_platform_build(default_python_version: str = "py311") -> str: A string like ``'manylinux_2_28-py311'`` or ``'macosx-py311'``. """ from_pixi = os.environ.get("PIXI_ENVIRONMENT_NAME", None) - if from_pixi and "-" in from_pixi: + if from_pixi and is_platform_env(from_pixi): manylinux_pixi_to_pattern_renaming: dict[str, str] = { "manylinux228": "manylinux_2_28", "manylinux234": "manylinux_2_34", diff --git a/tests/test_cmake_define_args.py b/tests/test_cmake_define_args.py index a76cfe74..50764f86 100644 --- a/tests/test_cmake_define_args.py +++ b/tests/test_cmake_define_args.py @@ -107,3 +107,13 @@ def test_repeated_library_options_all_reach_the_builder() -> None: ) assert semicolon_joined(args.exclude_libs) == ["libcuda.so.1;libnvrtc.so.12"] assert semicolon_joined(args.lib_paths) == [] + + +@pytest.mark.parametrize("active", ["dev", "dev-docs", "default", ""]) +def test_an_active_environment_that_builds_nothing_is_not_the_default( + monkeypatch: pytest.MonkeyPatch, active: str +) -> None: + monkeypatch.setenv("PIXI_ENVIRONMENT_NAME", active) + args = build_argument_parser(OS.LINUX, Path("IPP")).parse_args([]) + assert args.platform_env != active + assert args.platform_env.endswith("-py311") diff --git a/tests/test_wheel_builder_utils.py b/tests/test_wheel_builder_utils.py index 51048305..5664ecaa 100644 --- a/tests/test_wheel_builder_utils.py +++ b/tests/test_wheel_builder_utils.py @@ -155,3 +155,20 @@ def test_streamed_output_is_also_returned(capsys: pytest.CaptureFixture[str]) -> assert result.returncode == 0 assert result.stdout.splitlines() == ["line one", "line two"] assert "line one\nline two\n" in capsys.readouterr().out + + +@pytest.mark.parametrize( + ("name", "expected"), + [ + ("manylinux228-py311", True), + ("macosx-py311", True), + ("windows-py311", True), + ("linux-py311", True), + ("dev", False), + ("dev-docs", False), + ("pixi-pycharm", False), + ("", False), + ], +) +def test_is_platform_env(name: str, expected: bool) -> None: + assert wheel_builder_utils.is_platform_env(name) is expected From 3bafae039bb42b5de11400072df87cbcf2bd7da3 Mon Sep 17 00:00:00 2001 From: "Hans J. Johnson" Date: Wed, 25 Nov 2026 20:16:31 -0600 Subject: [PATCH 5/8] BUG: Split Windows CMAKE_OPTIONS without treating backslash as an escape #315 kept the backslashes of Windows paths by doubling every one before shlex.split. Inside single quotes shlex does not unescape, so '-DX=C:\a' arrived as -DX=C:\\a. On Windows, split with a shlex lexer that has no escape character, so backslashes are literal everywhere and quotes still group. Other platforms keep shlex.split's shell rules. --- scripts/build_wheels.py | 16 +++++++++++----- tests/test_cmake_define_args.py | 20 ++++++++++++++++++-- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/scripts/build_wheels.py b/scripts/build_wheels.py index 9a2d1813..c6a3d4e7 100755 --- a/scripts/build_wheels.py +++ b/scripts/build_wheels.py @@ -305,6 +305,16 @@ def default_build_dir_root(ipp_dir: Path, os_name: OS) -> Path: return ipp_dir.parent / "ITKPythonPackage-build" +def split_cmake_options(text: str, os_name: OS) -> list[str]: + """Split ``CMAKE_OPTIONS`` as a shell would, keeping Windows paths' backslashes.""" + lexer = shlex.shlex(text, posix=True) + lexer.whitespace_split = True + lexer.commenters = "" + if os_name is OS.WINDOWS: + lexer.escape = "" + return list(lexer) + + def build_argument_parser(os_name: OS, ipp_dir: Path) -> argparse.ArgumentParser: """Return the command line parser; defaults come from the environment.""" remote_module_build_dict = remotemodulebuildandtestaction() @@ -358,14 +368,10 @@ def build_argument_parser(os_name: OS, ipp_dir: Path) -> argparse.ArgumentParser "may be repeated" ), ) - _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="*", - default=shlex.split(_cmake_options_default) if _cmake_options_default else [], + default=split_cmake_options(remote_module_build_dict["CMAKE_OPTIONS"], os_name), help="Extra options to pass to CMake, e.g. -DBUILD_SHARED_LIBS:BOOL=OFF.\n" " These will override defaults if duplicated", ) diff --git a/tests/test_cmake_define_args.py b/tests/test_cmake_define_args.py index 50764f86..a503bb35 100644 --- a/tests/test_cmake_define_args.py +++ b/tests/test_cmake_define_args.py @@ -94,9 +94,25 @@ def test_the_default_platform_env_is_the_active_manylinux_environment( 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"') + monkeypatch.setenv( + "CMAKE_OPTIONS", + r"""-DA_DIR=C:\deps\a "-DB_DIR=C:\b c" '-DC_DIR=C:\c' -DD_DIR=\\server\d\\""", + ) 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"] + assert args.cmake_options == [ + r"-DA_DIR=C:\deps\a", + r"-DB_DIR=C:\b c", + r"-DC_DIR=C:\c", + "-DD_DIR=\\\\server\\d\\\\", + ] + + +def test_posix_cmake_options_keep_shell_escapes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("CMAKE_OPTIONS", r"-DA=x\ y -DB=1") + args = build_argument_parser(OS.LINUX, Path("IPP")).parse_args([]) + assert args.cmake_options == ["-DA=x y", "-DB=1"] def test_repeated_library_options_all_reach_the_builder() -> None: From e025a9579c3459e5de0cbf01bf53c045b1797724 Mon Sep 17 00:00:00 2001 From: "Hans J. Johnson" Date: Wed, 25 Nov 2026 20:18:14 -0600 Subject: [PATCH 6/8] BUG: Accept several -D options in the Linux and macOS module scripts ITKRemoteModuleBuildTestPackageAction passes its cmake-options input as --cmake_options -DA=1 -DB=2 without quotes. --cmake_options took -DA=1, and both scripts then stopped at -DB=2 as an unexpected option (the macOS one since #315; before, it took -DB=2 for a Python version). Each further -D argument is now added to CMAKE_OPTIONS, so the action works with several options without a change there. The macOS script also looped forever on a trailing --cmake_options with no value, as shift 2 fails without shifting when one argument is left. It now shows usage, as the Linux script does. --- ...-download-cache-and-build-module-wheels.sh | 5 +++ ...-download-cache-and-build-module-wheels.sh | 13 ++++++++ tests/test_module_script_arguments.py | 31 ++++++++++++++----- 3 files changed, 42 insertions(+), 7 deletions(-) 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 36159e48..997ee162 100755 --- a/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh +++ b/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh @@ -85,6 +85,11 @@ while [ $# -gt 0 ]; do python_versions+=("$@") break ;; + -D*) + # The CI action passes "--cmake_options -DA=1 -DB=2" unquoted. + export CMAKE_OPTIONS="${CMAKE_OPTIONS:+${CMAKE_OPTIONS} }$1" + shift + ;; -*) echo "Unexpected option: $1." usage diff --git a/scripts/macpython-download-cache-and-build-module-wheels.sh b/scripts/macpython-download-cache-and-build-module-wheels.sh index 39df56a5..ef69ab00 100755 --- a/scripts/macpython-download-cache-and-build-module-wheels.sh +++ b/scripts/macpython-download-cache-and-build-module-wheels.sh @@ -39,11 +39,19 @@ usage() { exit 2 } +option_value() { + if [ $# -lt 2 ]; then + echo "Option $1 needs a value." + usage + fi +} + CMAKE_OPTIONS="" while [ $# -gt 0 ]; do case "$1" in -h | --help) usage ;; -c | --cmake_options) + option_value "$@" CMAKE_OPTIONS="$2" shift 2 ;; @@ -51,6 +59,11 @@ while [ $# -gt 0 ]; do shift break ;; + -D*) + # The CI action passes "--cmake_options -DA=1 -DB=2" unquoted. + CMAKE_OPTIONS="${CMAKE_OPTIONS:+${CMAKE_OPTIONS} }$1" + shift + ;; -*) echo "Unexpected option: $1." usage diff --git a/tests/test_module_script_arguments.py b/tests/test_module_script_arguments.py index 3d77115b..5288c8e1 100644 --- a/tests/test_module_script_arguments.py +++ b/tests/test_module_script_arguments.py @@ -8,16 +8,16 @@ from tests.bash import BASH -SCRIPT = ( - Path(__file__).resolve().parent.parent - / "scripts" - / "dockcross-manylinux-download-cache-and-build-module-wheels.sh" -) +SCRIPTS = Path(__file__).resolve().parent.parent / "scripts" +SCRIPT = SCRIPTS / "dockcross-manylinux-download-cache-and-build-module-wheels.sh" +MAC_SCRIPT = SCRIPTS / "macpython-download-cache-and-build-module-wheels.sh" pytestmark = pytest.mark.skipif(not BASH, reason="needs bash") -def _run(tmp_path: Path, *args: str) -> subprocess.CompletedProcess[str]: +def _run( + tmp_path: Path, *args: str, script: Path = SCRIPT +) -> subprocess.CompletedProcess[str]: """Run the script up to its first check, with a ``getopt`` that always fails.""" fake_bin = tmp_path / "bin" fake_bin.mkdir(exist_ok=True) @@ -29,11 +29,12 @@ 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, check=False, + timeout=60, ) @@ -67,3 +68,19 @@ def test_bad_options_and_help_show_usage(tmp_path: Path, args: tuple[str, ...]) result = _run(tmp_path, *args) assert "Usage:" in result.stdout assert result.returncode == 2 + + +@pytest.mark.parametrize("script", [SCRIPT, MAC_SCRIPT], ids=["linux", "macos"]) +def test_several_unquoted_cmake_options_are_accepted( + tmp_path: Path, script: Path +) -> None: + """The CI action passes ``--cmake_options -DA=1 -DB=2`` without quotes.""" + result = _run(tmp_path, "--cmake_options", "-DA=1", "-DB=2", "cp311", script=script) + assert "Unexpected option" not in result.stdout + assert result.returncode == 1 + + +def test_a_macos_option_without_its_value_shows_usage(tmp_path: Path) -> None: + result = _run(tmp_path, "--cmake_options", script=MAC_SCRIPT) + assert "needs a value" in result.stdout + assert result.returncode == 2 From feaae0695d14923864aa34616ddad14623693fb1 Mon Sep 17 00:00:00 2001 From: "Hans J. Johnson" Date: Wed, 25 Nov 2026 20:20:54 -0600 Subject: [PATCH 7/8] BUG: Split the Windows module script's options on unquoted spaces only #315 split -cmake_options on every space and trimmed quotes from each piece, so "-DX=C:\a b" became two arguments. -setup_options was split the same way without the trimming, so a quoted --lib-paths directory kept its quotes. An -cmake_options of spaces alone added a bare "--". Split-Options splits both on whitespace outside quotes and removes the quotes, keeping backslashes literal. The new test runs it with PowerShell where one is installed; it passes with Windows PowerShell 5.1 on a Windows builder. --- ...download-cache-and-build-module-wheels.ps1 | 21 ++++-- tests/test_windows_module_script_options.py | 65 +++++++++++++++++++ 2 files changed, 79 insertions(+), 7 deletions(-) create mode 100644 tests/test_windows_module_script_options.py diff --git a/scripts/windows-download-cache-and-build-module-wheels.ps1 b/scripts/windows-download-cache-and-build-module-wheels.ps1 index 7f6f1660..e7ed42b6 100644 --- a/scripts/windows-download-cache-and-build-module-wheels.ps1 +++ b/scripts/windows-download-cache-and-build-module-wheels.ps1 @@ -65,6 +65,16 @@ param ( Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" +# Splits on unquoted whitespace and drops the quotes; backslashes stay literal. +# An unbalanced quote is dropped; the CI action never sends one. +function Split-Options([string]$text) { + $tokens = @() + foreach ($m in [regex]::Matches($text, '(?:"[^"]*"|''[^'']*''|[^\s"'']+)+')) { + $tokens += [regex]::Replace($m.Value, '"([^"]*)"|''([^'']*)''', '$1$2') + } + return $tokens +} + # Validate required inputs if (-not $python_version_minor) { Write-Error "ERROR: -python_version_minor is required. Example: -python_version_minor 11" @@ -287,14 +297,11 @@ $buildArgs += @( "--skip-itk-wheel-build" ) -if ($setup_options.Length -gt 0) { - $buildArgs += $setup_options.Split(" ") -} +$buildArgs += @(Split-Options $setup_options) -if ($cmake_options.Length -gt 0) { - $buildArgs += @("--") - # 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('"') } +$cmakeArgs = @(Split-Options $cmake_options) +if ($cmakeArgs.Count -gt 0) { + $buildArgs += @("--") + $cmakeArgs } echo "Building target module..." diff --git a/tests/test_windows_module_script_options.py b/tests/test_windows_module_script_options.py new file mode 100644 index 00000000..2f1735e0 --- /dev/null +++ b/tests/test_windows_module_script_options.py @@ -0,0 +1,65 @@ +"""How the Windows module script splits -setup_options and -cmake_options.""" + +import json +import os +import re +import shutil +import subprocess +from pathlib import Path + +import pytest + +SCRIPT = ( + Path(__file__).resolve().parent.parent + / "scripts" + / "windows-download-cache-and-build-module-wheels.ps1" +) +POWERSHELL = shutil.which("pwsh") or shutil.which("powershell") + +pytestmark = pytest.mark.skipif(not POWERSHELL, reason="needs PowerShell") + + +def _split(tmp_path: Path, text: str) -> list[str]: + function = re.search( + r"^function Split-Options.*?^}", SCRIPT.read_text(), re.MULTILINE | re.DOTALL + ) + assert function is not None + probe = tmp_path / "probe.ps1" + probe.write_text( + "Set-StrictMode -Version Latest\n" + f"{function[0]}\n" + "ConvertTo-Json -InputObject @(Split-Options $env:SPLIT_OPTIONS_TEXT) -Compress\n" + ) + result = subprocess.run( + [str(POWERSHELL), "-NoProfile", "-NonInteractive", "-File", str(probe)], + env={**os.environ, "SPLIT_OPTIONS_TEXT": text}, + capture_output=True, + text=True, + check=True, + ) + tokens: list[str] = json.loads(result.stdout) + return tokens + + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ('"-DA=1" "-DB=2"', ["-DA=1", "-DB=2"]), + ("-DA=1 -DB=2", ["-DA=1", "-DB=2"]), + ('"-DX=a b" -DZ=1', ["-DX=a b", "-DZ=1"]), + ( + r'-DP="C:\Program Files\x" -DQ=C:\a\b', + [r"-DP=C:\Program Files\x", r"-DQ=C:\a\b"], + ), + (r"'-DS=C:\s'", [r"-DS=C:\s"]), + ( + r'--lib-paths "C:\CUDA\bin" --exclude-libs nvcuda.dll', + ["--lib-paths", r"C:\CUDA\bin", "--exclude-libs", "nvcuda.dll"], + ), + (" ", []), + ], +) +def test_options_split_on_unquoted_spaces_only( + tmp_path: Path, text: str, expected: list[str] +) -> None: + assert _split(tmp_path, text) == expected From e6b36617dae71bb80562b33255e0e32a9163eaf5 Mon Sep 17 00:00:00 2001 From: "Hans J. Johnson" Date: Wed, 25 Nov 2026 20:22:19 -0600 Subject: [PATCH 8/8] ENH: Test three #315 fixes that had no test - The Linux module script stops before downloading when MANYLINUX_VERSION has no ITK caches. - It stops when the cache script cannot be downloaded, instead of running a missing script. - --module-itk-dir enters the build fingerprint. The script tests now run in a temporary directory, so a script that downloads does not write into the checkout. --- tests/test_build_inputs.py | 18 ++++++++++++ tests/test_module_script_arguments.py | 40 ++++++++++++++++++++++++++- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/tests/test_build_inputs.py b/tests/test_build_inputs.py index 8df8cad9..be6d46fc 100644 --- a/tests/test_build_inputs.py +++ b/tests/test_build_inputs.py @@ -273,6 +273,24 @@ def module_source(tmp_path: Path) -> Path: return module +def test_a_new_module_itk_dir_changes_the_fingerprint( + monkeypatch: pytest.MonkeyPatch, + linux_builder: LinuxBuildPythonInstance, + tmp_path: Path, + ipp_dir: Path, + itk_source: Path, + module_source: Path, +) -> None: + _wire_run( + monkeypatch, linux_builder, tmp_path, ipp_dir, itk_source, module=module_source + ) + linux_builder.module_itk_dir = "build" + build = linux_builder.build_inputs() + linux_builder.module_itk_dir = "install" + install = linux_builder.build_inputs() + assert build["fingerprint"] != install["fingerprint"] + + def test_module_state_follows_commits_and_uncommitted_edits( module_source: Path, ) -> None: diff --git a/tests/test_module_script_arguments.py b/tests/test_module_script_arguments.py index 5288c8e1..5a34d8f7 100644 --- a/tests/test_module_script_arguments.py +++ b/tests/test_module_script_arguments.py @@ -2,6 +2,7 @@ import os import subprocess +import sys from pathlib import Path import pytest @@ -16,7 +17,10 @@ def _run( - tmp_path: Path, *args: str, script: Path = SCRIPT + tmp_path: Path, + *args: str, + script: Path = SCRIPT, + extra_env: dict[str, str] | None = None, ) -> subprocess.CompletedProcess[str]: """Run the script up to its first check, with a ``getopt`` that always fails.""" fake_bin = tmp_path / "bin" @@ -27,10 +31,12 @@ def _run( env = { "PATH": f"{fake_bin}{os.pathsep}/usr/bin{os.pathsep}/bin", "MODULE_DEPS_DIR": str(tmp_path / "deps"), + **(extra_env or {}), } return subprocess.run( [BASH, str(script), *args], env=env, + cwd=tmp_path, capture_output=True, text=True, check=False, @@ -84,3 +90,35 @@ def test_a_macos_option_without_its_value_shows_usage(tmp_path: Path) -> None: result = _run(tmp_path, "--cmake_options", script=MAC_SCRIPT) assert "needs a value" in result.stdout assert result.returncode == 2 + + +def test_a_manylinux_version_without_caches_stops_before_downloading( + tmp_path: Path, +) -> None: + result = _run( + tmp_path, + "cp311", + extra_env={"ITK_PACKAGE_VERSION": "v6.0b03", "MANYLINUX_VERSION": "2014"}, + ) + assert "manylinux_2_28 only" in result.stdout + assert "Fetching" not in result.stdout + assert result.returncode == 1 + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Git bash does not find the fake curl on PATH" +) +def test_a_failed_download_stops_the_build(tmp_path: Path) -> None: + fake_bin = tmp_path / "bin" + fake_bin.mkdir() + curl = fake_bin / "curl" + curl.write_text("#!/bin/sh\nexit 22\n") + curl.chmod(0o755) + result = _run( + tmp_path, + "cp311", + extra_env={"ITK_PACKAGE_VERSION": "v6.0b03", "MANYLINUX_VERSION": "_2_28"}, + ) + assert "Fetching" in result.stdout + assert "Running:" not in result.stdout + assert result.returncode == 1