Skip to content
44 changes: 38 additions & 6 deletions scripts/build_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand All @@ -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, "<name>/".
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*.

Expand Down
44 changes: 29 additions & 15 deletions scripts/build_wheels.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -304,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()
Expand All @@ -313,7 +324,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",
Expand All @@ -340,29 +351,27 @@ 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"]
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",
)
Expand Down Expand Up @@ -737,6 +746,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,
Expand All @@ -750,8 +764,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
Expand All @@ -761,7 +775,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,
Expand Down
3 changes: 2 additions & 1 deletion scripts/dockcross-manylinux-build-module-wheels.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions scripts/macpython-download-cache-and-build-module-wheels.sh
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,31 @@ 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
;;
--)
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
Expand Down
11 changes: 10 additions & 1 deletion scripts/wheel_builder_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ``<platform>-<python>`` build identifier.

Expand All @@ -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",
Expand Down
21 changes: 14 additions & 7 deletions scripts/windows-download-cache-and-build-module-wheels.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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"'']+)+')) {
Comment thread
hjmjohnson marked this conversation as resolved.
Resolved
$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"
Expand Down Expand Up @@ -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..."
Expand Down
76 changes: 76 additions & 0 deletions tests/test_build_inputs.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -215,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:
Expand Down
Loading
Loading