Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2b4e589
BUG: Stop the Linux module build when the cache download fails
dzenanz Nov 24, 2026
1dee139
BUG: Reject manylinux versions other than _2_28 in the Linux module b…
dzenanz Nov 24, 2026
f7308ef
BUG: Repair Windows module wheels with --lib-paths and oneTBB
dzenanz Nov 24, 2026
d706d83
BUG: Strip the quotes around Windows module CMake options
dzenanz Nov 24, 2026
45540de
BUG: Fail the macOS module build on a bad option or a failed build
dzenanz Nov 24, 2026
8db4fc5
BUG: Exclude --exclude_libs libraries from Linux module wheels
dzenanz Nov 24, 2026
eb67898
BUG: Pass LD_LIBRARY_PATH to the Linux module build container
dzenanz Nov 24, 2026
f956d63
BUG: Run the shell script tests with Git's bash on Windows
dzenanz Nov 24, 2026
945100d
BUG: Compare paths in the config and cgroup tests as Windows writes them
dzenanz Nov 24, 2026
bb386e0
STYLE: Write the 7-Zip candidate paths with single backslashes
dzenanz Nov 24, 2026
7f443a0
BUG: Keep an installed 7-Zip out of the zip fallback test
dzenanz Nov 24, 2026
5985d10
BUG: Start a new Windows cache archive instead of adding to one
dzenanz Nov 24, 2026
f2b826b
BUG: Keep each module build's step report apart from the ITK build's
dzenanz Nov 24, 2026
358f879
BUG: Rebuild when the ITK source has uncommitted changes
dzenanz Nov 24, 2026
90c9857
BUG: Count untracked files in a remote module's state
dzenanz Nov 24, 2026
175c91a
BUG: Rerun the build when the wheel repair or module ITK tree changes
dzenanz Nov 24, 2026
03afff9
BUG: Keep dist/ when --cleanup runs with a build root in the checkout
dzenanz Nov 24, 2026
690fd28
BUG: Derive the ITK version without looking past the ITK tree
dzenanz Nov 24, 2026
5b3a5d5
BUG: Derive the ITK version from local tags when fetching fails
dzenanz Nov 24, 2026
fc40338
BUG: Drop the compiler launcher when rebuilding ITK without the cache
dzenanz Nov 24, 2026
ee4822e
BUG: Default --platform-env to the active manylinux pixi environment
dzenanz Nov 24, 2026
23db78b
BUG: Keep the backslashes of Windows paths in CMAKE_OPTIONS
dzenanz Nov 24, 2026
b53f9e0
BUG: Name a module wheel's init file after its wrapped module
dzenanz Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions docs/Build_ITK_Python_packages.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 ``<build-dir-root>/dist/build_log_<platform-env>.json`` so that a
Step state is persisted to ``<build-dir-root>/dist/build_log_<platform-env>.json``, or
``build_log_<platform-env>_<module>.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``
Expand Down
57 changes: 48 additions & 9 deletions scripts/build_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ``+<hash>``, as they change what is built.
"""
env = os.environ.copy()
# A cache-restored tree must not report an enclosing repository's commit.
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down
22 changes: 21 additions & 1 deletion scripts/build_python_instance_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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()),
Expand All @@ -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()
Expand All @@ -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(
Expand Down
19 changes: 15 additions & 4 deletions scripts/build_wheels.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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="*",
Expand Down Expand Up @@ -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)
)


Expand Down Expand Up @@ -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,
Expand Down
4 changes: 4 additions & 0 deletions scripts/dockcross-manylinux-build-module-wheels.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
;;
--)
Expand Down Expand Up @@ -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}
Expand All @@ -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} \
Expand All @@ -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
Expand Down
15 changes: 15 additions & 0 deletions scripts/linux_build_python_instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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)
Expand Down Expand Up @@ -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")
Expand Down
6 changes: 5 additions & 1 deletion scripts/macpython-download-cache-and-build-module-wheels.sh
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ while [ $# -gt 0 ]; do
shift
break
;;
-*)
echo "Unexpected option: $1."
usage
;;
*)
break
;;
Expand Down Expand Up @@ -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
8 changes: 7 additions & 1 deletion scripts/module_wheel_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,25 @@
from __future__ import annotations

import email.parser
import re
import zipfile
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from pathlib import Path

ITK_INIT = "itk/__init__.py"
_CONFIG = re.compile(r"^itk/Configuration/(?P<module>[^/]+)Config\.py$")


def module_init_name(wheel: Path) -> str:
"""Return the ``itk/__init_<module>__.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"
Expand Down
7 changes: 5 additions & 2 deletions scripts/wheel_builder_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 3 additions & 1 deletion scripts/wheel_packaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <ipp>/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"):
Expand Down
3 changes: 2 additions & 1 deletion scripts/windows-download-cache-and-build-module-wheels.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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..."
Expand Down
Loading
Loading