diff --git a/python/private/pypi/BUILD.bazel b/python/private/pypi/BUILD.bazel index c5331fd899..e9bf8c3b46 100644 --- a/python/private/pypi/BUILD.bazel +++ b/python/private/pypi/BUILD.bazel @@ -16,6 +16,7 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") load("//python:py_binary.bzl", "py_binary") load("//python:py_library.bzl", "py_library") load("//python/private:distribution_filegroup.bzl", "distribution_filegroup") +load("//python/private:py_interpreter_program.bzl", "py_interpreter_program") package(default_visibility = ["//:__subpackages__"]) @@ -26,6 +27,28 @@ exports_files( visibility = ["//visibility:public"], ) +filegroup( + name = "sdist_wheel_builder_helpers", + srcs = ["sdist_wheel_helpers.py"], +) + +py_interpreter_program( + name = "sdist_wheel_builder", + interpreter_args = ["-B"], + main = "sdist_wheel_builder.py", + visibility = ["//visibility:public"], +) + +py_library( + name = "sdist_wheel_builder_lib", + srcs = [ + "sdist_wheel_builder.py", + "sdist_wheel_helpers.py", + ], + imports = ["."], + visibility = ["//tests:__subpackages__"], +) + py_library( name = "rewriters_lib", srcs = [ @@ -715,6 +738,24 @@ bzl_library( srcs = ["platform.bzl"], ) +bzl_library( + name = "py_sdist_wheel", + srcs = ["py_sdist_wheel.bzl"], + deps = [ + "//python/private:attr_builders", + "//python/private:attributes", + "//python/private:builders", + "//python/private:common", + "//python/private:normalize_name", + "//python/private:py_info", + "//python/private:py_interpreter_program", + "//python/private:reexports", + "//python/private:rule_builders", + "//python/private:toolchain_types", + "//python/private:version", + ], +) + bzl_library( name = "python_tag", srcs = ["python_tag.bzl"], diff --git a/python/private/pypi/py_sdist_wheel.bzl b/python/private/pypi/py_sdist_wheel.bzl new file mode 100644 index 0000000000..0f14d06045 --- /dev/null +++ b/python/private/pypi/py_sdist_wheel.bzl @@ -0,0 +1,431 @@ +"""Rule for building a Python wheel (.whl) from an sdist archive in a Bazel build action.""" + +load("//python/private:attr_builders.bzl", "attrb") +load("//python/private:attributes.bzl", "REQUIRED_EXEC_GROUP_BUILDERS") +load("//python/private:builders.bzl", "builders") +load("//python/private:common.bzl", "actions_run") +load("//python/private:normalize_name.bzl", "normalize_name") +load("//python/private:py_info.bzl", "PyInfo", "VenvSymlinkKind") +load("//python/private:py_interpreter_program.bzl", "PyInterpreterProgramInfo") +load("//python/private:reexports.bzl", "BuiltinPyInfo") +load("//python/private:rule_builders.bzl", "ruleb") +load( + "//python/private:toolchain_types.bzl", + "EXEC_TOOLS_TOOLCHAIN_TYPE", + "TARGET_TOOLCHAIN_TYPE", +) +load("//python/private:version.bzl", "version") + +PyBuiltWheelInfo = provider( + doc = """ +Information about a wheel built in a build action. + +:::{versionadded} VERSION_NEXT_FEATURE +::: +""", + fields = { + "directory": """ +:type: File + +The `.whldir` directory artifact (`TreeArtifact`) containing the built `.whl` file +with its canonical PEP 427 filename. +""", + "distribution": """ +:type: str + +The normalized Python distribution name (e.g. `foo_bar`). +""", + "version": """ +:type: str + +The normalized PEP 440 version string (e.g. `1.2.3`). +""", + }, +) + +BOOTSTRAP_BUILD_PACKAGES = { + "build": True, + "installer": True, + "more_itertools": True, + "packaging": True, + "pip": True, + "pyproject_hooks": True, + "setuptools": True, + "tomli": True, + "wheel": True, +} + +_BOOTSTRAP_DEPS = [ + Label("@pypi__" + k + "//:lib") + for k in BOOTSTRAP_BUILD_PACKAGES +] + +_BOOTSTRAP_REPO_NAMES = { + dep_label.repo_name: True + for dep_label in _BOOTSTRAP_DEPS +} + +_PLATFORM_CONSTRAINTS = { + Label("@platforms//cpu:aarch32"): "cpu=arm", + Label("@platforms//cpu:aarch64"): "cpu=aarch64", + Label("@platforms//cpu:arm64e"): "cpu=aarch64", + Label("@platforms//cpu:armv7"): "cpu=arm", + Label("@platforms//cpu:i386"): "cpu=x86_32", + Label("@platforms//cpu:ppc"): "cpu=ppc", + Label("@platforms//cpu:ppc64le"): "cpu=ppc", + Label("@platforms//cpu:riscv64"): "cpu=riscv64", + Label("@platforms//cpu:s390x"): "cpu=s390x", + Label("@platforms//cpu:x86_32"): "cpu=x86_32", + Label("@platforms//cpu:x86_64"): "cpu=x86_64", + Label("@platforms//os:linux"): "os=linux", + Label("@platforms//os:macos"): "os=macos", + Label("@platforms//os:windows"): "os=windows", +} + +PY_SDIST_WHEEL_ATTRS = { + "add_libdir_to_library_search_path": lambda: attrb.Bool( + default = False, + doc = """ +If True, adds `-L/lib` for the build Python interpreter to `LDFLAGS`. +""", + ), + "build_deps": lambda: attrb.LabelList( + cfg = "exec", + default = [], + doc = """ +Additional build-time Python package dependencies (PEP 517 `build-system.requires`), +evaluated in the `exec` configuration. To satisfy version constraints that conflict +with the default bootstrap packages (e.g. `setuptools<70`), add the pinned package +to `build_deps`; it takes precedence. +""", + ), + "builder": lambda: attrb.Label( + cfg = "exec", + default = Label("//python/private/pypi:sdist_wheel_builder"), + doc = """ +Executable tool that builds a wheel from an sdist into a `.whldir` directory. +""", + ), + "config_settings": lambda: attrb.StringDict( + default = {}, + doc = """ +PEP 517 `--config-settings=KEY=VALUE` pairs passed to the wheel build. +""", + ), + "config_settings_list": lambda: attrb.StringListDict( + default = {}, + doc = """ +Multi-valued PEP 517 `--config-settings=KEY=VALUE` pairs passed as repeated +flags to the wheel build. +""", + ), + "distribution": lambda: attrb.String( + default = "", + doc = "Optional Python distribution name; inferred from the `sdist` filename if omitted.", + ), + "environment": lambda: attrb.StringDict( + default = {}, + doc = """ +Environment variables to set during the PEP 517 wheel build action. Note that +the default builder uses the host system toolchain (`use_default_shell_env`). +""", + ), + "pre_build_patch_strips": lambda: attrb.IntList( + default = [], + doc = "Optional per-patch strip counts corresponding 1:1 with `pre_build_patches`.", + ), + "pre_build_patches": lambda: attrb.LabelList( + allow_files = True, + default = [], + doc = """ +Unified diff patch files to apply to the unpacked sdist source directory before building. +Note that git-formatted patches with `a/` and `b/` path prefixes require strip `1` in +`pre_build_patch_strips`. +""", + ), + "sdist": lambda: attrb.Label( + allow_single_file = True, + mandatory = True, + doc = "The source distribution archive (`.tar.gz`, `.tgz`, `.tar.bz2`, `.tar.xz`, or `.zip`).", + ), + "version": lambda: attrb.String( + default = "", + doc = "Optional PEP 440 package version; inferred from the `sdist` filename if omitted.", + ), + "_bootstrap_deps": lambda: attrb.LabelList( + cfg = "exec", + default = _BOOTSTRAP_DEPS, + ), + "_platform_constraints": lambda: attrb.LabelKeyedStringDict( + default = _PLATFORM_CONSTRAINTS, + ), + "_sdist_wheel_builder_helpers": lambda: attrb.Label( + allow_files = True, + default = Label("//python/private/pypi:sdist_wheel_builder_helpers"), + ), +} + +_SDIST_EXTS = (".tar.gz", ".tgz", ".tar.bz2", ".tar.xz", ".zip") + +def _parse_sdist_filename(filename): + stem = filename + for ext in _SDIST_EXTS: + if stem.endswith(ext): + stem = stem[:-len(ext)] + break + dist, sep, ver = stem.rpartition("-") + if not sep or not dist or not ver: + return "", "" + parsed_ver = version.parse(ver, strict = False) + return normalize_name(dist), (parsed_ver.string if parsed_ver else "") + +def _collect_deps(deps): + files = builders.DepsetBuilder() + sources = builders.DepsetBuilder() + imports = builders.DepsetBuilder() + venv_symlinks = builders.DepsetBuilder() + for dep in deps: + files.add(dep[DefaultInfo].files) + if dep[DefaultInfo].default_runfiles: + files.add(dep[DefaultInfo].default_runfiles.files) + py = ( + dep[PyInfo] if PyInfo in dep else (dep[BuiltinPyInfo] if BuiltinPyInfo != None and BuiltinPyInfo in dep else None) + ) + if py: + files.add(py.transitive_sources) + sources.add(py.transitive_sources) + imports.add(py.imports) + if hasattr(py, "venv_symlinks"): + venv_symlinks.add(py.venv_symlinks) + return struct( + files = files.build(), + sources = sources.build(), + imports = imports.build(), + venv_symlinks = venv_symlinks.build(), + ) + +def _dir_only(f): + return f.path if f.is_directory else None + +def _venv_symlink_import_root(entry): + if entry.kind != VenvSymlinkKind.LIB or not entry.link_to_path or not entry.venv_path: + return None + suffix = "/" + entry.venv_path + if not entry.link_to_path.endswith(suffix): + return None + return entry.link_to_path[:-len(suffix)] + +def _non_dir_dep_file(f): + if f.is_directory: + return None + if f.owner and f.owner.repo_name in _BOOTSTRAP_REPO_NAMES: + return None + return f.path + "=" + f.short_path + +def _validate_sdist_toolchains(exec_runtime, target_runtime): + if not ( + exec_runtime and exec_runtime.interpreter_version_info and + target_runtime and target_runtime.interpreter_version_info + ): + return + evi = exec_runtime.interpreter_version_info + tvi = target_runtime.interpreter_version_info + if not (evi.major and evi.minor != None and tvi.major and tvi.minor != None): + return + if evi.major != tvi.major or evi.minor != tvi.minor: + fail( + "py_sdist_wheel requires exec and target Python toolchains to have matching " + + "major.minor versions because build_deps are built in the exec configuration " + + "(got exec Python {}.{}, target Python {}.{})".format( + evi.major, + evi.minor, + tvi.major, + tvi.minor, + ), + ) + +def _resolve_sdist_output_names(name): + if name.endswith(".whldir"): + stem = name[:-len(".whldir")] + return name, stem + ".sdist_build.whl" + if name.endswith(".sdist_build.whl"): + stem = name[:-len(".sdist_build.whl")] + return stem + ".whldir", name + if name.endswith(".whl"): + stem = name[:-len(".whl")] + return stem + ".whldir", name + return name + ".whldir", name + ".sdist_build.whl" + +def _py_sdist_wheel_impl(ctx): + if ctx.attr.add_libdir_to_library_search_path and "LDFLAGS" in ctx.attr.environment: + fail("Can't set both environment LDFLAGS and add_libdir_to_library_search_path") + patches = ctx.files.pre_build_patches + strips = ctx.attr.pre_build_patch_strips or ([0] * len(patches)) + if len(strips) != len(patches): + fail("pre_build_patch_strips length ({}) must match pre_build_patches length ({})".format( + len(strips), + len(patches), + )) + + exec_runtime = ctx.toolchains[EXEC_TOOLS_TOOLCHAIN_TYPE].exec_tools.exec_runtime + target_tc = ctx.toolchains[TARGET_TOOLCHAIN_TYPE] + target_runtime = target_tc.py3_runtime if target_tc else None + _validate_sdist_toolchains(exec_runtime, target_runtime) + + if not ctx.attr.distribution or not ctx.attr.version: + parsed_dist, parsed_ver = _parse_sdist_filename(ctx.file.sdist.basename) + else: + parsed_dist, parsed_ver = "", "" + dist = normalize_name(ctx.attr.distribution) if ctx.attr.distribution else parsed_dist + ver = version.normalize(ctx.attr.version) if ctx.attr.version else parsed_ver + + whldir_name, whl_file_name = _resolve_sdist_output_names(ctx.attr.name) + out_wheel_dir = ctx.actions.declare_directory(whldir_name) + out_wheel_file = ctx.actions.declare_file(whl_file_name) + + build_deps = _collect_deps(ctx.attr.build_deps) + bootstrap_deps = _collect_deps(ctx.attr._bootstrap_deps) + + args = ctx.actions.args() + args.add("--sdist", ctx.file.sdist.path) + args.add("--wheel-dir", out_wheel_dir.path) + args.add("--out-wheel-file", out_wheel_file.path) + args.add("--workspace-name", ctx.workspace_name) + + args.add_all( + build_deps.sources, + map_each = _dir_only, + expand_directories = False, + uniquify = True, + format_each = "--installed-wheel-dir=%s", + ) + args.add_all( + [d.label.workspace_root for d in ctx.attr._bootstrap_deps], + uniquify = True, + format_each = "--python-path=%s", + ) + args.add_all( + build_deps.imports, + uniquify = True, + format_each = "--import-root=%s", + ) + args.add_all( + build_deps.venv_symlinks, + map_each = _venv_symlink_import_root, + uniquify = True, + format_each = "--import-root=%s", + ) + args.add_all( + build_deps.files, + map_each = _non_dir_dep_file, + expand_directories = False, + uniquify = True, + format_each = "--dep-file=%s", + ) + + if target_runtime and target_runtime.interpreter_version_info: + tvi = target_runtime.interpreter_version_info + if tvi.major and tvi.minor != None: + args.add("--target-python-version", "{}.{}".format(tvi.major, tvi.minor)) + + target_os = "" + target_cpu = "" + for constraint_target, spec in ctx.attr._platform_constraints.items(): + if ctx.target_platform_has_constraint(constraint_target[platform_common.ConstraintValueInfo]): + kind, _, val = spec.partition("=") + if kind == "os": + target_os = val + elif kind == "cpu": + target_cpu = val + if not target_os or not target_cpu: + fail( + "py_sdist_wheel requires a target platform with recognized OS and CPU " + + "constraints (got os='{}', cpu='{}')".format(target_os, target_cpu), + ) + args.add("--target-os", target_os) + args.add("--target-cpu", target_cpu) + + if ctx.attr.add_libdir_to_library_search_path: + args.add("--add-libdir-to-library-search-path") + + for k, v in sorted(ctx.attr.config_settings.items()): + args.add("--config-setting={}={}".format(k, v)) + for k, vals in sorted(ctx.attr.config_settings_list.items()): + for v in vals: + args.add("--config-setting={}={}".format(k, v)) + for k, v in sorted(ctx.attr.environment.items()): + args.add("--env={}={}".format(k, v)) + + for patch_file, strip_val in zip(patches, strips): + args.add("--patch", "{}:{}".format(patch_file.path, strip_val)) + + helper_files = ( + ctx.files._sdist_wheel_builder_helpers if PyInterpreterProgramInfo in ctx.attr.builder else [] + ) + action_env = ( + { + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONPATH": helper_files[0].dirname, + } if helper_files else {} + ) + inputs = depset( + direct = [ctx.file.sdist] + patches + helper_files, + transitive = [build_deps.files, bootstrap_deps.files], + ) + + actions_run( + ctx, + executable = ctx.attr.builder, + arguments = [args], + env = action_env, + inputs = inputs, + outputs = [out_wheel_dir, out_wheel_file], + mnemonic = "PySdistWheelBuild", + progress_message = "Building wheel from sdist {} into %{{output}}".format(ctx.file.sdist.basename), + use_default_shell_env = True, + ) + + return [ + DefaultInfo( + files = depset([out_wheel_file]), + runfiles = ctx.runfiles(files = [out_wheel_file]), + ), + OutputGroupInfo( + whl = depset([out_wheel_file]), + whldir = depset([out_wheel_dir]), + ), + PyBuiltWheelInfo( + directory = out_wheel_dir, + distribution = dist, + version = ver, + ), + ] + +py_sdist_wheel = ruleb.Rule( + implementation = _py_sdist_wheel_impl, + doc = """ +Builds a Python wheel (`.whl`) from an sdist archive in a Bazel build action. + +Produces both: +- A default output `File` (`.sdist_build.whl`): contents are the built wheel; + the filename is not a valid wheel filename — use `:whldir` (or + `OutputGroupInfo.whldir` / `PyBuiltWheelInfo.directory`) for the real one. +- A `.whldir` directory artifact (`TreeArtifact`) containing the built wheel with its + canonical PEP 427 filename. + +:::{note} +The default builder uses the host system toolchain (`use_default_shell_env`) +and only supports building wheels compatible with the host platform. +::: + +:::{versionadded} VERSION_NEXT_FEATURE +::: +""", + exec_groups = dict(REQUIRED_EXEC_GROUP_BUILDERS), + attrs = PY_SDIST_WHEEL_ATTRS, + provides = [PyBuiltWheelInfo], + toolchains = [ + ruleb.ToolchainType(TARGET_TOOLCHAIN_TYPE, mandatory = False), + ruleb.ToolchainType(EXEC_TOOLS_TOOLCHAIN_TYPE, mandatory = True), + ], +).build() diff --git a/python/private/pypi/sdist_wheel_builder.py b/python/private/pypi/sdist_wheel_builder.py new file mode 100644 index 0000000000..6af6882278 --- /dev/null +++ b/python/private/pypi/sdist_wheel_builder.py @@ -0,0 +1,522 @@ +"""Build a Python wheel (.whl) from an sdist archive in a Bazel build action. + +Extracts an input `.tar.gz`/`.tgz`/`.zip` sdist archive, applies optional +unified-diff patches, stages `build_deps` and PEP 517 bootstrap wheels onto +`PYTHONPATH`, builds the wheel in `--out-wheel-dir`, and copies it to +`--out-wheel-file`. + +Usage: + python3 -B sdist_wheel_builder.py --sdist path/to/pkg-1.0.tar.gz \\ + --out-wheel-dir path/to/pkg.whldir \\ + --out-wheel-file path/to/pkg.sdist_build.whl +""" + +from __future__ import annotations + +import argparse +import importlib.metadata +import os +import platform +import shutil +import subprocess +import sys +import sysconfig +import tarfile +import zipfile +from pathlib import Path + +from sdist_wheel_helpers import ( + apply_unified_patch, + sanitize_wheel_entry_path, + scrub_bazel_env, + single_wheel_in, +) + + +def _detect_host_os() -> str: + if sys.platform.startswith("linux"): + return "linux" + if sys.platform == "darwin": + return "macos" + if sys.platform in ("win32", "cygwin", "msys"): + return "windows" + return sys.platform + + +def _detect_host_cpu() -> str: + machine = platform.machine().lower() + if machine in ("x86_64", "amd64"): + return "x86_64" + if machine in ("aarch64", "arm64", "arm64e"): + return "aarch64" + if machine in ("i386", "i686", "x86", "x86_32"): + return "x86_32" + if machine.startswith("arm"): + return "arm" + if machine in ("ppc64le", "ppc64", "ppc"): + return "ppc" + return machine + + +def _extract_sdist(sdist_path: Path, extract_dir: Path) -> Path: + extract_dir.mkdir(parents=True, exist_ok=True) + if zipfile.is_zipfile(sdist_path): + with zipfile.ZipFile(sdist_path) as zf: + for info in zf.infolist(): + parts = sanitize_wheel_entry_path(info.filename) + if parts is None: + continue + target_path = extract_dir / "/".join(parts) + target_path.parent.mkdir(parents=True, exist_ok=True) + with zf.open(info) as src_f, open(target_path, "wb") as dst_f: + shutil.copyfileobj(src_f, dst_f) + unix_mode = (info.external_attr >> 16) & 0o777 + if unix_mode: + os.chmod(target_path, unix_mode | 0o600) + else: + with tarfile.open(sdist_path, "r:*") as tf: + try: + tf.extractall(extract_dir, filter="data") + except TypeError as exc: + raise RuntimeError( + "Python interpreter does not support tarfile.extractall(filter='data'); " + "Python 3.11.4+ / 3.10.12+ is required" + ) from exc + + children = [p for p in extract_dir.iterdir() if not p.name.startswith(".")] + if len(children) == 1 and children[0].is_dir(): + return children[0] + return extract_dir + + +def _resolve_wheel_and_bootstrap_paths( + prefix: Path, + installed_wheel_dirs: list[str], + raw_python_paths: list[str], +) -> tuple[list[str], list[str], list[Path]]: + """Resolve `--installed-wheel-dir` and `--python-path` arguments.""" + wheel_py: list[str] = [] + bootstrap_py: list[str] = [] + bin_dirs: list[Path] = [] + for wd in installed_wheel_dirs: + wd_abs = (prefix / wd).absolute() + sp_abs = wd_abs / "site-packages" + if sp_abs.is_dir(): + wheel_py.append(str(sp_abs)) + bin_abs = wd_abs / "bin" + if bin_abs.is_dir(): + bin_dirs.append(bin_abs) + for raw_p in raw_python_paths: + bootstrap_py.append(str((prefix / raw_p).absolute())) + return wheel_py, bootstrap_py, bin_dirs + + +def _stage_dep_files( + deps_dir: Path, + prefix: Path, + workspace_name: str, + import_roots: list[str], + dep_files: list[str], + existing_py_paths: list[str] | tuple[str, ...] = (), +) -> tuple[list[str], list[str]]: + """Stage non-wheel `build_deps` files by runfiles path into `deps_dir`.""" + if not dep_files and not import_roots: + return [], [] + if dep_files: + deps_dir.mkdir(parents=True, exist_ok=True) + ws = workspace_name.replace("\\", "/").strip("/") or "_main" + staged_sources: dict[Path, Path] = {} + + for entry in dep_files: + exec_rel, sep, short_rel = entry.partition("=") + if not sep or not exec_rel or not short_rel: + continue + src_abs = (prefix / exec_rel).absolute() + norm_short = short_rel.replace("\\", "/").lstrip("/") + runfiles_rel = ( + norm_short[3:] if norm_short.startswith("../") else f"{ws}/{norm_short}" + ) + parts = sanitize_wheel_entry_path(runfiles_rel) + if not parts: + continue + dest_path = deps_dir.joinpath(*parts) + src_resolved = src_abs.resolve() + prev_src = staged_sources.get(dest_path) + if prev_src is not None: + if prev_src != src_resolved: + raise ValueError( + f"Conflicting build_deps files map to the same path " + f"'{runfiles_rel}': '{prev_src}' vs '{src_resolved}'" + ) + continue + staged_sources[dest_path] = src_resolved + dest_path.parent.mkdir(parents=True, exist_ok=True) + if not dest_path.exists() and not dest_path.is_symlink(): + try: + dest_path.symlink_to(src_abs) + except OSError: + shutil.copy2(src_abs, dest_path) + + norm_roots = [ + imp.replace("\\", "/").strip("/") + for imp in import_roots + if imp.replace("\\", "/").strip("/") + ] + existing_norm = [p.replace("\\", "/").rstrip("/") for p in existing_py_paths] + matched_roots: list[str] = [] + unmatched_roots: list[tuple[str, Path]] = [] + site_pkg_imports: list[str] = [] + first_party_imports: list[str] = [] + + for norm_imp in norm_roots: + imp_dir = (deps_dir / norm_imp).absolute() + if imp_dir.is_dir(): + matched_roots.append(norm_imp) + imp_str = str(imp_dir) + if norm_imp == "site-packages" or norm_imp.endswith("/site-packages"): + if imp_str not in site_pkg_imports: + site_pkg_imports.append(imp_str) + elif imp_str not in first_party_imports: + first_party_imports.append(imp_str) + else: + unmatched_roots.append((norm_imp, imp_dir)) + + for norm_imp, imp_dir in unmatched_roots: + # In venvs_site_packages=yes mode, py_library populates PyInfo.imports with + # raw unprefixed imports alongside the resolved PyInfo.venv_symlinks root. + if any(m.endswith(f"/{norm_imp}") for m in matched_roots): + continue + # Transitive PyInfo.imports from a py_library depending on an installed wheel + # or bootstrap library are already present in existing_py_paths. + rel_imp = norm_imp[len(ws) + 1 :] if norm_imp.startswith(f"{ws}/") else norm_imp + if "/" in rel_imp and any(ep.endswith(f"/{rel_imp}") for ep in existing_norm): + continue + raise ValueError( + f"Import root '{norm_imp}' does not exist under staged build_deps ({imp_dir})" + ) + + ws_dir = (deps_dir / ws).absolute() + if ws_dir.is_dir() and str(ws_dir) not in first_party_imports: + first_party_imports.append(str(ws_dir)) + + return site_pkg_imports, first_party_imports + + +def _populate_scratch_bin_dir( + scratch_bin_dir: Path, + build_python: str, + bin_dirs: list[Path], + python_paths: list[str], +) -> None: + """Create a tool bin directory containing python3/python and build_deps console scripts.""" + scratch_bin_dir.mkdir(parents=True, exist_ok=True) + build_py_abs = Path(build_python).absolute() + + for link_name in ("python3", "python"): + dest = scratch_bin_dir / link_name + if not dest.exists() and not dest.is_symlink(): + dest.symlink_to(build_py_abs) + + for bd_abs in bin_dirs: + for item in sorted(bd_abs.iterdir()): + if not item.is_file(): + continue + dest = scratch_bin_dir / item.name + if dest.exists(): + continue + shutil.copy2(item, dest) + os.chmod(dest, os.stat(dest).st_mode | 0o755) + + for dist in importlib.metadata.distributions(path=python_paths): + for ep in dist.entry_points: + if ep.group not in ("console_scripts", "gui_scripts"): + continue + dest = scratch_bin_dir / ep.name + if dest.exists(): + continue + module_name, sep, attr_name = ( + ep.value.partition("[")[0].strip().partition(":") + ) + if not sep or not module_name or not attr_name: + continue + with open(dest, "w", encoding="utf-8", newline="\n") as f: + f.write( + "#!/bin/sh\n" + '\'\'\'exec\' "$(dirname "$0")/python3" "$0" "$@"\n' + "' '''\n" + f"import re, sys\nfrom {module_name.strip()} import {attr_name.strip()}\n" + "if __name__ == '__main__':\n" + " sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n" + f" sys.exit({attr_name.strip()}())\n" + ) + os.chmod(dest, 0o755) + + +def _get_macos_sysroot_cflag() -> str: + """Query macOS SDK path via xcrun for python-build-standalone compatibility.""" + if sys.platform != "darwin": + return "" + xcrun = shutil.which("xcrun") + if not xcrun: + return "" + proc = subprocess.run( + [xcrun, "--show-sdk-path"], + capture_output=True, + text=True, + check=False, + ) + if proc.returncode == 0 and proc.stdout.strip(): + return f"-isysroot {proc.stdout.strip()}" + return "" + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Build a wheel from an sdist archive into a TreeArtifact directory.", + fromfile_prefix_chars="@", + ) + parser.add_argument("--sdist", type=Path, required=True) + parser.add_argument("--wheel-dir", type=Path, required=True) + parser.add_argument("--out-wheel-file", type=Path, default=None) + parser.add_argument("--workspace-name", default="_main") + parser.add_argument( + "--installed-wheel-dir", + action="append", + dest="installed_wheel_dirs", + default=[], + ) + parser.add_argument( + "--python-path", + action="append", + dest="python_paths", + default=[], + ) + parser.add_argument( + "--import-root", + action="append", + dest="import_roots", + default=[], + ) + parser.add_argument( + "--dep-file", + action="append", + dest="dep_files", + default=[], + ) + parser.add_argument( + "--config-setting", + action="append", + dest="config_settings", + default=[], + ) + parser.add_argument( + "--env", + action="append", + dest="env_vars", + default=[], + ) + parser.add_argument( + "--patch", + action="append", + dest="patches", + default=[], + ) + parser.add_argument( + "--add-libdir-to-library-search-path", + action="store_true", + default=False, + ) + parser.add_argument("--target-os", default="") + parser.add_argument("--target-cpu", default="") + parser.add_argument("--target-python-version", default="") + args = parser.parse_args() + + host_os = _detect_host_os() + host_cpu = _detect_host_cpu() + if (args.target_os and args.target_os != host_os) or ( + args.target_cpu and args.target_cpu != host_cpu + ): + raise RuntimeError( + f"Target platform (os={args.target_os or 'any'}, cpu={args.target_cpu or 'any'}) " + f"differs from host (os={host_os}, cpu={host_cpu}); " + "the default sdist builder only builds for the host." + ) + host_py_ver = f"{sys.version_info.major}.{sys.version_info.minor}" + if args.target_python_version and args.target_python_version != host_py_ver: + raise RuntimeError( + f"Target Python version ({args.target_python_version}) differs from " + f"build Python interpreter ({host_py_ver}); py_sdist_wheel requires " + "matching major.minor versions." + ) + + prefix = Path.cwd().absolute() + sdist_abs = (prefix / args.sdist).absolute() + wheel_dir_abs = (prefix / args.wheel_dir).absolute() + wheel_dir_abs.mkdir(parents=True, exist_ok=True) + + wheel_py_paths, bootstrap_py_paths, bin_dirs = _resolve_wheel_and_bootstrap_paths( + prefix, + args.installed_wheel_dirs, + args.python_paths, + ) + + orig_env = scrub_bazel_env(os.environ.copy()) + build_python = sys.executable + + scratch_dir = (wheel_dir_abs.parent / f"_{wheel_dir_abs.name}_tmp").absolute() + shutil.rmtree(scratch_dir, ignore_errors=True) + + try: + home_dir = scratch_dir / "home" + work_tmp_dir = scratch_dir / "tmp" + scratch_bin_dir = scratch_dir / "bin" + home_dir.mkdir(parents=True, exist_ok=True) + work_tmp_dir.mkdir(parents=True, exist_ok=True) + + site_pkg_imports, first_party_imports = _stage_dep_files( + deps_dir=scratch_dir / "deps", + prefix=prefix, + workspace_name=args.workspace_name, + import_roots=args.import_roots, + dep_files=args.dep_files, + existing_py_paths=[ + *wheel_py_paths, + *(f"{bp}/site-packages" for bp in bootstrap_py_paths), + ], + ) + resolved_python_paths = [ + *wheel_py_paths, + *site_pkg_imports, + *bootstrap_py_paths, + *first_party_imports, + ] + + _populate_scratch_bin_dir( + scratch_bin_dir=scratch_bin_dir, + build_python=build_python, + bin_dirs=bin_dirs, + python_paths=resolved_python_paths, + ) + + sdist_root = _extract_sdist(sdist_abs, scratch_dir / "src") + for item in args.patches: + raw_path, _, raw_strip = item.rpartition(":") + apply_unified_patch( + sdist_root, + (prefix / Path(raw_path)).absolute(), + strip=int(raw_strip), + ) + + env = dict(orig_env) + env["PYTHONHASHSEED"] = "0" + env["PYTHONNOUSERSITE"] = "1" + env["PYTHONDONTWRITEBYTECODE"] = "1" + env.setdefault("SOURCE_DATE_EPOCH", "315532800") + env["HOME"] = str(home_dir) + env["TMPDIR"] = str(work_tmp_dir) + env["TEMP"] = str(work_tmp_dir) + env["TMP"] = str(work_tmp_dir) + + c_remap_flag = f"-ffile-prefix-map={scratch_dir}=." + for flag_var in ("CFLAGS", "CXXFLAGS"): + env[flag_var] = ( + f"{env[flag_var]} {c_remap_flag}" if env.get(flag_var) else c_remap_flag + ) + + rust_remap_flag = f"--remap-path-prefix={scratch_dir}=." + env["RUSTFLAGS"] = ( + f"{env['RUSTFLAGS']} {rust_remap_flag}" + if env.get("RUSTFLAGS") + else rust_remap_flag + ) + + include_dir = sysconfig.get_path("include") or "" + cppflags: list[str] = [env["CPPFLAGS"]] if env.get("CPPFLAGS") else [] + sysroot_flag = _get_macos_sysroot_cflag() + if ( + sysroot_flag + and "-isysroot" not in env.get("CPPFLAGS", "") + and "-isysroot" not in env.get("CFLAGS", "") + ): + cppflags.append(sysroot_flag) + if include_dir and os.path.isdir(include_dir): + cppflags.append(f"-isystem {include_dir}") + if cppflags: + env["CPPFLAGS"] = " ".join(cppflags) + + env["PYTHONPATH"] = os.pathsep.join(resolved_python_paths) + orig_path = env.get("PATH", "") + env["PATH"] = os.pathsep.join( + [str(scratch_bin_dir)] + ([orig_path] if orig_path else []) + ) + + if args.add_libdir_to_library_search_path: + libdir_flag = f"-L{sys.exec_prefix}/lib" + env["LDFLAGS"] = ( + f"{env['LDFLAGS']} {libdir_flag}" if env.get("LDFLAGS") else libdir_flag + ) + + for item in args.env_vars: + k, sep, v = item.partition("=") + if not sep or not k: + raise ValueError(f"Invalid --env entry '{item}', expected KEY=VALUE") + env[k] = v + + pip_config_args = [f"--config-settings={cs}" for cs in args.config_settings] + + cmd = [ + build_python, + "-m", + "pip", + "--isolated", + "--no-cache-dir", + "wheel", + "--no-deps", + "--no-index", + "--no-build-isolation", + "--check-build-dependencies", + "--wheel-dir", + str(wheel_dir_abs), + *pip_config_args, + str(sdist_root.absolute()), + ] + result = subprocess.run( + cmd, + env=env, + cwd=str(sdist_root), + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + ) + if result.returncode != 0: + hint = "" + if ( + "Some build dependencies" in result.stdout + and "are missing" in result.stdout + ): + hint = ( + "\nHint: Ensure the missing build requirements are present in your " + "pip requirements lockfile / hub or specify them via " + "'sdist_build_deps' (pip.whl_mods / package_annotation) or " + "'py_sdist_wheel.build_deps'." + ) + sys.stderr.write( + f"Failed to build wheel from sdist '{args.sdist}':\n{result.stdout}{hint}\n" + ) + sys.exit(result.returncode) + finally: + shutil.rmtree(scratch_dir, ignore_errors=True) + + built_whl = single_wheel_in(wheel_dir_abs) + if args.out_wheel_file is not None: + out_whl_abs = (prefix / args.out_wheel_file).absolute() + if out_whl_abs.exists() or out_whl_abs.is_symlink(): + out_whl_abs.unlink() + try: + os.link(built_whl, out_whl_abs) + except OSError: + shutil.copy2(built_whl, out_whl_abs) + + +if __name__ == "__main__": + main() diff --git a/python/private/pypi/sdist_wheel_helpers.py b/python/private/pypi/sdist_wheel_helpers.py new file mode 100644 index 0000000000..95581100c2 --- /dev/null +++ b/python/private/pypi/sdist_wheel_helpers.py @@ -0,0 +1,339 @@ +"""Pure-stdlib helpers for sdist_wheel_builder.""" + +from __future__ import annotations + +import re +from pathlib import Path + +_BAZEL_LAUNCHER_VARS = ( + "PYTHONSAFEPATH", + "PYTHONPATH", + "PYTHONHOME", + "RUNFILES_DIR", + "RUNFILES_MANIFEST_FILE", + "RUNFILES_MANIFEST_ONLY", +) + + +def scrub_bazel_env(env: dict[str, str]) -> dict[str, str]: + """Remove Bazel py_binary launcher variables from `env` in-place.""" + for key in _BAZEL_LAUNCHER_VARS: + env.pop(key, None) + return env + + +def sanitize_wheel_entry_path(name: str) -> list[str] | None: + """Validate and split a wheel zip member path into normalized path components. + + Returns None for directory entries (`name.endswith("/")`). + Raises ValueError if the path is absolute, contains backslashes, drive + letters, empty segments, `.`, or `..`. + """ + if name.endswith("/"): + return None + if name.startswith("/") or "\\" in name: + raise ValueError(f"Unsafe wheel entry path: {name!r}") + parts = name.split("/") + if ":" in parts[0]: + raise ValueError(f"Unsafe wheel entry path: {name!r}") + for part in parts: + if part in ("", ".", ".."): + raise ValueError(f"Unsafe wheel entry path: {name!r}") + return parts + + +def single_wheel_in(wheel_dir: Path, *, check_stray: bool = False) -> Path: + """Return the single `.whl` file inside `wheel_dir`, or raise `ValueError`.""" + entries = sorted(wheel_dir.iterdir()) + whls = [p for p in entries if p.is_file() and p.suffix == ".whl"] + if len(whls) != 1: + raise ValueError( + f"Expected 1 .whl file in '{wheel_dir}', found {len(whls)}: {[p.name for p in whls]}" + ) + if check_stray and len(entries) != 1: + stray = [p.name for p in entries if p != whls[0]] + raise ValueError(f"Unexpected non-wheel files in '{wheel_dir}': {stray}") + return whls[0] + + +_HUNK_HEADER_RE = re.compile(rb"^@@ -(\d+)(?:,(\d+))? \+\d+(?:,(\d+))? @@") +_UNSUPPORTED_PATCH_PREFIXES = ( + b"Binary files ", + b"GIT binary patch", + b"rename from ", + b"rename to ", + b"copy from ", + b"copy to ", +) + + +def _strip_patch_path(raw_path: bytes, strip: int) -> str: + path_bytes = raw_path.split(b"\t", 1)[0].strip() + try: + path = path_bytes.decode("utf-8") + except UnicodeDecodeError as exc: + raise ValueError(f"Non-UTF-8 path in patch header: {raw_path!r}") from exc + if path == "/dev/null": + return path + if path.startswith("/") or "\\" in path or ":" in path.split("/", 1)[0]: + raise ValueError(f"Unsafe patch path: {path!r}") + parts = [p for p in path.split("/") if p] + if strip >= len(parts): + raise ValueError(f"Cannot strip {strip} components from patch path '{path}'") + return "/".join(parts[strip:]) + + +def _find_hunk_position( + file_lines: list[bytes], + preferred_pos: int, + old_ops: list[bytes], + min_pos: int = 0, +) -> int | None: + def _matches(pos: int) -> bool: + return ( + min_pos <= pos + and pos + len(old_ops) <= len(file_lines) + and all( + file_lines[pos + idx].rstrip(b"\r\n") == expected + for idx, expected in enumerate(old_ops) + ) + ) + + if not old_ops: + return preferred_pos if min_pos <= preferred_pos <= len(file_lines) else None + if _matches(preferred_pos): + return preferred_pos + max_delta = max(preferred_pos - min_pos, len(file_lines) - preferred_pos) + for delta in range(1, max_delta + 1): + for candidate in (preferred_pos - delta, preferred_pos + delta): + if _matches(candidate): + return candidate + return None + + +def _parse_patch_hunk( + lines: list[bytes], + i: int, + patch_path: Path, + target_rel: str, +) -> tuple[int, int, list[tuple[bytes, bytes, bool]], int]: + n = len(lines) + m = _HUNK_HEADER_RE.match(lines[i]) + if not m: + raise ValueError(f"Invalid hunk header in {patch_path}: {lines[i]!r}") + old_start = int(m.group(1)) + old_count = int(m.group(2)) if m.group(2) is not None else 1 + new_count = int(m.group(3)) if m.group(3) is not None else 1 + i += 1 + + rem_old = old_count + rem_new = new_count + hunk_ops: list[tuple[bytes, bytes, bool]] = [] + + while rem_old > 0 or rem_new > 0: + if i >= n: + raise ValueError( + f"Unexpected end of patch {patch_path} inside hunk for {target_rel}" + ) + hline = lines[i] + i += 1 + if hline in (b"\n", b"\r\n") and rem_old > 0 and rem_new > 0: + op = b" " + body = b"" + else: + op = hline[:1] + body = hline[1:].rstrip(b"\r\n") + + if op == b" ": + if rem_old <= 0 or rem_new <= 0: + raise ValueError( + f"Unexpected context line in {patch_path} for {target_rel}" + ) + rem_old -= 1 + rem_new -= 1 + elif op == b"-": + if rem_old <= 0: + raise ValueError( + f"Unexpected deletion line in {patch_path} for {target_rel}" + ) + rem_old -= 1 + elif op == b"+": + if rem_new <= 0: + raise ValueError( + f"Unexpected addition line in {patch_path} for {target_rel}" + ) + rem_new -= 1 + else: + raise ValueError( + f"Malformed hunk line in {patch_path} for {target_rel}: {hline!r}" + ) + + no_nl = False + if i < n and lines[i].startswith(b"\\"): + no_nl = True + i += 1 + hunk_ops.append((op, body, no_nl)) + + return old_start, old_count, hunk_ops, i + + +def _apply_hunk_ops( + file_lines: list[bytes], + match_pos: int, + hunk_ops: list[tuple[bytes, bytes, bool]], + eol: bytes, +) -> tuple[list[bytes], int]: + replacement: list[bytes] = [] + cur_old = match_pos + for op, body, no_nl in hunk_ops: + if op == b"-": + cur_old += 1 + continue + if op == b"+": + replacement.append(body if no_nl else (body + eol)) + continue + orig_line = file_lines[cur_old] + cur_old += 1 + if no_nl: + replacement.append(orig_line.rstrip(b"\r\n")) + elif not orig_line.endswith((b"\n", b"\r\n")): + replacement.append(orig_line + eol) + else: + replacement.append(orig_line) + return replacement, cur_old + + +def apply_unified_patch( + root_dir: Path, + patch_path: Path, + strip: int = 0, +) -> set[str]: + """Apply a unified diff file strictly under `root_dir`, preserving line endings. + + Returns the set of relative POSIX paths under `root_dir` touched by the patch. + """ + root_resolved = root_dir.resolve() + lines = patch_path.read_bytes().splitlines(keepends=True) + i = 0 + n = len(lines) + applied_any = False + just_finished_hunk = False + touched: set[str] = set() + + while i < n: + line = lines[i] + if line.startswith(_UNSUPPORTED_PATCH_PREFIXES): + raise ValueError( + f"Unsupported binary or rename/copy patch directive in {patch_path}: {line!r}" + ) + is_file_header = ( + line.startswith(b"--- ") and i + 1 < n and lines[i + 1].startswith(b"+++ ") + ) + if not is_file_header: + if _HUNK_HEADER_RE.match(line): + raise ValueError( + f"Hunk without preceding '--- '/'+++ ' file header in {patch_path}: {line!r}" + ) + if ( + just_finished_hunk + and line.startswith((b"+", b"-", b" ")) + and not line.startswith(b"+++ ") + and line not in (b"-- \n", b"-- \r\n") + ): + raise ValueError( + f"Unexpected diff body line outside hunk in {patch_path}: {line!r}" + ) + just_finished_hunk = False + i += 1 + continue + just_finished_hunk = False + + old_rel = _strip_patch_path(line[4:], strip) + new_rel = _strip_patch_path(lines[i + 1][4:], strip) + i += 2 + + if ( + strip == 0 + and (old_rel.startswith("a/") or old_rel == "/dev/null") + and (new_rel.startswith("b/") or new_rel == "/dev/null") + and (old_rel != "/dev/null" or new_rel != "/dev/null") + ): + raise ValueError( + f"Patch {patch_path}: patch looks git-formatted (a/ b/ prefixes); use strip=1" + ) + + target_rel = old_rel if new_rel == "/dev/null" else new_rel + target_file = root_dir / target_rel + target_resolved = target_file.resolve() + if ( + not target_resolved.is_relative_to(root_resolved) + or target_resolved == root_resolved + ): + raise ValueError( + f"Patch target '{target_rel}' escapes root directory '{root_dir}'" + ) + + if old_rel == "/dev/null": + if target_file.exists(): + raise ValueError( + f"Patch {patch_path} attempts to create existing file '{target_rel}'" + ) + file_lines: list[bytes] = [] + elif not target_file.exists(): + raise ValueError( + f"Patch {patch_path} targets non-existent file '{target_rel}'" + ) + else: + file_lines = target_file.read_bytes().splitlines(keepends=True) + + eol = b"\r\n" if any(fl.endswith(b"\r\n") for fl in file_lines) else b"\n" + + offset = 0 + min_pos = 0 + file_had_hunk = False + while i < n and lines[i].startswith(b"@@ "): + old_start, old_count, hunk_ops, i = _parse_patch_hunk( + lines, i, patch_path, target_rel + ) + old_bodies = [body for op, body, _ in hunk_ops if op in (b" ", b"-")] + if old_count == 0: + preferred = max(0, old_start + offset) + else: + preferred = 0 if old_start == 0 else max(0, old_start - 1 + offset) + match_pos = _find_hunk_position( + file_lines, preferred, old_bodies, min_pos=min_pos + ) + if match_pos is None: + raise ValueError( + f"Patch {patch_path} failed to apply to {target_rel} at line {old_start}: context mismatch" + ) + + replacement, cur_old = _apply_hunk_ops(file_lines, match_pos, hunk_ops, eol) + file_lines[match_pos:cur_old] = replacement + offset += (match_pos - preferred) + len(replacement) - (cur_old - match_pos) + min_pos = match_pos + len(replacement) + file_had_hunk = True + applied_any = True + + just_finished_hunk = True + if not file_had_hunk: + raise ValueError( + f"Patch {patch_path} has file header for {target_rel} without any hunks" + ) + + if new_rel == "/dev/null": + if file_lines: + raise ValueError( + f"Delete patch {patch_path} for '{target_rel}' did not consume entire file" + ) + if target_file.exists(): + target_file.unlink() + else: + target_file.parent.mkdir(parents=True, exist_ok=True) + target_file.write_bytes(b"".join(file_lines)) + touched.add(target_rel) + + if not applied_any: + raise ValueError(f"No valid unified diff hunks found in {patch_path}") + + return touched diff --git a/tests/pypi/py_sdist_wheel/BUILD.bazel b/tests/pypi/py_sdist_wheel/BUILD.bazel new file mode 100644 index 0000000000..ed79dfa3fd --- /dev/null +++ b/tests/pypi/py_sdist_wheel/BUILD.bazel @@ -0,0 +1,162 @@ +load("//python:pip.bzl", "whl_filegroup") +load("//python:py_binary.bzl", "py_binary") +load("//python:py_library.bzl", "py_library") +load("//python:py_test.bzl", "py_test") +load("//python/private/pypi:py_sdist_wheel.bzl", "py_sdist_wheel") # buildifier: disable=bzl-visibility +load(":py_sdist_wheel_bzl_tests.bzl", "py_sdist_wheel_bzl_test_suite") + +py_sdist_wheel_bzl_test_suite( + name = "py_sdist_wheel_bzl_tests", +) + +py_binary( + name = "make_test_sdist", + srcs = ["make_test_sdist.py"], + main = "make_test_sdist.py", +) + +genrule( + name = "gen_demo_sdist", + outs = ["sdist_demo-0.5.0.tar.gz"], + cmd = "$(execpath :make_test_sdist) $@", + tools = [":make_test_sdist"], +) + +py_library( + name = "classic_bdep", + srcs = ["classic_bdep/site-packages/classic_bdep/__init__.py"], + data = ["classic_bdep/site-packages/classic_bdep-1.0.dist-info/METADATA"], + imports = ["classic_bdep/site-packages"], +) + +py_library( + name = "custom_build_helper", + srcs = ["custom_build_helper/helper_mod.py"], + data = ["custom_build_helper/helper_data.txt"], + imports = ["custom_build_helper"], +) + +py_library( + name = "custom_shadow_dep", + srcs = ["custom_shadow_dep/packaging/__init__.py"], + imports = ["custom_shadow_dep"], +) + +py_sdist_wheel( + name = "sdist_demo-0.5.0.whldir", + build_deps = [ + ":classic_bdep", + ":custom_build_helper", + ":custom_shadow_dep", + ], + pre_build_patch_strips = [1], + pre_build_patches = ["pre_build.patch"], + sdist = ":gen_demo_sdist", +) + +filegroup( + name = "sdist_demo_whldir_fg", + srcs = [":sdist_demo-0.5.0.whldir"], + output_group = "whldir", +) + +whl_filegroup( + name = "sdist_demo_whl_fg", + pattern = "sdist_demo/.*", + whl = ":sdist_demo-0.5.0.whldir", +) + +py_sdist_wheel( + name = "sdist_demo_bare_a", + build_deps = [ + ":classic_bdep", + ":custom_build_helper", + ":custom_shadow_dep", + ], + sdist = ":gen_demo_sdist", +) + +py_sdist_wheel( + name = "sdist_demo_bare_b", + build_deps = [ + ":classic_bdep", + ":custom_build_helper", + ":custom_shadow_dep", + ], + sdist = ":gen_demo_sdist", +) + +genrule( + name = "gen_cext_sdist", + outs = ["sdist_cext-0.1.0.tar.gz"], + cmd = "$(execpath :make_test_sdist) --c-ext $@", + tools = [":make_test_sdist"], +) + +py_sdist_wheel( + name = "sdist_cext_a.whldir", + sdist = ":gen_cext_sdist", + target_compatible_with = select({ + "@platforms//os:windows": ["@platforms//:incompatible"], + "//conditions:default": [], + }), +) + +filegroup( + name = "sdist_cext_a_whldir_fg", + srcs = [":sdist_cext_a.whldir"], + output_group = "whldir", +) + +py_sdist_wheel( + name = "sdist_cext_b.whldir", + sdist = ":gen_cext_sdist", + target_compatible_with = select({ + "@platforms//os:windows": ["@platforms//:incompatible"], + "//conditions:default": [], + }), +) + +filegroup( + name = "sdist_cext_b_whldir_fg", + srcs = [":sdist_cext_b.whldir"], + output_group = "whldir", +) + +py_test( + name = "sdist_cext_test", + size = "small", + srcs = ["sdist_cext_test.py"], + data = [ + ":sdist_cext_a.whldir", + ":sdist_cext_a_whldir_fg", + ":sdist_cext_b.whldir", + ":sdist_cext_b_whldir_fg", + ], + target_compatible_with = select({ + "@platforms//os:windows": ["@platforms//:incompatible"], + "//conditions:default": [], + }), + deps = ["//python/runfiles"], +) + +py_test( + name = "sdist_wheel_builder_test", + size = "small", + srcs = [ + "make_test_sdist.py", + "sdist_wheel_builder_test.py", + ], + data = [ + ":sdist_demo-0.5.0.whldir", + ":sdist_demo_bare_a", + ":sdist_demo_bare_b", + ":sdist_demo_whl_fg", + ":sdist_demo_whldir_fg", + ], + main = "sdist_wheel_builder_test.py", + deps = [ + "//python/private/pypi:sdist_wheel_builder_lib", + "//python/runfiles", + ], +) diff --git a/tests/pypi/py_sdist_wheel/classic_bdep/site-packages/classic_bdep-1.0.dist-info/METADATA b/tests/pypi/py_sdist_wheel/classic_bdep/site-packages/classic_bdep-1.0.dist-info/METADATA new file mode 100644 index 0000000000..517762ce2d --- /dev/null +++ b/tests/pypi/py_sdist_wheel/classic_bdep/site-packages/classic_bdep-1.0.dist-info/METADATA @@ -0,0 +1,3 @@ +Metadata-Version: 2.1 +Name: classic-bdep +Version: 1.0 diff --git a/tests/pypi/py_sdist_wheel/classic_bdep/site-packages/classic_bdep/__init__.py b/tests/pypi/py_sdist_wheel/classic_bdep/site-packages/classic_bdep/__init__.py new file mode 100644 index 0000000000..1e8445dab2 --- /dev/null +++ b/tests/pypi/py_sdist_wheel/classic_bdep/site-packages/classic_bdep/__init__.py @@ -0,0 +1 @@ +CLASSIC_BDEP_OK = True diff --git a/tests/pypi/py_sdist_wheel/custom_build_helper/helper_data.txt b/tests/pypi/py_sdist_wheel/custom_build_helper/helper_data.txt new file mode 100644 index 0000000000..3c719ead7e --- /dev/null +++ b/tests/pypi/py_sdist_wheel/custom_build_helper/helper_data.txt @@ -0,0 +1 @@ +helper_data_ok diff --git a/tests/pypi/py_sdist_wheel/custom_build_helper/helper_mod.py b/tests/pypi/py_sdist_wheel/custom_build_helper/helper_mod.py new file mode 100644 index 0000000000..9f33bcab0b --- /dev/null +++ b/tests/pypi/py_sdist_wheel/custom_build_helper/helper_mod.py @@ -0,0 +1,11 @@ +"""First-party build helper module used to test py_library in py_sdist_wheel.build_deps.""" + +import os + +with open( + os.path.join(os.path.dirname(__file__), "helper_data.txt"), + encoding="utf-8", +) as _f: + HELPER_DATA = _f.read().strip() + +HELPER_READY = HELPER_DATA == "helper_data_ok" diff --git a/tests/pypi/py_sdist_wheel/custom_shadow_dep/packaging/__init__.py b/tests/pypi/py_sdist_wheel/custom_shadow_dep/packaging/__init__.py new file mode 100644 index 0000000000..a19780d8ab --- /dev/null +++ b/tests/pypi/py_sdist_wheel/custom_shadow_dep/packaging/__init__.py @@ -0,0 +1,3 @@ +"""First-party module named `packaging` to verify it does not shadow bootstrap `packaging`.""" + +SHADOW_MARKER = True diff --git a/tests/pypi/py_sdist_wheel/make_test_sdist.py b/tests/pypi/py_sdist_wheel/make_test_sdist.py new file mode 100644 index 0000000000..06b309d7db --- /dev/null +++ b/tests/pypi/py_sdist_wheel/make_test_sdist.py @@ -0,0 +1,93 @@ +"""Helper to generate deterministic test sdist tar.gz files for py_sdist_wheel tests.""" + +from __future__ import annotations + +import argparse +import io +import pathlib +import tarfile + +_CEXT_SOURCE = """\ +#define PY_SSIZE_T_CLEAN +#include + +static PyObject* cext_add_ints(PyObject* self, PyObject* args) { + long a = 0, b = 0; + if (!PyArg_ParseTuple(args, "ll", &a, &b)) return NULL; + return PyLong_FromLong(a + b); +} + +static PyMethodDef CextMethods[] = { + {"add_ints", cext_add_ints, METH_VARARGS, "Add two ints."}, + {NULL, NULL, 0, NULL} +}; + +static struct PyModuleDef cextmodule = { + PyModuleDef_HEAD_INIT, "cext_demo", NULL, -1, CextMethods +}; + +PyMODINIT_FUNC PyInit_cext_demo(void) { + return PyModule_Create(&cextmodule); +} +""" + + +def write_sdist_tar(out: pathlib.Path, files: dict[str, str]) -> pathlib.Path: + out.parent.mkdir(parents=True, exist_ok=True) + with tarfile.open(out, "w:gz") as tf: + for name, content in files.items(): + data = content.encode("utf-8") + info = tarfile.TarInfo(name=name) + info.size = len(data) + info.mtime = 315532800 + info.mode = 0o644 + tf.addfile(info, io.BytesIO(data)) + return out + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("out", type=pathlib.Path) + parser.add_argument("--c-ext", action="store_true") + args = parser.parse_args() + + if args.c_ext: + write_sdist_tar( + args.out, + { + "sdist_cext-0.1.0/PKG-INFO": "Metadata-Version: 2.1\nName: sdist-cext\nVersion: 0.1.0\n", + "sdist_cext-0.1.0/setup.py": ( + "from setuptools import Extension, setup\n" + "setup(name='sdist-cext', version='0.1.0', packages=['sdist_cext'], " + "ext_modules=[Extension('cext_demo', ['src/cext_demo.c'])])\n" + ), + "sdist_cext-0.1.0/sdist_cext/__init__.py": "import cext_demo\nadd_ints = cext_demo.add_ints\n", + "sdist_cext-0.1.0/src/cext_demo.c": _CEXT_SOURCE, + }, + ) + else: + write_sdist_tar( + args.out, + { + "sdist_demo-0.5.0/pyproject.toml": ( + "[build-system]\n" + 'requires = ["setuptools", "wheel", "classic-bdep>=1.0"]\n' + 'build-backend = "setuptools.build_meta"\n' + ), + "sdist_demo-0.5.0/PKG-INFO": "Metadata-Version: 2.1\nName: sdist-demo\nVersion: 0.5.0\n", + "sdist_demo-0.5.0/setup.py": ( + "import classic_bdep, helper_mod, packaging, packaging.version\n" + "from setuptools import setup\n" + "assert classic_bdep.CLASSIC_BDEP_OK is True\n" + "assert helper_mod.HELPER_READY is True\n" + "assert helper_mod.HELPER_DATA == 'helper_data_ok'\n" + "assert not hasattr(packaging, 'SHADOW_MARKER')\n" + "setup(name='sdist-demo', version='0.5.0', packages=['sdist_demo'])\n" + ), + "sdist_demo-0.5.0/sdist_demo/__init__.py": 'GREETING = "unpatched_sdist"\n', + }, + ) + + +if __name__ == "__main__": + main() diff --git a/tests/pypi/py_sdist_wheel/pre_build.patch b/tests/pypi/py_sdist_wheel/pre_build.patch new file mode 100644 index 0000000000..595b7e7339 --- /dev/null +++ b/tests/pypi/py_sdist_wheel/pre_build.patch @@ -0,0 +1,5 @@ +--- a/sdist_demo/__init__.py ++++ b/sdist_demo/__init__.py +@@ -1 +1 @@ +-GREETING = "unpatched_sdist" ++GREETING = "patched_before_build" diff --git a/tests/pypi/py_sdist_wheel/py_sdist_wheel_bzl_tests.bzl b/tests/pypi/py_sdist_wheel/py_sdist_wheel_bzl_tests.bzl new file mode 100644 index 0000000000..3a0719599d --- /dev/null +++ b/tests/pypi/py_sdist_wheel/py_sdist_wheel_bzl_tests.bzl @@ -0,0 +1,44 @@ +"""Analysis tests for py_sdist_wheel.""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test") +load("@rules_testing//lib:test_suite.bzl", "test_suite") +load("@rules_testing//lib:truth.bzl", "matching") +load("//python/private/pypi:py_sdist_wheel.bzl", "py_sdist_wheel") # buildifier: disable=bzl-visibility + +_tests = [] + +def _test_unrecognized_target_cpu_fails(name): + native.platform( + name = name + "_ppc32_platform", + constraint_values = [ + "@platforms//os:linux", + "@platforms//cpu:ppc32", + ], + ) + py_sdist_wheel( + name = name + "_subject", + sdist = ":gen_demo_sdist", + tags = ["manual"], + ) + analysis_test( + name = name, + config_settings = { + "//command_line_option:platforms": str(native.package_relative_label(name + "_ppc32_platform")), + }, + expect_failure = True, + impl = _test_unrecognized_target_cpu_fails_impl, + target = name + "_subject", + ) + +def _test_unrecognized_target_cpu_fails_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.contains("recognized OS and CPU constraints"), + ) + +_tests.append(_test_unrecognized_target_cpu_fails) + +def py_sdist_wheel_bzl_test_suite(name): + test_suite( + name = name, + tests = _tests, + ) diff --git a/tests/pypi/py_sdist_wheel/sdist_cext_test.py b/tests/pypi/py_sdist_wheel/sdist_cext_test.py new file mode 100644 index 0000000000..67b8b55260 --- /dev/null +++ b/tests/pypi/py_sdist_wheel/sdist_cext_test.py @@ -0,0 +1,59 @@ +"""Tests C-extension sdist building and determinism in py_sdist_wheel.""" + +from __future__ import annotations + +import importlib +import importlib.metadata +import pathlib +import sys +import tempfile +import unittest +import zipfile + +from python.runfiles import runfiles + + +class SdistCextTest(unittest.TestCase): + def test_import_cext_and_metadata(self): + rf = runfiles.Create() + assert rf is not None + rloc_a = rf.Rlocation( + "rules_python/tests/pypi/py_sdist_wheel/sdist_cext_a.whldir" + ) + assert rloc_a is not None + whls = list(pathlib.Path(rloc_a).glob("*.whl")) + self.assertEqual(len(whls), 1) + with tempfile.TemporaryDirectory() as tmp: + with zipfile.ZipFile(whls[0]) as zf: + zf.extractall(tmp) + sys.path.insert(0, tmp) + try: + sdist_cext = importlib.import_module("sdist_cext") + cext_demo = importlib.import_module("cext_demo") + self.assertEqual(sdist_cext.add_ints(19, 23), 42) + self.assertEqual(cext_demo.add_ints(100, 200), 300) + self.assertEqual(importlib.metadata.version("sdist-cext"), "0.1.0") + finally: + sys.path.remove(tmp) + + def test_wheel_determinism_across_distinct_scratch_dirs(self): + rf = runfiles.Create() + assert rf is not None + rloc_a = rf.Rlocation( + "rules_python/tests/pypi/py_sdist_wheel/sdist_cext_a.whldir" + ) + rloc_b = rf.Rlocation( + "rules_python/tests/pypi/py_sdist_wheel/sdist_cext_b.whldir" + ) + assert rloc_a is not None + assert rloc_b is not None + whls_a = list(pathlib.Path(rloc_a).glob("*.whl")) + whls_b = list(pathlib.Path(rloc_b).glob("*.whl")) + self.assertEqual(len(whls_a), 1) + self.assertEqual(len(whls_b), 1) + self.assertEqual(whls_a[0].name, whls_b[0].name) + self.assertEqual(whls_a[0].read_bytes(), whls_b[0].read_bytes()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/pypi/py_sdist_wheel/sdist_wheel_builder_test.py b/tests/pypi/py_sdist_wheel/sdist_wheel_builder_test.py new file mode 100644 index 0000000000..8db5ed635b --- /dev/null +++ b/tests/pypi/py_sdist_wheel/sdist_wheel_builder_test.py @@ -0,0 +1,260 @@ +"""Unit tests for sdist_wheel_builder and py_sdist_wheel.""" + +from __future__ import annotations + +import os +import pathlib +import subprocess +import sys +import tempfile +import unittest +import zipfile + +import sdist_wheel_builder +import sdist_wheel_helpers + +from python.runfiles import runfiles +from tests.pypi.py_sdist_wheel.make_test_sdist import write_sdist_tar + + +def _builder_env() -> dict[str, str]: + builder_dir = str(pathlib.Path(sdist_wheel_builder.__file__ or "").resolve().parent) + return { + **os.environ, + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONPATH": builder_dir, + } + + +class SdistWheelBuilderTest(unittest.TestCase): + def test_built_sdist_demo_whldir_and_whl_file(self): + rf = runfiles.Create() + assert rf is not None + whldir_rloc = rf.Rlocation( + "rules_python/tests/pypi/py_sdist_wheel/sdist_demo-0.5.0.whldir" + ) + assert whldir_rloc is not None + whls = list(pathlib.Path(whldir_rloc).glob("*.whl")) + self.assertEqual(len(whls), 1) + with zipfile.ZipFile(whls[0]) as zf: + init_text = zf.read("sdist_demo/__init__.py").decode("utf-8") + self.assertIn('GREETING = "patched_before_build"', init_text) + + # Verify the regular .sdist_build.whl File output has identical bytes, + # satisfies Gazelle modules_mapping get_wheel_name, and works with + # whl_filegroup. + whl_file_rloc = rf.Rlocation( + "rules_python/tests/pypi/py_sdist_wheel/sdist_demo-0.5.0.sdist_build.whl" + ) + assert whl_file_rloc is not None + whl_file_path = pathlib.Path(whl_file_rloc) + self.assertTrue(whl_file_path.is_file()) + self.assertEqual(whl_file_path.read_bytes(), whls[0].read_bytes()) + # Gazelle modules_mapping get_wheel_name check: suffix == ".whl" and prefix before "-" is dist + self.assertEqual(whl_file_path.suffix, ".whl") + self.assertEqual( + whl_file_path.name[: whl_file_path.name.find("-")], "sdist_demo" + ) + # PEP 427 wheel filename check: only 1 '-' so pip/uv reject it as invalid wheel filename + self.assertLess(whl_file_path.stem.count("-"), 4) + + whl_fg_rloc = rf.Rlocation( + "rules_python/tests/pypi/py_sdist_wheel/sdist_demo_whl_fg/sdist_demo/__init__.py" + ) + assert whl_fg_rloc is not None + self.assertIn( + 'GREETING = "patched_before_build"', + pathlib.Path(whl_fg_rloc).read_text(encoding="utf-8"), + ) + + for bare_name in ("sdist_demo_bare_a", "sdist_demo_bare_b"): + bare_rloc = rf.Rlocation( + f"rules_python/tests/pypi/py_sdist_wheel/{bare_name}.sdist_build.whl" + ) + assert bare_rloc is not None + self.assertTrue(pathlib.Path(bare_rloc).is_file()) + + def test_cross_platform_target_fails_before_build(self): + with tempfile.TemporaryDirectory() as tmp: + tmp_path = pathlib.Path(tmp) + proc = subprocess.run( + [ + sys.executable, + str(pathlib.Path(sdist_wheel_builder.__file__).resolve()), + "--sdist", + str(tmp_path / "unused.tar.gz"), + "--wheel-dir", + str(tmp_path / "out.whldir"), + "--target-os", + "nonexistent_os", + ], + capture_output=True, + text=True, + check=False, + env=_builder_env(), + ) + self.assertNotEqual(proc.returncode, 0) + self.assertIn( + "the default sdist builder only builds for the host", + proc.stderr, + ) + + def test_mismatched_target_python_version_fails_before_build(self): + with tempfile.TemporaryDirectory() as tmp: + tmp_path = pathlib.Path(tmp) + proc = subprocess.run( + [ + sys.executable, + str(pathlib.Path(sdist_wheel_builder.__file__).resolve()), + "--sdist", + str(tmp_path / "unused.tar.gz"), + "--wheel-dir", + str(tmp_path / "out.whldir"), + "--target-python-version", + "2.7", + ], + capture_output=True, + text=True, + check=False, + env=_builder_env(), + ) + self.assertNotEqual(proc.returncode, 0) + self.assertIn( + "Target Python version (2.7) differs from build Python interpreter", + proc.stderr, + ) + + def test_bad_pre_build_patch_fails(self): + with tempfile.TemporaryDirectory() as tmp: + tmp_path = pathlib.Path(tmp) + sdist_tar = write_sdist_tar( + tmp_path / "patch_fail-1.0.tar.gz", + { + "patch_fail-1.0/setup.py": ( + "from setuptools import setup\n" + "setup(name='patch-fail', version='1.0', packages=['patch_fail'])\n" + ), + "patch_fail-1.0/patch_fail/__init__.py": "X = 1\n", + }, + ) + bad_patch = tmp_path / "bad.patch" + bad_patch.write_text( + "--- a/patch_fail/__init__.py\n" + "+++ b/patch_fail/__init__.py\n" + "@@ -1,1 +1,1 @@\n" + "-DOES_NOT_MATCH = 1\n" + "+X = 2\n", + encoding="utf-8", + ) + proc = subprocess.run( + [ + sys.executable, + str(pathlib.Path(sdist_wheel_builder.__file__).resolve()), + "--sdist", + str(sdist_tar), + "--wheel-dir", + str(tmp_path / "out.whldir"), + "--patch", + f"{bad_patch}:1", + ], + capture_output=True, + text=True, + check=False, + env=_builder_env(), + ) + self.assertNotEqual(proc.returncode, 0) + self.assertIn("context mismatch", proc.stderr) + + def test_dep_file_conflict_fails(self): + with tempfile.TemporaryDirectory() as tmp: + tmp_path = pathlib.Path(tmp) + fp_a = tmp_path / "src/util/__init__.py" + fp_b = tmp_path / "bin/util/__init__.py" + fp_a.parent.mkdir(parents=True, exist_ok=True) + fp_b.parent.mkdir(parents=True, exist_ok=True) + fp_a.write_text("A = 1\n", encoding="utf-8") + fp_b.write_text("B = 2\n", encoding="utf-8") + with self.assertRaisesRegex( + ValueError, + "Conflicting build_deps files map to the same path '_main/util/__init__.py'", + ): + sdist_wheel_builder._stage_dep_files( + deps_dir=tmp_path / "deps", + prefix=tmp_path, + workspace_name="_main", + import_roots=["_main"], + dep_files=[ + "src/util/__init__.py=util/__init__.py", + "bin/util/__init__.py=util/__init__.py", + ], + ) + + def test_missing_import_root_fails_and_non_wheel_bin_ignored(self): + with tempfile.TemporaryDirectory() as tmp: + tmp_path = pathlib.Path(tmp) + fp = tmp_path / "external/pypi_foo/site-packages/foo/__init__.py" + fp.parent.mkdir(parents=True, exist_ok=True) + fp.write_text("X = 1\n", encoding="utf-8") + with self.assertRaisesRegex( + ValueError, + "Import root 'site-packages' does not exist under staged build_deps", + ): + sdist_wheel_builder._stage_dep_files( + deps_dir=tmp_path / "deps", + prefix=tmp_path, + workspace_name="_main", + import_roots=["site-packages"], + dep_files=[ + "external/pypi_foo/site-packages/foo/__init__.py=../pypi_foo/site-packages/foo/__init__.py" + ], + ) + + non_wheel = tmp_path / "non_wheel_tree" + (non_wheel / "bin").mkdir(parents=True, exist_ok=True) + wheel_py, _, bin_dirs = ( + sdist_wheel_builder._resolve_wheel_and_bootstrap_paths( + tmp_path, ["non_wheel_tree"], [] + ) + ) + self.assertEqual(wheel_py, []) + self.assertEqual(bin_dirs, []) + + def test_apply_unified_patch_carries_relocated_hunk_offset(self): + patch_text = ( + "--- a/sample.txt\n" + "+++ b/sample.txt\n" + "@@ -1 +1 @@\n" + "-a\n" + "+A\n" + "@@ -2,0 +3 @@\n" + "+X\n" + ) + with tempfile.TemporaryDirectory() as tmp: + tmp_path = pathlib.Path(tmp) + patch_file = tmp_path / "relocated.patch" + patch_file.write_text(patch_text, encoding="utf-8") + + # First hunk relocates from line 1 to line 2; second zero-context + # hunk must carry that +1 shift and insert after 'b'. + relocated_dir = tmp_path / "relocated" + relocated_dir.mkdir() + (relocated_dir / "sample.txt").write_text("prefix\na\nb\n", encoding="utf-8") + sdist_wheel_helpers.apply_unified_patch(relocated_dir, patch_file, strip=1) + self.assertEqual( + (relocated_dir / "sample.txt").read_text(encoding="utf-8"), + "prefix\nA\nb\nX\n", + ) + + # When no relocation occurs, placement is unchanged. + exact_dir = tmp_path / "exact" + exact_dir.mkdir() + (exact_dir / "sample.txt").write_text("a\nb\n", encoding="utf-8") + sdist_wheel_helpers.apply_unified_patch(exact_dir, patch_file, strip=1) + self.assertEqual( + (exact_dir / "sample.txt").read_text(encoding="utf-8"), + "A\nb\nX\n", + ) + + +if __name__ == "__main__": + unittest.main()