From bc9a0d6265db486d53cd3db1ee7e59aaa82abad8 Mon Sep 17 00:00:00 2001 From: Jeremy Volkman Date: Sat, 31 Oct 2026 20:41:31 +0000 Subject: [PATCH 1/9] feat(pypi): add experimental_action_install mode for wheels Extracting wheels during the repository phase materializes thousands of individual files per wheel into external repository directories and glob()-expanded py_library targets. In large workspaces with many third-party dependencies, this inflates fetch times, loading-phase memory, and sandbox symlink creation overhead. Add an opt-in experimental_action_install attribute (and RULES_PYTHON_EXPERIMENTAL_ACTION_INSTALL environment variable) on pip.parse, pip_parse, and whl_library that defers wheel extraction and installation to a build action: * At repository fetch time, inspect the wheel zip central directory to record metadata, console-script entry points, script shebang names, and namespace package paths without extracting wheel payloads to disk. * At build time, unpack and install the wheel into a single directory artifact via a new py_wheel_library rule using the exec_tools toolchain, supporting bytecode precompilation, sourceless mode, virtual environment site-packages symlinks, and stub exposure through PyInfo. * Emit clear diagnostics when repository-phase features incompatible with build-time wheel extraction (such as custom glob filegroups or wheel-internal copy_files sources) are configured. --- .bazelci/presubmit.yml | 27 + MODULE.bazel | 2 + docs/environment-variables.md | 16 + docs/pypi/use.md | 4 +- news/experimental-action-install.added.md | 2 + python/private/common.bzl | 25 +- python/private/internal_dev_deps.bzl | 43 +- python/private/py_info.bzl | 8 +- python/private/pypi/BUILD.bazel | 57 ++ python/private/pypi/action_whl_installer.py | 546 +++++++++++++++++ python/private/pypi/attrs.bzl | 64 ++ python/private/pypi/extension.bzl | 5 +- .../pypi/generate_whl_library_build_bazel.bzl | 25 + python/private/pypi/hub_builder.bzl | 12 +- python/private/pypi/inspect_whl.py | 136 +++++ python/private/pypi/labels.bzl | 5 + python/private/pypi/patch_and_extract_whl.bzl | 175 +++++- python/private/pypi/pip_archive.bzl | 2 - python/private/pypi/pip_repository.bzl | 8 +- python/private/pypi/py_wheel_library.bzl | 410 +++++++++++++ python/private/pypi/wheel_layout.py | 344 +++++++++++ python/private/pypi/whl_archive.bzl | 12 +- python/private/pypi/whl_library.bzl | 45 +- python/private/pypi/whl_library_srcs.bzl | 177 +++++- python/private/pypi/whl_library_targets.bzl | 12 + tests/pypi/extension/pip_parse.bzl | 2 + ...generate_whl_library_build_bazel_tests.bzl | 117 ++++ tests/pypi/hub_builder/hub_builder_tests.bzl | 90 +++ tests/pypi/py_wheel_library/BUILD.bazel | 12 + .../py_wheel_library_bzl_tests.bzl | 288 +++++++++ .../wheel_layout_and_installer_test.py | 548 ++++++++++++++++++ .../whl_library_srcs_tests.bzl | 201 +++++++ tests/support/py_reconfig.bzl | 8 + .../app_files_building_tests.bzl | 99 ++-- .../tree_conflicts/BUILD.bazel | 88 +++ .../fp/site-packages/foo/plugins/c.py | 1 + .../fp/site-packages/gns/gamma/__init__.py | 1 + .../tree_conflicts/fp/site-packages/pk/z.py | 1 + .../fp2/site-packages/bar/__init__.py | 1 + .../tree_conflicts/fp2/site-packages/bar/m.py | 1 + .../tree_conflicts/testdata/wa/bar/ext/e.py | 1 + .../testdata/wa/foo/__init__.py | 1 + .../tree_conflicts/testdata/wa/foo/a.py | 1 + .../testdata/wa/foo/plugins/shared.py | 1 + .../testdata/wa/gns/alpha/__init__.py | 1 + .../testdata/wa/gns/libs/libdummy_a.so | 1 + .../tree_conflicts/testdata/wa/pk/__init__.py | 2 + .../tree_conflicts/testdata/wa/pk/x.py | 1 + .../scripts/tc_a_only | 2 + .../tree_conflict_a-1.0.data/scripts/tc_tool | 2 + .../wa/tree_conflict_a-1.0.dist-info/METADATA | 3 + .../wa/tree_conflict_a-1.0.dist-info/RECORD | 0 .../wa/tree_conflict_a-1.0.dist-info/WHEEL | 4 + .../testdata/wb/foo/plugins/b.py | 1 + .../testdata/wb/foo/plugins/shared.py | 1 + .../testdata/wb/gns/beta/__init__.py | 1 + .../testdata/wb/gns/libs/helper.py | 1 + .../testdata/wb/gns/libs/libdummy_b.so | 1 + .../tree_conflicts/testdata/wb/pk/__init__.py | 2 + .../tree_conflicts/testdata/wb/pk/y.py | 1 + .../scripts/tc_b_only | 2 + .../tree_conflict_b-1.0.data/scripts/tc_tool | 2 + .../wb/tree_conflict_b-1.0.dist-info/METADATA | 3 + .../wb/tree_conflict_b-1.0.dist-info/RECORD | 0 .../wb/tree_conflict_b-1.0.dist-info/WHEEL | 4 + .../tree_conflicts/tree_conflicts_test.py | 152 +++++ 66 files changed, 3673 insertions(+), 138 deletions(-) create mode 100644 news/experimental-action-install.added.md create mode 100644 python/private/pypi/action_whl_installer.py create mode 100644 python/private/pypi/inspect_whl.py create mode 100644 python/private/pypi/py_wheel_library.bzl create mode 100644 python/private/pypi/wheel_layout.py create mode 100644 tests/pypi/py_wheel_library/BUILD.bazel create mode 100644 tests/pypi/py_wheel_library/py_wheel_library_bzl_tests.bzl create mode 100644 tests/pypi/py_wheel_library/wheel_layout_and_installer_test.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/BUILD.bazel create mode 100644 tests/venv_site_packages_libs/tree_conflicts/fp/site-packages/foo/plugins/c.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/fp/site-packages/gns/gamma/__init__.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/fp/site-packages/pk/z.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/fp2/site-packages/bar/__init__.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/fp2/site-packages/bar/m.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wa/bar/ext/e.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wa/foo/__init__.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wa/foo/a.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wa/foo/plugins/shared.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wa/gns/alpha/__init__.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wa/gns/libs/libdummy_a.so create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wa/pk/__init__.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wa/pk/x.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.data/scripts/tc_a_only create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.data/scripts/tc_tool create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.dist-info/METADATA create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.dist-info/RECORD create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.dist-info/WHEEL create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wb/foo/plugins/b.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wb/foo/plugins/shared.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wb/gns/beta/__init__.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wb/gns/libs/helper.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wb/gns/libs/libdummy_b.so create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wb/pk/__init__.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wb/pk/y.py create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.data/scripts/tc_b_only create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.data/scripts/tc_tool create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.dist-info/METADATA create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.dist-info/RECORD create mode 100644 tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.dist-info/WHEEL create mode 100644 tests/venv_site_packages_libs/tree_conflicts/tree_conflicts_test.py diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index c5ccd9b69b..b2a2a23334 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -241,6 +241,33 @@ tasks: name: "Default: Ubuntu, Bazel {bazel}" platform: ubuntu2204 bazel: ${{ bazel }} + ubuntu_action_install: + <<: *reusable_config + name: "Action install: Ubuntu" + platform: ubuntu2204 + build_flags: + <<: *reusable_config_build_flags + ? "--repo_env=RULES_PYTHON_EXPERIMENTAL_ACTION_INSTALL=1" + # pyrefly aspect does not yet support TreeArtifact directory sources + ? "--output_groups=-pyrefly" + test_flags: &action_install_test_flags + <<: *reusable_config_test_flags + ? "--repo_env=RULES_PYTHON_EXPERIMENTAL_ACTION_INSTALL=1" + # pyrefly aspect does not yet support TreeArtifact directory sources + ? "--output_groups=-pyrefly" + ubuntu_action_install_venvs: + name: "Action install (venvs_site_packages): Ubuntu" + platform: ubuntu2204 + test_flags: + <<: *action_install_test_flags + ? "--//python/config_settings:venvs_site_packages=yes" + test_targets: + - "--" + - "//tests/entry_points/..." + - "//tests/implicit_namespace_packages/..." + - "//tests/pypi/..." + - "//tests/venv_site_packages_libs/..." + - "//tests/whl_with_build_files/..." ubuntu_upcoming: <<: *reusable_config name: "Default: Ubuntu, upcoming Bazel" diff --git a/MODULE.bazel b/MODULE.bazel index 98ae8114b5..34cc0b692e 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -333,6 +333,8 @@ use_repo( "pkgutil_nspkg2", "rules_python_runtime_env_tc_info", "somepkg_with_build_files", + "tree_conflict_a", + "tree_conflict_b", "whl_library_extras_direct_dep", "whl_with_build_files", "whl_with_data1", diff --git a/docs/environment-variables.md b/docs/environment-variables.md index 8ac7a939b2..1b1738c132 100644 --- a/docs/environment-variables.md +++ b/docs/environment-variables.md @@ -52,6 +52,22 @@ When `1`, `rules_python` will warn users about deprecated functionality that wil be removed in a subsequent major `rules_python` version. Defaults to `0` if unset. ::: +::::{envvar} RULES_PYTHON_EXPERIMENTAL_ACTION_INSTALL + +When set to `1` or `true` (case-insensitive), wheel extraction and installation +in `pip.parse` (and WORKSPACE `pip_parse`) are deferred to a Bazel build action +(`py_wheel_library`) producing a directory artifact (`TreeArtifact`) rather than +extracting wheel contents during the repository phase. Setting it to `0`, +`false`, or `""` disables action-based wheel installation, overriding +`experimental_action_install = True` on `pip.parse`. Any other value is an +error. + +See {bzl:attr}`pip.parse.experimental_action_install` for details and caveats. + +:::{versionadded} VERSION_NEXT_FEATURE +::: +:::: + ::::{envvar} RULES_PYTHON_EXTRACT_ROOT Directory to use as the root for creating files necessary for bootstrapping so diff --git a/docs/pypi/use.md b/docs/pypi/use.md index 9d0c54c4ab..31be148a3c 100644 --- a/docs/pypi/use.md +++ b/docs/pypi/use.md @@ -39,7 +39,9 @@ Note that the hub repo contains the following targets for each package: rules. * `@pypi//numpy:data` - the {obj}`filegroup` for all of the extra files that are included as data in the `pkg` target. -* `@pypi//numpy:dist_info` - the {obj}`filegroup` for all of the files in the `.distinfo` directory. +* `@pypi//numpy:dist_info` - the {obj}`filegroup` for all of the files in the + `.distinfo` directory (or only `entry_points.txt` + when `experimental_action_install` is enabled). * `@pypi//numpy:extracted_whl_files` - a {obj}`filegroup` of all the files extracted from the whl file. * `@pypi//numpy:whl` - the {obj}`filegroup` that is the `.whl` file itself, which includes all diff --git a/news/experimental-action-install.added.md b/news/experimental-action-install.added.md new file mode 100644 index 0000000000..8a5a2609d0 --- /dev/null +++ b/news/experimental-action-install.added.md @@ -0,0 +1,2 @@ +(pypi) Added experimental {bzl:attr}`pip.parse.experimental_action_install` to +defer wheel extraction and installation to a build action. diff --git a/python/private/common.bzl b/python/private/common.bzl index 2d4c48d8d5..fb7922f49f 100644 --- a/python/private/common.bzl +++ b/python/private/common.bzl @@ -381,7 +381,10 @@ def create_py_info( implicit_pyc_files, implicit_pyc_source_files, imports, - venv_symlinks = []): + venv_symlinks = [], + pyi_files = None, + srcs_version = None, + pyi_deps = None): """Create PyInfo provider. Args: @@ -401,26 +404,32 @@ def create_py_info( imports: depset of strings; the import path values to propagate. venv_symlinks: {type}`list[VenvSymlinkEntry]` instances for symlinks to create in the consuming binary's venv. + pyi_files: `list[File] | None`; override for `ctx.files.pyi_srcs`. + srcs_version: `str | None`; override for `ctx.attr.srcs_version`. + pyi_deps: `list[Target] | None`; override for `ctx.attr.pyi_deps`. Returns: A tuple of the PyInfo instance and a depset of the transitive sources collected from dependencies (the latter is only necessary for deprecated extra actions support). """ + pyi_srcs = ctx.files.pyi_srcs if pyi_files == None else pyi_files + srcs_version = ctx.attr.srcs_version if srcs_version == None else srcs_version + pyi_deps = ctx.attr.pyi_deps if pyi_deps == None else pyi_deps py_info = PyInfoBuilder.new() py_info.venv_symlinks.add(venv_symlinks) py_info.direct_original_sources.add(original_sources) py_info.direct_pyc_files.add(required_pyc_files) - py_info.direct_pyi_files.add(ctx.files.pyi_srcs) + py_info.direct_pyi_files.add(pyi_srcs) py_info.transitive_original_sources.add(original_sources) py_info.transitive_pyc_files.add(required_pyc_files) - py_info.transitive_pyi_files.add(ctx.files.pyi_srcs) + py_info.transitive_pyi_files.add(pyi_srcs) py_info.direct_implicit_pyc_files.add(implicit_pyc_files) py_info.transitive_implicit_pyc_files.add(implicit_pyc_files) py_info.transitive_implicit_pyc_source_files.add(implicit_pyc_source_files) py_info.imports.add(imports) - py_info.merge_has_py2_only_sources(ctx.attr.srcs_version in ("PY2", "PY2ONLY")) - py_info.merge_has_py3_only_sources(ctx.attr.srcs_version in ("PY3", "PY3ONLY")) + py_info.merge_has_py2_only_sources(srcs_version in ("PY2", "PY2ONLY")) + py_info.merge_has_py3_only_sources(srcs_version in ("PY3", "PY3ONLY")) for target in ctx.attr.deps: # PyInfo may not be present e.g. cc_library rules. @@ -438,7 +447,7 @@ def create_py_info( hasattr(ctx.attr, "_pyi_deps_to_runfiles_flag") and PyiDepsToRunfilesFlag.is_enabled(ctx) ) - for target in ctx.attr.pyi_deps: + for target in pyi_deps: # PyInfo may not be present e.g. cc_library rules. if PyInfo in target or (BuiltinPyInfo != None and BuiltinPyInfo in target): target_py_info = _get_py_info(target) @@ -473,10 +482,10 @@ def create_py_info( def _get_py_info(target): return target[PyInfo] if PyInfo in target or BuiltinPyInfo == None else target[BuiltinPyInfo] -def create_instrumented_files_info(ctx): +def create_instrumented_files_info(ctx, source_attributes = ["srcs"]): return _coverage_common.instrumented_files_info( ctx, - source_attributes = ["srcs"], + source_attributes = source_attributes, dependency_attributes = ["deps", "data"], extensions = _PYTHON_SOURCE_EXTENSIONS, ) diff --git a/python/private/internal_dev_deps.bzl b/python/private/internal_dev_deps.bzl index 5bbee232f9..f7d41ab50f 100644 --- a/python/private/internal_dev_deps.bzl +++ b/python/private/internal_dev_deps.bzl @@ -14,12 +14,23 @@ """Module extension for internal dev_dependency=True setup.""" load("@bazel_ci_rules//:rbe_repo.bzl", "rbe_preconfig") +load("@pythons_hub//:interpreters.bzl", "INTERPRETER_LABELS") +load("@pythons_hub//:versions.bzl", "DEFAULT_PYTHON_VERSION") +load("//python/private/pypi:attrs.bzl", "use_action_install") load("//python/private/pypi:whl_library.bzl", "whl_library") load("//tests/support/whl_from_dir:whl_from_dir_repo.bzl", "whl_from_dir_repo") load(":runtime_env_repo.bzl", "runtime_env_repo") def _internal_dev_deps_impl(mctx): - _ = mctx # @unused + whl_library_kwargs = {} + if use_action_install(mctx, struct(experimental_action_install = False)): + host_key = "python_{}_host".format( + DEFAULT_PYTHON_VERSION.replace(".", "_"), + ) + whl_library_kwargs = { + "experimental_action_install": True, + "python_interpreter_target": INTERPRETER_LABELS[host_key], + } # Creates a default toolchain config for RBE. # Use this as is if you are using the rbe_ubuntu16_04 container, @@ -40,6 +51,7 @@ def _internal_dev_deps_impl(mctx): name = "somepkg_with_build_files", whl_file = "@whl_with_build_files//:somepkg-1.0-any-none-any.whl", requirement = "somepkg", + **whl_library_kwargs ) # Setup for //tests/implicit_namespace_packages @@ -53,6 +65,7 @@ def _internal_dev_deps_impl(mctx): whl_file = "@implicit_namespace_ns_sub1_whl//:ns_sub1-1.0-any-none-any.whl", requirement = "ns-sub1", enable_implicit_namespace_pkgs = False, + **whl_library_kwargs ) whl_from_dir_repo( @@ -65,6 +78,7 @@ def _internal_dev_deps_impl(mctx): whl_file = "@implicit_namespace_ns_sub2_whl//:ns_sub2-1.0-any-none-any.whl", requirement = "ns-sub2", enable_implicit_namespace_pkgs = False, + **whl_library_kwargs ) whl_from_dir_repo( @@ -77,6 +91,7 @@ def _internal_dev_deps_impl(mctx): whl_file = "@pkgutil_nspkg1_whl//:pkgutil_nspkg1-1.0-any-none-any.whl", requirement = "pkgutil_nspkg1", enable_implicit_namespace_pkgs = False, + **whl_library_kwargs ) whl_from_dir_repo( @@ -89,6 +104,7 @@ def _internal_dev_deps_impl(mctx): whl_file = "@pkgutil_nspkg2_whl//:pkgutil_nspkg2-1.0-any-none-any.whl", requirement = "pkgutil_nspkg2", enable_implicit_namespace_pkgs = False, + **whl_library_kwargs ) whl_from_dir_repo( @@ -100,6 +116,7 @@ def _internal_dev_deps_impl(mctx): name = "whl_with_data1", whl_file = "@whl_with_data1_whl//:whl_with_data1-1.0-any-none-any.whl", requirement = "whl-with-data1", + **whl_library_kwargs ) whl_from_dir_repo( @@ -111,6 +128,7 @@ def _internal_dev_deps_impl(mctx): name = "whl_with_data2", whl_file = "@whl_with_data2_whl//:whl_with_data2-1.0-any-none-any.whl", requirement = "whl-with-data2", + **whl_library_kwargs ) _whl_library_from_dir( @@ -121,6 +139,7 @@ def _internal_dev_deps_impl(mctx): # The following is necessary to enable pipstar and make tests faster config_load = "@rules_python//tests/pypi/whl_library/testdata:packages.bzl", dep_template = "@whl_library_extras_{name}//:{target}", + **whl_library_kwargs ) _whl_library_from_dir( name = "whl_library_extras_optional_dep", @@ -129,6 +148,7 @@ def _internal_dev_deps_impl(mctx): requirement = "optional_dep", # The following is necessary to enable pipstar and make tests faster config_load = "@rules_python//tests/pypi/whl_library/testdata:packages.bzl", + **whl_library_kwargs ) # Setup for //tests/pypi/patch_whl/patch_whl_patch_test.py @@ -147,8 +167,29 @@ def _internal_dev_deps_impl(mctx): "whls": ["pkg-1.0-any-none-any.whl"], }), }, + **whl_library_kwargs ) + # Setup for //tests/venv_site_packages_libs/tree_conflicts + for suffix in ("a", "b"): + whl_from_dir_repo( + name = "tree_conflict_{}_whl".format(suffix), + root = "//tests/venv_site_packages_libs/tree_conflicts:testdata/w{}/BUILD.bazel".format( + suffix, + ), + output = "tree_conflict_{}-1.0-py3-none-any.whl".format(suffix), + ) + whl_library( + name = "tree_conflict_{}".format(suffix), + whl_file = "@tree_conflict_{}_whl//:tree_conflict_{}-1.0-py3-none-any.whl".format( + suffix, + suffix, + ), + requirement = "tree-conflict-{}".format(suffix), + enable_implicit_namespace_pkgs = False, + **whl_library_kwargs + ) + def _whl_library_from_dir(*, name, output, root, **kwargs): whl_from_dir_repo( name = "{}_whl".format(name), diff --git a/python/private/py_info.bzl b/python/private/py_info.bzl index c04cb26083..9b9a47b2c3 100644 --- a/python/private/py_info.bzl +++ b/python/private/py_info.bzl @@ -521,7 +521,9 @@ program. :::{note} This may contain implementation-specific file types specific to a particular -type checker. +type checker. When `experimental_action_install` is enabled, this depset may +also contain directory `File` objects (`TreeArtifact`s) for wheel targets that +ship `.pyi` stubs or `py.typed` markers; consumers must handle directories. ::: ::::{versionadded} 1.1.0 @@ -602,7 +604,9 @@ program. :::{note} This may contain implementation-specific file types specific to a particular -type checker. +type checker. When `experimental_action_install` is enabled, this depset may +also contain directory `File` objects (`TreeArtifact`s) for wheel targets that +ship `.pyi` stubs or `py.typed` markers; consumers must handle directories. ::: ::::{versionadded} 1.1.0 diff --git a/python/private/pypi/BUILD.bazel b/python/private/pypi/BUILD.bazel index c5331fd899..9d51b388ec 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,23 @@ exports_files( visibility = ["//visibility:public"], ) +filegroup( + name = "action_whl_installer_helpers", + srcs = [ + "namespace_pkg_tmpl.py", + "venv_shebang_rewriter.py", + "wheel_layout.py", + "wheel_record_rewriter.py", + ], +) + +py_interpreter_program( + name = "action_whl_installer", + interpreter_args = ["-B"], + main = "action_whl_installer.py", + visibility = ["//visibility:public"], +) + py_library( name = "rewriters_lib", srcs = [ @@ -35,6 +53,19 @@ py_library( visibility = ["//tests:__subpackages__"], ) +py_library( + name = "wheel_installer_lib", + srcs = [ + "action_whl_installer.py", + "inspect_whl.py", + "wheel_layout.py", + ], + data = ["namespace_pkg_tmpl.py"], + imports = ["."], + visibility = ["//tests:__subpackages__"], + deps = [":rewriters_lib"], +) + alias( name = "venv_entry_point_template", actual = select({ @@ -334,6 +365,7 @@ bzl_library( name = "pip_repository", srcs = ["pip_repository.bzl"], deps = [ + ":attrs", ":default_platforms", ":hash", ":parse_requirements", @@ -601,6 +633,7 @@ bzl_library( srcs = ["patch_and_extract_whl.bzl"], deps = [ ":generate_whl_library_build_bazel", + ":labels", ":patch_whl", ":pep508_requirement", ":pypi_repo_utils", @@ -623,6 +656,29 @@ bzl_library( ], ) +bzl_library( + name = "py_wheel_library", + srcs = ["py_wheel_library.bzl"], + deps = [ + "//python/private:attr_builders", + "//python/private:attributes", + "//python/private:builders", + "//python/private:common", + "//python/private:flags", + "//python/private:normalize_name", + "//python/private:py_cc_link_params_info", + "//python/private:py_info", + "//python/private:py_interpreter_program", + "//python/private:py_library", + "//python/private:reexports", + "//python/private:rule_builders", + "//python/private:toolchain_types", + "//python/private:venv_runfiles", + "//python/private:version", + "@bazel_skylib//lib:paths", + ], +) + bzl_library( name = "whl_library_srcs", srcs = ["whl_library_srcs.bzl"], @@ -630,6 +686,7 @@ bzl_library( ":gen_wheel_record", ":labels", ":namespace_pkgs", + ":py_wheel_library", ":venv_entry_point", ":venv_rewrite_shebang", "//python:py_library", diff --git a/python/private/pypi/action_whl_installer.py b/python/private/pypi/action_whl_installer.py new file mode 100644 index 0000000000..3247fa3997 --- /dev/null +++ b/python/private/pypi/action_whl_installer.py @@ -0,0 +1,546 @@ +"""Build-action tool to extract and install a wheel into a TreeArtifact directory. + +Extracts wheel entries into `/site-packages`, `/bin`, +`/data`, and `/include`, rewrites `#!python` script +shebangs and `.data` `RECORD` entries, optionally populates pkgutil namespace +`__init__.py` files, and optionally precompiles `.py` files. + +Usage: + python3 -B action_whl_installer.py --wheel path/to/pkg.whl \\ + --directory path/to/out_dir [--target-os unix|windows] \\ + [--create-namespace-inits] [--precompile --pyc-tag cpython-311] +""" + +from __future__ import annotations + +import argparse +import os +import py_compile +import re +import shutil +import subprocess +import sys +import tempfile +import zipfile +from collections.abc import Sequence +from pathlib import Path + +import wheel_layout +from venv_shebang_rewriter import rewrite_shebang_bytes +from wheel_layout import ( + INSTALLER_URL, + create_namespace_inits, + expected_data_dir_for_dist_info, + find_wheel_dist_info_and_entry_points, + glob_to_regex, + is_excluded, + plan_wheel_entries, + update_record_for_touched_files, +) +from wheel_record_rewriter import rewrite_record_lines + +_NAMESPACE_PKG_TMPL_PATH = ( + Path(wheel_layout.__file__ or "").parent / "namespace_pkg_tmpl.py" +) + +_CompileItem = tuple[Path, str, str, Path] + + +def _check_in_process_python_version(python_version: str) -> None: + if not python_version: + return + major_str, _, minor_str = python_version.partition(".") + expected_ver = (int(major_str), int(minor_str)) + actual_ver = (sys.version_info.major, sys.version_info.minor) + if actual_ver != expected_ver: + raise ValueError( + f"Python version mismatch for precompile: target python_version is " + f"{expected_ver[0]}.{expected_ver[1]}, but py_exec_tools_toolchain's " + f"exec_interpreter is {actual_ver[0]}.{actual_ver[1]}. Register an " + f"exec_tools toolchain matching the target Python version or disable precompile." + ) + + +def _write_syntax_error_stub_pyc( + pyc_path: Path, + src_name: str, + exc: BaseException | str, + *, + optimize_level: int, + inv_mode: py_compile.PycInvalidationMode, +) -> None: + syn: SyntaxError | None = None + if isinstance(exc, py_compile.PyCompileError) and isinstance( + exc.exc_value, SyntaxError + ): + syn = exc.exc_value + elif isinstance(exc, SyntaxError): + syn = exc + + if syn is not None: + stub_src = ( + f"raise SyntaxError({syn.msg!r}, " + f"({src_name!r}, {syn.lineno!r}, {syn.offset!r}, {syn.text!r}))\n" + ) + else: + stub_src = ( + f"raise SyntaxError({str(exc)!r}, ({src_name!r}, None, None, None))\n" + ) + + pyc_path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile( + mode="w", encoding="utf-8", suffix=".py", delete=False + ) as stub_f: + stub_path = Path(stub_f.name) + stub_f.write(stub_src) + try: + py_compile.compile( + str(stub_path), + cfile=str(pyc_path), + dfile=src_name, + doraise=True, + optimize=optimize_level, + invalidation_mode=inv_mode, + ) + finally: + stub_path.unlink(missing_ok=True) + + +def _run_precompiler_batch( + precompiler_tool: Path, + items: list[_CompileItem], + *, + invalidation_mode: str, + optimize_level: int, + python_version: str, +) -> bool: + lines = [ + "--invalidation_mode", + invalidation_mode, + "--optimize", + str(optimize_level), + "--python_version", + python_version, + ] + for py_path, _, src_name, pyc_path in items: + lines.extend( + [ + "--src", + str(py_path), + "--src_name", + src_name, + "--pyc", + str(pyc_path), + ] + ) + with tempfile.NamedTemporaryFile( + mode="w", encoding="utf-8", suffix=".params", delete=False + ) as pf: + param_path = Path(pf.name) + pf.write("\n".join(lines) + "\n") + try: + proc = subprocess.run([str(precompiler_tool), f"@{param_path}"], check=False) + return proc.returncode == 0 + finally: + param_path.unlink(missing_ok=True) + + +def _compile_batch_or_bisect( + precompiler_tool: Path, + items: list[_CompileItem], + site_packages_dir: Path, + touched: set[str], + *, + invalidation_mode: str, + inv_mode: py_compile.PycInvalidationMode, + optimize_level: int, + source_retention: str, + python_version: str, +) -> None: + if _run_precompiler_batch( + precompiler_tool, + items, + invalidation_mode=invalidation_mode, + optimize_level=optimize_level, + python_version=python_version, + ): + for py_path, rel_to_site, _, pyc_path in items: + touched.add(pyc_path.relative_to(site_packages_dir).as_posix()) + if source_retention == "omit_source": + py_path.unlink() + touched.add(rel_to_site) + return + + if len(items) == 1: + _, rel_to_site, src_name, pyc_path = items[0] + print( + f"WARNING: skipping precompilation of {rel_to_site}: custom precompiler exited non-zero", + file=sys.stderr, + ) + _write_syntax_error_stub_pyc( + pyc_path, + src_name, + f"Failed to precompile {src_name}", + optimize_level=optimize_level, + inv_mode=inv_mode, + ) + touched.add(pyc_path.relative_to(site_packages_dir).as_posix()) + return + + mid = len(items) // 2 + for half in (items[:mid], items[mid:]): + _compile_batch_or_bisect( + precompiler_tool, + half, + site_packages_dir, + touched, + invalidation_mode=invalidation_mode, + inv_mode=inv_mode, + optimize_level=optimize_level, + source_retention=source_retention, + python_version=python_version, + ) + + +def _compile_in_process( + items: list[_CompileItem], + site_packages_dir: Path, + *, + inv_mode: py_compile.PycInvalidationMode, + optimize_level: int, + source_retention: str, +) -> set[str]: + touched: set[str] = set() + for py_path, rel_to_site, src_name, pyc_path in items: + try: + py_compile.compile( + str(py_path), + cfile=str(pyc_path), + dfile=src_name, + doraise=True, + optimize=optimize_level, + invalidation_mode=inv_mode, + ) + except (py_compile.PyCompileError, SyntaxError, ValueError) as exc: + print( + f"WARNING: skipping precompilation of {rel_to_site}: {exc}", + file=sys.stderr, + ) + _write_syntax_error_stub_pyc( + pyc_path, + src_name, + exc, + optimize_level=optimize_level, + inv_mode=inv_mode, + ) + touched.add(pyc_path.relative_to(site_packages_dir).as_posix()) + continue + + touched.add(pyc_path.relative_to(site_packages_dir).as_posix()) + if source_retention == "omit_source": + py_path.unlink() + touched.add(rel_to_site) + return touched + + +def precompile_site_packages( + dest_dir: Path, + site_packages_dir: Path, + *, + pyc_tag: str, + invalidation_mode: str = "checked_hash", + optimize_level: int = 0, + source_retention: str = "keep_source", + python_version: str = "", + src_name_prefix: str = "", + precompiler_tool: Path | None = None, +) -> set[str]: + """Compile `.py` files under `site_packages_dir` and return touched site-packages relative paths.""" + if not pyc_tag: + raise ValueError("precompile requires a non-empty --pyc-tag") + if precompiler_tool is None: + _check_in_process_python_version(python_version) + + py_files = sorted( + p + for p in site_packages_dir.rglob("*.py") + if p.is_file() and "__pycache__" not in p.relative_to(site_packages_dir).parts + ) + if not py_files: + return set() + + compile_items: list[_CompileItem] = [] + for py_path in py_files: + rel_to_dest = py_path.relative_to(dest_dir).as_posix() + rel_to_site = py_path.relative_to(site_packages_dir).as_posix() + src_name = ( + f"{src_name_prefix.rstrip('/')}/{rel_to_dest}" + if src_name_prefix + else rel_to_dest + ) + if source_retention == "omit_source": + pyc_path = py_path.with_suffix(".pyc") + else: + # Note: optimize_level > 0 retains `{stem}.{pyc_tag}.pyc` naming (rather + # than `.opt-N.pyc`) to match `py_library`'s precompiler behavior. + pycache_dir = py_path.parent / "__pycache__" + pycache_dir.mkdir(parents=True, exist_ok=True) + pyc_path = pycache_dir / f"{py_path.stem}.{pyc_tag}.pyc" + compile_items.append((py_path, rel_to_site, src_name, pyc_path)) + + inv_mode = py_compile.PycInvalidationMode[invalidation_mode.upper()] + if precompiler_tool is None: + return _compile_in_process( + compile_items, + site_packages_dir, + inv_mode=inv_mode, + optimize_level=optimize_level, + source_retention=source_retention, + ) + + touched: set[str] = set() + _compile_batch_or_bisect( + precompiler_tool, + compile_items, + site_packages_dir, + touched, + invalidation_mode=invalidation_mode, + inv_mode=inv_mode, + optimize_level=optimize_level, + source_retention=source_retention, + python_version=python_version, + ) + return touched + + +def _write_rewritten_script( + dest_dir: Path, + script_name: str, + raw_bytes: bytes, + target_os: str, +) -> None: + rewritten = rewrite_shebang_bytes(raw_bytes, target_os) + out_script_name = f"{script_name}.bat" if target_os == "windows" else script_name + out_path = dest_dir / "bin" / out_script_name + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_bytes(rewritten) + os.chmod(out_path, os.stat(out_path).st_mode | 0o111) + + +def _finalize_dist_info( + site_packages_dir: Path, + dist_info_dir: str, + *, + data_exclude_rx: list[re.Pattern[str]], + used_data_dir: bool, + expected_data_dir: str, + target_os: str, + rewritten_scripts: set[str], +) -> None: + dist_info_path = site_packages_dir / dist_info_dir + dist_info_path.mkdir(parents=True, exist_ok=True) + if not is_excluded(f"site-packages/{dist_info_dir}/INSTALLER", data_exclude_rx): + with open( + dist_info_path / "INSTALLER", "w", encoding="utf-8", newline="\n" + ) as f: + f.write(INSTALLER_URL) + + record_path = dist_info_path / "RECORD" + if not (used_data_dir and record_path.is_file()): + return + + with open(record_path, encoding="utf-8") as f: + lines = rewrite_record_lines( + f, + target_os, + expected_data_dir, + rewritten_scripts, + ) + with open(record_path, "w", encoding="utf-8", newline="\n") as f: + f.write("".join(lines)) + + +def install_wheel( + wheel_path: Path, + dest_dir: Path, + *, + target_os: str = "unix", + srcs_exclude_globs: list[str] | None = None, + data_exclude_globs: list[str] | None = None, + create_namespace_inits_flag: bool = False, + precompile: bool = False, + pyc_tag: str = "", + precompile_invalidation_mode: str = "checked_hash", + precompile_optimize_level: int = 0, + precompile_source_retention: str = "keep_source", + python_version: str = "", + src_name_prefix: str = "", + precompiler_tool: Path | None = None, +) -> None: + """Extract and install `wheel_path` into `dest_dir`.""" + site_packages_dir = dest_dir / "site-packages" + site_packages_dir.mkdir(parents=True, exist_ok=True) + + srcs_exclude_rx = [glob_to_regex(g) for g in (srcs_exclude_globs or ())] + data_exclude_rx = [glob_to_regex(g) for g in (data_exclude_globs or ())] + + rewritten_scripts: set[str] = set() + used_data_dir = False + + with zipfile.ZipFile(wheel_path) as z: + dist_info_dir, _, entry_points_content = find_wheel_dist_info_and_entry_points( + z + ) + expected_data_dir = expected_data_dir_for_dist_info(dist_info_dir) + data_dir_prefix = f"{expected_data_dir}/" + + for info, dest_or_script, is_shebang in plan_wheel_entries( + z, + dist_info_dir, + entry_points_content, + srcs_exclude_rx, + data_exclude_rx, + ): + if info.filename.startswith(data_dir_prefix): + used_data_dir = True + if is_shebang: + _write_rewritten_script( + dest_dir, dest_or_script, z.read(info), target_os + ) + rewritten_scripts.add(dest_or_script) + continue + + out_path = dest_dir / dest_or_script + out_path.parent.mkdir(parents=True, exist_ok=True) + with z.open(info) as src_f, open(out_path, "wb") as dst_f: + shutil.copyfileobj(src_f, dst_f) + + unix_mode = (info.external_attr >> 16) & 0o777 + if (unix_mode & 0o111) or dest_or_script.startswith("bin/"): + os.chmod(out_path, os.stat(out_path).st_mode | 0o111) + + _finalize_dist_info( + site_packages_dir, + dist_info_dir, + data_exclude_rx=data_exclude_rx, + used_data_dir=used_data_dir, + expected_data_dir=expected_data_dir, + target_os=target_os, + rewritten_scripts=rewritten_scripts, + ) + + if create_namespace_inits_flag: + create_namespace_inits( + site_packages_dir, _NAMESPACE_PKG_TMPL_PATH.read_text(encoding="utf-8") + ) + + if not precompile: + return + + pyc_touched = precompile_site_packages( + dest_dir, + site_packages_dir, + pyc_tag=pyc_tag, + invalidation_mode=precompile_invalidation_mode, + optimize_level=precompile_optimize_level, + source_retention=precompile_source_retention, + python_version=python_version, + src_name_prefix=src_name_prefix, + precompiler_tool=precompiler_tool, + ) + if pyc_touched: + update_record_for_touched_files( + site_packages_dir, + dist_info_dir, + pyc_touched, + ) + + +def main(argv: Sequence[str] | None = None) -> None: + parser = argparse.ArgumentParser( + description="Extract a wheel into a TreeArtifact directory.", + fromfile_prefix_chars="@", + ) + parser.add_argument("--wheel", type=Path, required=True) + parser.add_argument("--directory", type=Path, required=True) + parser.add_argument( + "--target-os", + choices=["unix", "windows"], + default="unix", + ) + parser.add_argument( + "--srcs-exclude-glob", + action="append", + dest="srcs_exclude_globs", + default=[], + ) + parser.add_argument( + "--data-exclude-glob", + action="append", + dest="data_exclude_globs", + default=[], + ) + parser.add_argument( + "--create-namespace-inits", + action="store_true", + default=False, + ) + parser.add_argument( + "--precompile", + action="store_true", + default=False, + ) + parser.add_argument( + "--pyc-tag", + default="", + ) + parser.add_argument( + "--precompile-invalidation-mode", + choices=["checked_hash", "unchecked_hash"], + default="checked_hash", + ) + parser.add_argument( + "--precompile-optimize-level", + type=int, + default=0, + ) + parser.add_argument( + "--precompile-source-retention", + choices=["keep_source", "omit_source"], + default="keep_source", + ) + parser.add_argument( + "--python-version", + default="", + ) + parser.add_argument( + "--src-name-prefix", + default="", + ) + parser.add_argument( + "--precompiler-tool", + type=Path, + default=None, + ) + args = parser.parse_args(argv) + + install_wheel( + args.wheel, + args.directory, + target_os=args.target_os, + srcs_exclude_globs=args.srcs_exclude_globs, + data_exclude_globs=args.data_exclude_globs, + create_namespace_inits_flag=args.create_namespace_inits, + precompile=args.precompile, + pyc_tag=args.pyc_tag, + precompile_invalidation_mode=args.precompile_invalidation_mode, + precompile_optimize_level=args.precompile_optimize_level, + precompile_source_retention=args.precompile_source_retention, + python_version=args.python_version, + src_name_prefix=args.src_name_prefix, + precompiler_tool=args.precompiler_tool, + ) + + +if __name__ == "__main__": + main() diff --git a/python/private/pypi/attrs.bzl b/python/private/pypi/attrs.bzl index 271c17e35c..19c414d7a5 100644 --- a/python/private/pypi/attrs.bzl +++ b/python/private/pypi/attrs.bzl @@ -62,6 +62,47 @@ or `${VARNAME:-default}` (expanding to default if the variable is unset or empty in the environment). Note: On Bazel 6 and Bazel 7.0 changes to the variables named here do not cause packages to be re-fetched. Don't fetch different things based on the value of these variables. +""", + ), + "experimental_action_install": attr.bool( + default = False, + doc = """ +If True, wheel extraction and installation are deferred to a Bazel build action +(`py_wheel_library`) producing a directory artifact (`TreeArtifact`) rather than +extracting wheel contents during the repository phase. Alternatively, the +{envvar}`RULES_PYTHON_EXPERIMENTAL_ACTION_INSTALL` environment variable can be +used to control this flag on `pip.parse` (and WORKSPACE `pip_parse`). + +:::{note} +In this mode: +- Aspects that inspect `PyInfo.direct_original_sources` or `srcs` receive the + installed wheel `TreeArtifact` directory rather than individual `.py` source + files. +- The `:data` and `:extracted_whl_files` targets alias the installed wheel + `TreeArtifact` directory rather than separate `filegroup` subsets, and + `:dist_info` exposes only `entry_points.txt` (when present in the wheel). +- With `--//python/config_settings:venvs_site_packages=yes`, single-file virtual + environment links into wheel `TreeArtifact`s (such as top-level modules, + shared libraries, namespace `__init__.py` files, and merged conflict paths) + create per-binary `UnresolvedSymlink` actions rather than runfiles root + symlinks. +- A registered Python exec-tools toolchain (`//python:exec_tools_toolchain_type`) + is required, and `whl_library` repositories require a fetch-time Python + interpreter (`python_interpreter` or `python_interpreter_target`) to inspect + `.whl` zip archives. +- If a custom `PyExecToolsInfo.precompiler` binary is configured on the + exec-tools toolchain, it runs as a plain subprocess inside the wheel + installation action using its documented CLI (`@params` file); worker settings + (`--//tools/precompiler:execution_requirements` and `testing.ExecutionInfo`) + do not apply. +- In `pip.whl_mods`, `filegroups` is not supported, `copy_files` / + `copy_executables` cannot reference wheel-extracted paths as sources, and + `native.glob()` in `additive_build_content` matches no wheel files (a warning + is emitted). +::: + +:::{versionadded} VERSION_NEXT_FEATURE +::: """, ), "extra_pip_args": attr.string_list( @@ -142,3 +183,26 @@ def use_isolated(ctx, attr): use_isolated = True return use_isolated + +def use_action_install(ctx, attr): + """Determine whether to extract wheels in a build action instead of repository phase. + + Args: + ctx: repository or module context + attr: attributes for the repo rule or tag extension + + Returns: + True if build-action wheel installation should be used + """ + env_val = ctx.getenv("RULES_PYTHON_EXPERIMENTAL_ACTION_INSTALL", None) + if env_val != None: + normalized = env_val.lower() + if normalized in ("1", "true"): + return True + if normalized in ("0", "false", ""): + return False + fail( + "Invalid value for RULES_PYTHON_EXPERIMENTAL_ACTION_INSTALL: '{}'; ".format(env_val) + + "expected one of '1', 'true', '0', 'false', or ''", + ) + return bool(attr.experimental_action_install) diff --git a/python/private/pypi/extension.bzl b/python/private/pypi/extension.bzl index 89485a74f2..fb6cac88e7 100644 --- a/python/private/pypi/extension.bzl +++ b/python/private/pypi/extension.bzl @@ -1232,7 +1232,10 @@ See {ref}`Configuring the Exposed Packages ` for examples. ) pypi = module_extension( - environ = ["RULES_PYTHON_PYPI_HUB_RESERVED"], + environ = [ + "RULES_PYTHON_EXPERIMENTAL_ACTION_INSTALL", + "RULES_PYTHON_PYPI_HUB_RESERVED", + ], doc = """\ This extension is used to make dependencies from pip available. diff --git a/python/private/pypi/generate_whl_library_build_bazel.bzl b/python/private/pypi/generate_whl_library_build_bazel.bzl index c8a46b5f2d..617f4e1639 100644 --- a/python/private/pypi/generate_whl_library_build_bazel.bzl +++ b/python/private/pypi/generate_whl_library_build_bazel.bzl @@ -22,11 +22,13 @@ _RENDER = { "data": render.list, "data_exclude": render.list, "entry_points": render.dict_dict, + "extracted_files": render.list, "extras": render.list, "group_deps": render.list, "include": str, "repo": lambda maybe_label: repr(str(maybe_label)), "requires_dist": render.list, + "shebang_scripts": render.list, "srcs_exclude": render.list, "tags": render.list, } @@ -50,6 +52,14 @@ whl_package_metadata( ) """ +def _check_additive_build_content_for_glob(content): + """Return True if `content` contains a `glob(` call outside comments.""" + for raw_line in content.splitlines(): + line = raw_line.split("#", 1)[0] + if "glob(" in line or "glob (" in line: + return True + return False + def generate_whl_library_build_bazel( *, metadata_version, @@ -57,6 +67,7 @@ def generate_whl_library_build_bazel( config_load, purl = None, requires_dist = [], + logger = None, **kwargs): """Generate a BUILD file for an unzipped Wheel @@ -67,6 +78,7 @@ def generate_whl_library_build_bazel( purl: {type}`dict[str, str] | None` The fields of the PyPI PURL passed to {obj}`whl_package_metadata`. requires_dist: {type}`list[str]` The list of dependencies from the METADATA file. + logger: Optional repository logger used to emit warnings. **kwargs: Extra args serialized to be passed to the {obj}`whl_library_targets`. @@ -111,6 +123,19 @@ def generate_whl_library_build_bazel( kwargs["data_exclude"] = kwargs.get("data_exclude", []) + annotation.data_exclude_glob kwargs["srcs_exclude"] = annotation.srcs_exclude_glob if annotation.additive_build_content: + should_warn_glob = ( + kwargs.get("action_install") and + logger != None and + _check_additive_build_content_for_glob(annotation.additive_build_content) + ) + if should_warn_glob: + logger.warn( + ( + "In '{}', annotation 'additive_build_content' may glob wheel contents; " + + "globs match nothing under experimental_action_install because wheel " + + "contents are extracted into the ':srcs' TreeArtifact during the build phase." + ).format(kwargs.get("name", kwargs.get("metadata_name", ""))), + ) additional_content.append(annotation.additive_build_content) contents = "\n".join( diff --git a/python/private/pypi/hub_builder.bzl b/python/private/pypi/hub_builder.bzl index 6bb94594d7..2ea61e08d5 100644 --- a/python/private/pypi/hub_builder.bzl +++ b/python/private/pypi/hub_builder.bzl @@ -7,7 +7,7 @@ load("//python/private:repo_utils.bzl", "repo_utils") load("//python/private:text_util.bzl", "render") load("//python/private:version.bzl", "version") load("//python/private:version_label.bzl", "version_label") -load(":attrs.bzl", "use_isolated") +load(":attrs.bzl", "use_action_install", "use_isolated") load(":hash.bzl", "hash") load(":parse_requirements.bzl", "parse_requirements") load(":pep508_env.bzl", "env") @@ -643,6 +643,10 @@ def _common_args(self, module_ctx, *, pip_attr): enable_implicit_namespace_pkgs = pip_attr.enable_implicit_namespace_pkgs, environment = pip_attr.environment, envsubst = pip_attr.envsubst, + experimental_action_install = use_action_install( + module_ctx, + pip_attr, + ), pip_data_exclude = pip_attr.pip_data_exclude, ) @@ -707,7 +711,11 @@ def _whl_repo( # need to pass the extra args there, so only pop this for whls args["extra_pip_args"] = src.extra_pip_args - if not (enable_pipstar_extract and is_whl): + needs_interpreter = ( + args.get("experimental_action_install") or + not (enable_pipstar_extract and is_whl) + ) + if needs_interpreter: if interpreter.path: args["python_interpreter"] = interpreter.path if interpreter.target: diff --git a/python/private/pypi/inspect_whl.py b/python/private/pypi/inspect_whl.py new file mode 100644 index 0000000000..1fb44b750d --- /dev/null +++ b/python/private/pypi/inspect_whl.py @@ -0,0 +1,136 @@ +"""Inspect a wheel archive without extracting it to disk. + +Writes a JSON object to stdout containing `entry_points_content`, +`extracted_files`, `has_entry_points_txt`, `metadata_content`, +`namespace_package_files`, and `shebang_scripts` for BUILD generation. + +Usage: + python3 -I -B inspect_whl.py --wheel path/to/pkg-1.0-py3-none-any.whl \\ + [--srcs-exclude-glob PATTERN ...] [--data-exclude-glob PATTERN ...] +""" + +from __future__ import annotations + +import argparse +import json +import sys +import zipfile +from collections.abc import Sequence +from pathlib import Path +from typing import TypedDict + +# Invoked directly via `rctx.execute([python_interpreter, ...])` during +# repository fetch before any `py_binary` target can be built, so Bazel's +# `py_binary` import path setup is unavailable. +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from wheel_layout import ( # noqa: E402 + find_wheel_dist_info_and_entry_points, + glob_to_regex, + is_excluded, + is_pkgutil_namespace_init, + plan_wheel_entries, +) + + +def _is_top_level_pkg_init(dest_rel: str) -> bool: + parts = dest_rel.split("/") + return ( + len(parts) == 3 + and parts[0] == "site-packages" + and parts[2] == "__init__.py" + and parts[1].isidentifier() + ) + + +class WheelInspection(TypedDict): + entry_points_content: str + extracted_files: list[str] + has_entry_points_txt: bool + metadata_content: str + namespace_package_files: list[str] + shebang_scripts: list[str] + + +def inspect_wheel( + wheel_path: Path, + srcs_exclude_globs: list[str] | None = None, + data_exclude_globs: list[str] | None = None, +) -> WheelInspection: + """Inspect a .whl zip file and return metadata and extracted file paths.""" + srcs_exclude_rx = [glob_to_regex(p) for p in (srcs_exclude_globs or ())] + data_exclude_rx = [glob_to_regex(p) for p in (data_exclude_globs or ())] + + extracted_files: set[str] = set() + namespace_package_files: set[str] = set() + shebang_scripts: set[str] = set() + + with zipfile.ZipFile(wheel_path) as z: + dist_info_dir, metadata_content, entry_points_content = ( + find_wheel_dist_info_and_entry_points(z) + ) + for info, dest_or_script, is_shebang in plan_wheel_entries( + z, + dist_info_dir, + entry_points_content, + srcs_exclude_rx, + data_exclude_rx, + ): + if is_shebang: + shebang_scripts.add(dest_or_script) + continue + extracted_files.add(dest_or_script) + if not _is_top_level_pkg_init(dest_or_script): + continue + content = z.read(info).decode("utf-8", "replace") + if is_pkgutil_namespace_init(content): + namespace_package_files.add(dest_or_script) + + installer_rel = f"site-packages/{dist_info_dir}/INSTALLER" + if not is_excluded(installer_rel, data_exclude_rx): + extracted_files.add(installer_rel) + + return { + "entry_points_content": entry_points_content or "", + "extracted_files": sorted(extracted_files), + "has_entry_points_txt": entry_points_content is not None, + "metadata_content": metadata_content, + "namespace_package_files": sorted(namespace_package_files), + "shebang_scripts": sorted(shebang_scripts), + } + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Inspect a wheel file.") + parser.add_argument("--wheel", type=Path, required=True) + parser.add_argument( + "--srcs-exclude-glob", + action="append", + dest="srcs_exclude_globs", + default=[], + ) + parser.add_argument( + "--data-exclude-glob", + action="append", + dest="data_exclude_globs", + default=[], + ) + args = parser.parse_args(argv) + + try: + result = inspect_wheel( + args.wheel, args.srcs_exclude_globs, args.data_exclude_globs + ) + except (zipfile.BadZipFile, ValueError, OSError) as exc: + print( + f"inspect_whl: failed to inspect '{args.wheel}': {exc}", + file=sys.stderr, + ) + return 1 + + json.dump(result, sys.stdout, sort_keys=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/python/private/pypi/labels.bzl b/python/private/pypi/labels.bzl index c77167b593..7881b422d0 100644 --- a/python/private/pypi/labels.bzl +++ b/python/private/pypi/labels.bzl @@ -24,3 +24,8 @@ PY_SRCS_LABEL = "srcs" DATA_LABEL = "data" DIST_INFO_LABEL = "dist_info" NODEPS_LABEL = "no_deps" + +DEFAULT_DATA_EXCLUDE = [ + "**/*.pyc", + "**/*.pyc.*", # During pyc creation, temp files named *.pyc.NNNN are created +] diff --git a/python/private/pypi/patch_and_extract_whl.bzl b/python/private/pypi/patch_and_extract_whl.bzl index 0c73568806..d047d85c51 100644 --- a/python/private/pypi/patch_and_extract_whl.bzl +++ b/python/private/pypi/patch_and_extract_whl.bzl @@ -3,11 +3,12 @@ load("//python/private:normalize_name.bzl", "normalize_name") load("//python/private:repo_utils.bzl", "repo_utils") load(":generate_whl_library_build_bazel.bzl", "generate_whl_library_build_bazel") +load(":labels.bzl", "DEFAULT_DATA_EXCLUDE") load(":patch_whl.bzl", "get_whl_patches", "patch_whl") load(":pep508_requirement.bzl", "requirement") load(":pypi_repo_utils.bzl", "pypi_repo_utils") load(":whl_extract.bzl", "whl_extract") -load(":whl_metadata.bzl", "parse_entry_points", "whl_metadata") +load(":whl_metadata.bzl", "parse_entry_points", "parse_whl_metadata", "whl_metadata") def _get_entry_points(rctx, install_dir_path, metadata): dist_info_dir = "{}-{}.dist-info".format( @@ -73,6 +74,107 @@ def _remove_files(rctx, *basenames): elif path.is_dir: paths.extend(path.readdir()) +def _resolve_inspect_python(rctx, logger): + if not (rctx.attr.python_interpreter or rctx.attr.python_interpreter_target): + logger.fail( + "experimental_action_install requires 'python_interpreter' or " + + "'python_interpreter_target' to be set on '{}'".format(rctx.attr.name), + ) + return None + return pypi_repo_utils.resolve_python_interpreter( + rctx, + python_interpreter = rctx.attr.python_interpreter, + python_interpreter_target = rctx.attr.python_interpreter_target, + ) + +def _maybe_patch_whl(rctx, whl_path, whl_file): + if not rctx.attr.whl_patches: + return whl_path, whl_file, False + patches = get_whl_patches(rctx.attr.whl_patches, whl_path.basename) + if not patches: + return whl_path, whl_file, False + + # patch_whl deletes its input before repacking. Never delete an + # archive owned by another repository. + if whl_path.dirname != rctx.path("."): + rctx.symlink(whl_path, whl_path.basename) + whl_path = rctx.path(whl_path.basename) + whl_path = patch_whl( + rctx, + whl_path = whl_path, + patches = patches, + ) + return whl_path, None, True + +def _inspect_whl_for_action_install( + rctx, + *, + whl_path, + patched, + sdist_filename, + annotation, + logger): + if patched: + for entry in rctx.path(".").readdir(): + if entry.basename != whl_path.basename: + rctx.delete(entry) + + data_exclude = ( + DEFAULT_DATA_EXCLUDE + + (["**/*.dist-info/RECORD"] if sdist_filename else []) + + rctx.attr.pip_data_exclude + ) + inspect_args = [ + "-I", + "-B", + str(rctx.path(rctx.attr._inspect_whl)), + "--wheel", + str(whl_path), + ] + if annotation: + for pattern in annotation.srcs_exclude_glob: + inspect_args.extend(["--srcs-exclude-glob", pattern]) + for pattern in data_exclude + (annotation.data_exclude_glob if annotation else []): + inspect_args.extend(["--data-exclude-glob", pattern]) + + inspect_python = _resolve_inspect_python(rctx, logger) + if not inspect_python: + return None + + inspection = json.decode(pypi_repo_utils.execute_checked_stdout( + rctx, + python = inspect_python, + srcs = [ + rctx.attr._inspect_whl, + rctx.attr._wheel_layout, + ], + op = "InspectWhl({})".format(whl_path.basename), + arguments = inspect_args, + logger = logger, + )) + + metadata = parse_whl_metadata(inspection["metadata_content"]) + if not (metadata.name and metadata.version): + logger.fail("Failed to parse the wheel METADATA file in '{}'".format(whl_path.basename)) + return None + + extra_kwargs = { + "action_install": True, + "extracted_files": inspection["extracted_files"], + "shebang_scripts": inspection["shebang_scripts"], + } + if inspection["has_entry_points_txt"]: + rctx.file("entry_points.txt", inspection["entry_points_content"]) + extra_kwargs["has_entry_points_txt"] = True + + return struct( + metadata = metadata, + entry_points = parse_entry_points(inspection["entry_points_content"]), + namespace_package_files = inspection["namespace_package_files"], + data_exclude = data_exclude, + extra_kwargs = extra_kwargs, + ) + def patch_and_extract_whl(rctx, *, whl_path, logger, sdist_filename = None, whl_file = None): """Extract the wheel, apply patches and generate BUILD.bazel files. @@ -88,40 +190,48 @@ def patch_and_extract_whl(rctx, *, whl_path, logger, sdist_filename = None, whl_ Returns: The repository metadata if the extraction is reproducible """ - if rctx.attr.whl_patches: - patches = get_whl_patches(rctx.attr.whl_patches, whl_path.basename) - - if patches: - # patch_whl deletes its input before repacking. Never delete an - # archive owned by another repository. - if whl_path.dirname != rctx.path("."): - rctx.symlink(whl_path, whl_path.basename) - whl_path = rctx.path(whl_path.basename) - whl_path = patch_whl( - rctx, - whl_path = whl_path, - patches = patches, - ) - whl_file = None - - whl_extract(rctx, whl_path = whl_path, logger = logger) - - install_dir_path = rctx.path("site-packages") - metadata = whl_metadata( - install_dir = install_dir_path, - read_fn = rctx.read, - logger = logger, - ) + whl_path, whl_file, patched = _maybe_patch_whl(rctx, whl_path, whl_file) + annotation = None if not rctx.attr.annotation else struct(**json.decode(rctx.read(rctx.attr.annotation))) + + if rctx.attr.experimental_action_install: + inspected = _inspect_whl_for_action_install( + rctx, + whl_path = whl_path, + patched = patched, + sdist_filename = sdist_filename, + annotation = annotation, + logger = logger, + ) + if inspected == None: + return None + metadata = inspected.metadata + entry_points = inspected.entry_points + namespace_package_files = inspected.namespace_package_files + data_exclude = inspected.data_exclude + extra_kwargs = inspected.extra_kwargs + else: + whl_extract(rctx, whl_path = whl_path, logger = logger) + install_dir_path = rctx.path("site-packages") + metadata = whl_metadata( + install_dir = install_dir_path, + read_fn = rctx.read, + logger = logger, + ) + namespace_package_files = pypi_repo_utils.find_namespace_package_files(rctx, install_dir_path) + entry_points = _get_entry_points(rctx, install_dir_path, metadata) + _move_scripts_needing_shebang_rewrite(rctx, entry_points) + data_exclude = rctx.attr.pip_data_exclude + extra_kwargs = {} + + if whl_file: + extra_kwargs["whl_file"] = str(whl_file) + rctx.file("metadata.json", json.encode_indent({ "name": metadata.name, "provides_extra": metadata.provides_extra, "requires_dist": metadata.requires_dist, "version": metadata.version, })) - namespace_package_files = pypi_repo_utils.find_namespace_package_files(rctx, install_dir_path) - - entry_points = _get_entry_points(rctx, install_dir_path, metadata) - _move_scripts_needing_shebang_rewrite(rctx, entry_points) build_file_contents = generate_whl_library_build_bazel( name = whl_path.basename, @@ -134,8 +244,8 @@ def patch_and_extract_whl(rctx, *, whl_path, logger, sdist_filename = None, whl_ # TODO @aignas 2025-05-17: maybe have a build flag for this instead enable_implicit_namespace_pkgs = rctx.attr.enable_implicit_namespace_pkgs, # TODO @aignas 2025-04-14: load through the hub: - annotation = None if not rctx.attr.annotation else struct(**json.decode(rctx.read(rctx.attr.annotation))), - data_exclude = rctx.attr.pip_data_exclude, + annotation = annotation, + data_exclude = data_exclude, group_deps = rctx.attr.group_deps, group_name = rctx.attr.group_name, namespace_package_files = namespace_package_files, @@ -146,7 +256,8 @@ def patch_and_extract_whl(rctx, *, whl_path, logger, sdist_filename = None, whl_ metadata = metadata, filename = sdist_filename or whl_path.basename, ), - **({"whl_file": str(whl_file)} if whl_file else {}) + logger = logger, + **extra_kwargs ) # The generated wheel target can obtain the original archive independently. diff --git a/python/private/pypi/pip_archive.bzl b/python/private/pypi/pip_archive.bzl index 1764abe70d..79a805b32c 100644 --- a/python/private/pypi/pip_archive.bzl +++ b/python/private/pypi/pip_archive.bzl @@ -353,8 +353,6 @@ pip_archive_attrs = { "environment", "extra_pip_args", "isolated", - "python_interpreter", - "python_interpreter_target", "quiet", "timeout", ] diff --git a/python/private/pypi/pip_repository.bzl b/python/private/pypi/pip_repository.bzl index d02c62eae1..5bcdd8b939 100644 --- a/python/private/pypi/pip_repository.bzl +++ b/python/private/pypi/pip_repository.bzl @@ -20,6 +20,7 @@ load("//python/private:normalize_name.bzl", "normalize_name") load("//python/private:repo_utils.bzl", "REPO_DEBUG_ENV_VAR", "repo_utils") load("//python/private:text_util.bzl", "render") load("//python/private:version.bzl", "version") +load(":attrs.bzl", "use_action_install") load(":default_platforms.bzl", "default_platforms") load(":hash.bzl", "hash") load(":parse_requirements.bzl", "host_platform", "parse_requirements", "select_requirement") @@ -253,6 +254,9 @@ def _pip_repository_impl(rctx): if rctx.attr.python_interpreter_target: config["python_interpreter_target"] = str(rctx.attr.python_interpreter_target) + if use_action_install(rctx, rctx.attr): + config["experimental_action_install"] = True + macro_tmpl = "@%s//{}:{}" % rctx.attr.name aliases = render_pkg_aliases( @@ -375,7 +379,8 @@ You can then reference installed dependencies from a `BUILD` file with the alias - `@pypi//pyyaml` and `@pypi//pyyaml:pkg` both point to the `py_library` created after extracting the `PyYAML` package. - `@pypi//pyyaml:data` points to the extra data included in the package. -- `@pypi//pyyaml:dist_info` points to the `dist-info` files in the package. +- `@pypi//pyyaml:dist_info` points to the `dist-info` files in the package (or + only `entry_points.txt` when `experimental_action_install` is enabled). - `@pypi//pyyaml:whl` points to the wheel file that was extracted. ```starlark @@ -433,6 +438,7 @@ See the example in rules_python/examples/pip_parse_vendored. """, implementation = _pip_repository_impl, environ = [ + "RULES_PYTHON_EXPERIMENTAL_ACTION_INSTALL", "RULES_PYTHON_PIP_ISOLATED", REPO_DEBUG_ENV_VAR, ], diff --git a/python/private/pypi/py_wheel_library.bzl b/python/private/pypi/py_wheel_library.bzl new file mode 100644 index 0000000000..425aad745d --- /dev/null +++ b/python/private/pypi/py_wheel_library.bzl @@ -0,0 +1,410 @@ +"""Rule for extracting and installing a Python wheel in a Bazel build action.""" + +load("@bazel_skylib//lib:paths.bzl", "paths") +load("//python/private:attr_builders.bzl", "attrb") +load( + "//python/private:attributes.bzl", + "COMMON_ATTRS", + "PY_SRCS_ATTRS", + "PrecompileAttr", + "PrecompileInvalidationModeAttr", + "PrecompileSourceRetentionAttr", + "WINDOWS_CONSTRAINTS_ATTRS", +) +load("//python/private:builders.bzl", "builders") +load( + "//python/private:common.bzl", + "actions_run", + "collect_cc_info", + "collect_runfiles", + "create_instrumented_files_info", + "create_output_group_info", + "create_py_info", + "is_windows_platform", + "runfiles_root_path", +) +load( + "//python/private:flags.bzl", + "CompilationMode", + "VenvsSitePackages", +) +load("//python/private:normalize_name.bzl", "normalize_name") +load("//python/private:py_cc_link_params_info.bzl", "PyCcLinkParamsInfo") +load("//python/private:py_info.bzl", "PyInfo") +load("//python/private:py_interpreter_program.bzl", "PyInterpreterProgramInfo") +load("//python/private:py_library.bzl", "LIBRARY_ATTRS") +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:venv_runfiles.bzl", "get_venv_symlinks") +load("//python/private:version.bzl", "version") + +PY_WHEEL_LIBRARY_ATTRS = COMMON_ATTRS | WINDOWS_CONSTRAINTS_ATTRS | { + "data_exclude": lambda: attrb.StringList( + default = [], + doc = """ +Glob patterns to exclude from non-.py files when extracting the wheel. +""", + ), + "deps": PY_SRCS_ATTRS["deps"], + "enable_implicit_namespace_pkgs": lambda: attrb.Bool( + default = False, + doc = """ +If True, disables generating pkgutil-style __init__.py files for implicit +namespace packages. +""", + ), + "experimental_venvs_site_packages": LIBRARY_ATTRS["experimental_venvs_site_packages"], + "extracted_files": lambda: attrb.StringList( + default = [], + doc = "Relative paths under the installed wheel directory.", + ), + "namespace_package_files": lambda: attrb.StringList( + default = [], + doc = """ +Relative paths to pkgutil-style namespace package __init__.py files. +""", + ), + "precompile": PY_SRCS_ATTRS["precompile"], + "precompile_invalidation_mode": PY_SRCS_ATTRS["precompile_invalidation_mode"], + "precompile_optimize_level": PY_SRCS_ATTRS["precompile_optimize_level"], + "precompile_source_retention": PY_SRCS_ATTRS["precompile_source_retention"], + "shebang_scripts": lambda: attrb.StringList( + default = [], + doc = """ +Top-level script names in .data/scripts/ whose #!python shebang is rewritten. +""", + ), + "srcs_exclude": lambda: attrb.StringList( + default = [], + doc = "Glob patterns to exclude from .py files when extracting the wheel.", + ), + "wheel": lambda: attrb.Label( + allow_single_file = True, + mandatory = True, + doc = "The .whl file to extract and install.", + ), + "_action_whl_installer": lambda: attrb.Label( + cfg = "exec", + default = Label("//python/private/pypi:action_whl_installer"), + ), + "_action_whl_installer_helpers": lambda: attrb.Label( + allow_files = True, + default = Label("//python/private/pypi:action_whl_installer_helpers"), + ), + "_precompile_flag": PY_SRCS_ATTRS["_precompile_flag"], + "_precompile_source_retention_flag": PY_SRCS_ATTRS["_precompile_source_retention_flag"], +} + +def _has_pyi_files(extracted_files, keep_source = True): + for f in extracted_files: + if not f.startswith("site-packages/"): + continue + if f.endswith(".pyi"): + return True + if keep_source and (f == "site-packages/py.typed" or f.endswith("/py.typed")): + return True + return False + +def _should_precompile(ctx, exec_tools_toolchain): + if exec_tools_toolchain.exec_tools.precompiler == None: + return False + target_toolchain = ctx.toolchains[TARGET_TOOLCHAIN_TYPE] + + # Builtin / custom toolchains may omit py3_runtime, pyc_tag, or + # interpreter_version_info (e.g. BuiltinPyRuntimeInfo). + if target_toolchain == None: + return False + if not hasattr(target_toolchain, "py3_runtime") or not target_toolchain.py3_runtime: + return False + target_runtime = target_toolchain.py3_runtime + if not hasattr(target_runtime, "pyc_tag") or not target_runtime.pyc_tag: + return False + if ( + not hasattr(target_runtime, "interpreter_version_info") or + not target_runtime.interpreter_version_info + ): + return False + return PrecompileAttr.get_effective_value(ctx) == PrecompileAttr.ENABLED + +def _get_package_and_version(extracted_files, tags): + dist_info_dir = None + for f in extracted_files: + parts = f.split("/") + if ( + len(parts) == 3 and + parts[0] == "site-packages" and + parts[1].endswith(".dist-info") and + parts[2].lower() == "metadata" + ): + dist_info_dir = parts[1] + break + + if dist_info_dir: + stem = dist_info_dir.removesuffix(".dist-info") + package, _, version_str = stem.rpartition("-") + if package and version_str: + return normalize_name(package), version.normalize(version_str) + + package = None + version_str = None + for tag in tags: + if tag.startswith("pypi_name="): + package = normalize_name(tag[len("pypi_name="):]) + elif tag.startswith("pypi_version="): + version_str = version.normalize(tag[len("pypi_version="):]) + return package, version_str + +def _resolve_invalidation_mode(ctx): + mode = ctx.attr.precompile_invalidation_mode + if mode != PrecompileInvalidationModeAttr.AUTO: + return mode + if ctx.var.get("COMPILATION_MODE") == CompilationMode.OPT: + return PrecompileInvalidationModeAttr.UNCHECKED_HASH + return PrecompileInvalidationModeAttr.CHECKED_HASH + +def _add_precompile_args(ctx, args, out_short_path, exec_tools_toolchain, source_retention): + target_runtime = ctx.toolchains[TARGET_TOOLCHAIN_TYPE].py3_runtime + version_info = target_runtime.interpreter_version_info + python_version = "{}.{}".format(version_info.major, version_info.minor) + args.add("--precompile") + args.add("--pyc-tag", target_runtime.pyc_tag) + args.add("--precompile-invalidation-mode", _resolve_invalidation_mode(ctx)) + args.add("--precompile-optimize-level", str(ctx.attr.precompile_optimize_level)) + args.add("--precompile-source-retention", source_retention) + args.add("--python-version", python_version) + args.add("--src-name-prefix", out_short_path) + + precompiler = exec_tools_toolchain.exec_tools.precompiler + + # When the precompiler provides PyInterpreterProgramInfo (the default stock + # precompiler), action_whl_installer compiles in-process using the exec_tools + # interpreter directly. + if PyInterpreterProgramInfo in precompiler: + return [] + + files_to_run = precompiler[DefaultInfo].files_to_run + if not files_to_run or not files_to_run.executable: + fail(("Unrecognized precompiler: target '{}' does not provide " + + "PyInterpreterProgramInfo nor appears to be executable").format( + precompiler, + )) + args.add("--precompiler-tool", files_to_run.executable) + return [files_to_run] + +def _collect_installed_tree_files( + extracted_files, + shebang_scripts, + *, + is_windows, + keep_source, + pyc_tag): + tree_files = [] + for f in extracted_files: + is_site_py = f.startswith("site-packages/") and f.endswith(".py") + if not is_site_py: + tree_files.append(f) + continue + if not keep_source: + tree_files.append(f[:-len(".py")] + ".pyc") + continue + tree_files.append(f) + if pyc_tag: + stem = paths.basename(f)[:-len(".py")] + tree_files.append( + "{}/__pycache__/{}.{}.pyc".format(paths.dirname(f), stem, pyc_tag), + ) + for s in shebang_scripts: + tree_files.append("bin/" + ((s + ".bat") if is_windows else s)) + return tree_files + +def _compute_wheel_venv_symlinks( + ctx, + out, + *, + is_windows, + should_precompile, + keep_source): + package, version_str = _get_package_and_version( + ctx.attr.extracted_files, + ctx.attr.tags, + ) + pyc_tag = ( + ctx.toolchains[TARGET_TOOLCHAIN_TYPE].py3_runtime.pyc_tag if should_precompile else "" + ) + tree_files = _collect_installed_tree_files( + ctx.attr.extracted_files, + ctx.attr.shebang_scripts, + is_windows = is_windows, + keep_source = keep_source, + pyc_tag = pyc_tag, + ) + venv_symlinks = list(get_venv_symlinks( + ctx, + tree_files, + package, + version_str, + site_packages_root = "site-packages", + namespace_package_files = ctx.attr.namespace_package_files, + tree_artifact = out, + )) + extra_data_files = [f for f in ctx.files.data if not f.is_directory] + if extra_data_files: + site_packages_root = paths.normalize(paths.join( + ctx.label.package, + "site-packages", + )) + venv_symlinks.extend(get_venv_symlinks( + ctx, + extra_data_files, + package, + version_str, + site_packages_root = site_packages_root, + )) + return venv_symlinks + +def _py_wheel_library_impl(ctx): + exec_tools_toolchain = ctx.toolchains[EXEC_TOOLS_TOOLCHAIN_TYPE] + if exec_tools_toolchain == None: + fail( + "experimental_action_install requires the exec_tools toolchain " + + "(set //python/config_settings:exec_tools_toolchain=enabled)", + ) + + out = ctx.actions.declare_directory(ctx.attr.name) + is_windows = is_windows_platform(ctx) + venvs_site_packages_enabled = VenvsSitePackages.is_enabled(ctx) + create_namespace_inits = ( + not ctx.attr.enable_implicit_namespace_pkgs and + not venvs_site_packages_enabled + ) + should_precompile = _should_precompile(ctx, exec_tools_toolchain) + source_retention = PrecompileSourceRetentionAttr.get_effective_value(ctx) + keep_source = ( + not should_precompile or + source_retention == PrecompileSourceRetentionAttr.KEEP_SOURCE + ) + + args = ctx.actions.args() + args.add("--wheel", ctx.file.wheel) + args.add_all("--directory", [out], expand_directories = False) + args.add("--target-os", "windows" if is_windows else "unix") + for pattern in ctx.attr.srcs_exclude: + args.add("--srcs-exclude-glob", pattern) + for pattern in ctx.attr.data_exclude: + args.add("--data-exclude-glob", pattern) + if create_namespace_inits: + args.add("--create-namespace-inits") + + extra_tools = [] + if should_precompile: + extra_tools = _add_precompile_args( + ctx, + args, + out.short_path, + exec_tools_toolchain, + source_retention, + ) + + helper_files = ctx.files._action_whl_installer_helpers + actions_run( + ctx, + executable = ctx.attr._action_whl_installer, + arguments = [args], + env = { + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONPATH": helper_files[0].dirname, + }, + inputs = [ctx.file.wheel] + helper_files, + outputs = [out], + tools = extra_tools, + mnemonic = "PyWheelInstall", + progress_message = "Installing wheel {} into %{{output}}".format(ctx.file.wheel.basename), + ) + + out_rf_path = runfiles_root_path(ctx, out.short_path) + site_packages_rf_path = paths.join(out_rf_path, "site-packages") + + if venvs_site_packages_enabled: + imports = depset() + venv_symlinks = _compute_wheel_venv_symlinks( + ctx, + out, + is_windows = is_windows, + should_precompile = should_precompile, + keep_source = keep_source, + ) + else: + imports = depset([site_packages_rf_path]) + venv_symlinks = [] + + runfiles = builders.RunfilesBuilder() + runfiles.add([out]) + runfiles.add(collect_runfiles(ctx)) + runfiles = runfiles.build(ctx) + + cc_info = collect_cc_info(ctx) + py_info, builtins_py_info = create_py_info( + ctx, + original_sources = [out], + required_py_files = [out] if keep_source else [], + required_pyc_files = [out] if should_precompile else [], + implicit_pyc_files = [], + implicit_pyc_source_files = [], + imports = imports, + venv_symlinks = venv_symlinks, + pyi_files = [out] if _has_pyi_files(ctx.attr.extracted_files, keep_source = keep_source) else [], + srcs_version = "ALL", + pyi_deps = [], + ) + + providers = [ + DefaultInfo(files = depset([out]), runfiles = runfiles), + py_info, + create_instrumented_files_info(ctx, source_attributes = []), + PyCcLinkParamsInfo(cc_info = cc_info), + create_output_group_info(py_info.transitive_sources, extra_groups = {}), + ] + if builtins_py_info: + providers.append(builtins_py_info) + return providers + +_MaybeBuiltinPyInfo = [BuiltinPyInfo] if BuiltinPyInfo != None else [] + +py_wheel_library = ruleb.Rule( + implementation = _py_wheel_library_impl, + doc = """ +Extracts and installs a Python wheel into a directory artifact during the build +phase. + +:::{note} +Precompilation is performed inside the wheel installation action based on the +effective `precompile` setting (`--precompile` and `precompile`). A downstream +binary that explicitly overrides `pyc_collection` (rather than inheriting from +`--precompile`) does not change whether `.pyc` files are included in the +installed wheel directory. When a custom `PyExecToolsInfo.precompiler` binary is +configured on the exec-tools toolchain, it runs as a plain subprocess inside the +wheel installation action using its documented CLI (`@params` file); worker +settings (`--//tools/precompiler:execution_requirements` and +`testing.ExecutionInfo`) do not apply. When `precompile_source_retention` is +`omit_source`, `.py` source files are removed from the installed wheel +`TreeArtifact` (and `PyInfo.direct_original_sources` / +`transitive_original_sources` reference that sourceless directory, so static +analysis and coverage tools will not see `.py` sources for the wheel). When +`.pyi` stubs or `py.typed` markers are present (`py.typed` without `.pyi` files +is ignored when sources are omitted), `PyInfo.direct_pyi_files` / +`transitive_pyi_files` contains the installed wheel `TreeArtifact` directory; +consumers must handle directory `File`s. +::: +""", + attrs = PY_WHEEL_LIBRARY_ATTRS, + provides = [PyCcLinkParamsInfo, PyInfo] + _MaybeBuiltinPyInfo, + toolchains = [ + ruleb.ToolchainType(TARGET_TOOLCHAIN_TYPE, mandatory = False), + ruleb.ToolchainType(EXEC_TOOLS_TOOLCHAIN_TYPE, mandatory = False), + ], +).build() diff --git a/python/private/pypi/wheel_layout.py b/python/private/pypi/wheel_layout.py new file mode 100644 index 0000000000..55d76507c0 --- /dev/null +++ b/python/private/pypi/wheel_layout.py @@ -0,0 +1,344 @@ +"""Shared wheel layout mapping and path sanitization for inspect_whl and action_whl_installer.""" + +from __future__ import annotations + +import base64 +import csv +import hashlib +import io +import re +import zipfile +from collections.abc import Iterator +from pathlib import Path + +_BAZEL_REPO_FILES = frozenset( + { + "BUILD", + "BUILD.bazel", + "REPO.bazel", + "WORKSPACE", + "WORKSPACE.bazel", + "WORKSPACE.bzlmod", + } +) + +_DATA_CATEGORIES = { + "data": "data", + "headers": "include", + "platlib": "site-packages", + "purelib": "site-packages", + "scripts": "bin", +} + +INSTALLER_URL = "https://github.com/bazel-contrib/rules_python#pipstar" + + +def glob_to_regex(pattern: str) -> re.Pattern[str]: + """Convert a Bazel-style glob pattern (supporting `**`) into a compiled regex.""" + i = 0 + n = len(pattern) + parts = ["^"] + while i < n: + if pattern[i : i + 3] == "**/": + parts.append("(?:.+/)?") + i += 3 + elif pattern[i : i + 3] == "/**": + parts.append("(?:/.*)?") + i += 3 + elif pattern[i : i + 2] == "**": + parts.append(".*") + i += 2 + elif pattern[i] == "*": + parts.append("[^/]*") + i += 1 + elif pattern[i] == "?": + parts.append("[^/]") + i += 1 + else: + parts.append(re.escape(pattern[i])) + i += 1 + parts.append("$") + return re.compile("".join(parts)) + + +def is_excluded(path: str, compiled_globs: list[re.Pattern[str]]) -> bool: + """Return whether `path` matches any compiled exclusion glob.""" + return any(rx.match(path) for rx in compiled_globs) + + +def is_pkgutil_namespace_init(content: str) -> bool: + """Whether an `__init__.py` declares a pkgutil namespace package.""" + return ( + "__path__ =" in content and "pkgutil" in content and "extend_path(" in content + ) + + +def _parse_entry_point_names_lower(contents: str) -> set[str]: + """Parse lowercase console_scripts and gui_scripts names from entry_points.txt.""" + names: set[str] = set() + current_group_lower = None + for line in contents.splitlines(): + line = line.strip() + if not line or line.startswith("#"): + continue + if line.startswith("[") and line.endswith("]"): + current_group_lower = line[1:-1].strip().lower() + continue + if current_group_lower not in ("console_scripts", "gui_scripts"): + continue + name, _, _ = line.partition("=") + name = name.strip() + if name: + names.add(name.lower()) + return names + + +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 find_wheel_dist_info_and_entry_points( + zf: zipfile.ZipFile, +) -> tuple[str, str, str | None]: + """Return `(dist_info_dir, metadata_content, entry_points_content)` for `zf`. + + `entry_points_content` is `None` when the `.dist-info` directory contains no + `entry_points.txt` file. Raises `ValueError` if zero or multiple top-level + `.dist-info/METADATA` files exist in the archive. + """ + metadata_infos: dict[str, zipfile.ZipInfo] = {} + entry_points_infos: dict[str, zipfile.ZipInfo] = {} + + for info in zf.infolist(): + parts = sanitize_wheel_entry_path(info.filename) + if parts is None or len(parts) != 2 or not parts[0].endswith(".dist-info"): + continue + if parts[1] == "METADATA": + metadata_infos.setdefault(parts[0], info) + elif parts[1] == "entry_points.txt": + entry_points_infos.setdefault(parts[0], info) + + if not metadata_infos: + raise ValueError("Wheel archive contains no '*.dist-info/METADATA' file") + if len(metadata_infos) > 1: + dirs = ", ".join(sorted(metadata_infos)) + raise ValueError( + f"Wheel archive contains multiple .dist-info directories: {dirs}" + ) + + dist_info_dir, metadata_info = next(iter(metadata_infos.items())) + metadata_content = zf.read(metadata_info).decode("utf-8", "replace") + ep_info = entry_points_infos.get(dist_info_dir) + entry_points_content = ( + zf.read(ep_info).decode("utf-8", "replace") if ep_info is not None else None + ) + return dist_info_dir, metadata_content, entry_points_content + + +def expected_data_dir_for_dist_info(dist_info_dir: str) -> str: + """Derive the PEP 427 `.data` directory name from the `.dist-info` directory name.""" + return dist_info_dir[: -len(".dist-info")] + ".data" + + +def _resolve_wheel_entry_dest( + name: str, + parts: list[str], + expected_data_dir: str, +) -> str | None: + if parts[-1] in _BAZEL_REPO_FILES: + return None + if parts[0] != expected_data_dir: + return f"site-packages/{name}" + if len(parts) <= 2: + return None + dest_prefix = _DATA_CATEGORIES.get(parts[1]) + if not dest_prefix: + raise ValueError(f"Unknown .data category {parts[1]!r} in wheel entry {name!r}") + rel_path = "/".join(parts[2:]) + return f"{dest_prefix}/{rel_path}" if rel_path else None + + +def _map_wheel_entry_destination( + name: str, + parts: list[str], + expected_data_dir: str, + seen_destinations: dict[str, str], +) -> str | None: + """Map a wheel archive entry to its installed relative path under the TreeArtifact root. + + Raises ValueError if an unknown `.data` category is encountered or if two + distinct wheel entries map to the same destination path (checked + case-insensitively across platforms). + """ + dest_rel = _resolve_wheel_entry_dest(name, parts, expected_data_dir) + if dest_rel is None: + return None + + dest_key = dest_rel.casefold() + prev = seen_destinations.get(dest_key) + if prev is not None and prev != name: + raise ValueError( + f"Detected collision at '{dest_rel}' between wheel entries '{prev}' and '{name}'" + ) + seen_destinations[dest_key] = name + return dest_rel + + +def _has_python_shebang(zf: zipfile.ZipFile, info: zipfile.ZipInfo) -> bool: + with zf.open(info) as f: + return f.read(10).startswith(b"#!python") + + +def plan_wheel_entries( + zf: zipfile.ZipFile, + dist_info_dir: str, + entry_points_content: str | None, + srcs_exclude_rx: list[re.Pattern[str]], + data_exclude_rx: list[re.Pattern[str]], +) -> Iterator[tuple[zipfile.ZipInfo, str, bool]]: + """Yield `(info, dest_rel_or_script_name, is_shebang_script)` for wheel entries.""" + expected_data_dir = expected_data_dir_for_dist_info(dist_info_dir) + ep_names_lower = _parse_entry_point_names_lower(entry_points_content or "") + seen_destinations: dict[str, str] = {} + + for info in zf.infolist(): + name = info.filename + parts = sanitize_wheel_entry_path(name) + if parts is None: + continue + + dest_rel = _map_wheel_entry_destination( + name, + parts, + expected_data_dir, + seen_destinations, + ) + if dest_rel is None: + continue + + if dest_rel.startswith("site-packages/"): + exclude_rx = ( + srcs_exclude_rx if dest_rel.endswith(".py") else data_exclude_rx + ) + if is_excluded(dest_rel, exclude_rx): + continue + + is_top_level_bin = dest_rel.startswith("bin/") and dest_rel.count("/") == 1 + if not is_top_level_bin: + yield info, dest_rel, False + continue + + script_name = dest_rel[len("bin/") :] + if script_name.lower() in ep_names_lower: + continue + + is_shebang_script = not script_name.endswith( + (".exe", ".dll") + ) and _has_python_shebang(zf, info) + if is_shebang_script: + yield info, script_name, True + continue + + yield info, dest_rel, False + + +def create_namespace_inits(site_packages_dir: Path, init_content: str) -> None: + """Populate pkgutil-style `__init__.py` files for implicit namespace packages.""" + all_rel_files = sorted( + p.relative_to(site_packages_dir).as_posix() + for p in site_packages_dir.rglob("*") + if p.is_file() + ) + + dirs: dict[str, None] = {} + ignored: dict[str, None] = {} + + def add_all(dirname: str, target: dict[str, None]) -> None: + dir_path = "." + for dir_name in dirname.split("/"): + dir_path = f"{dir_path}/{dir_name}" + target[dir_path[2:]] = None + + for file_rel in all_rel_files: + if "__pycache__" in file_rel.split("/"): + continue + dirname, _, filename = file_rel.rpartition("/") + if filename == "__init__.py": + ignored[dirname] = None + dirname, _, _ = dirname.rpartition("/") + elif not filename.endswith((".py", ".pyd", ".so")): + continue + + if dirname in dirs or not dirname: + continue + add_all(dirname, dirs) + + for d in sorted(d for d in dirs if d not in ignored): + init_path = site_packages_dir / d / "__init__.py" + if not init_path.exists(): + with open(init_path, "w", encoding="utf-8", newline="\n") as f: + f.write(init_content) + + +def _record_row(entry_path: str, full_path: Path) -> list[str]: + if entry_path.endswith((".pyc", ".pyo")): + return [entry_path, "", ""] + data = full_path.read_bytes() + digest = ( + base64.urlsafe_b64encode(hashlib.sha256(data).digest()) + .rstrip(b"=") + .decode("ascii") + ) + return [entry_path, f"sha256={digest}", str(len(data))] + + +def update_record_for_touched_files( + site_packages_dir: Path, + dist_info_dir: str, + touched_site_rel_paths: set[str], +) -> None: + """Update RECORD in `site-packages//RECORD` for touched files.""" + record_path = site_packages_dir / dist_info_dir / "RECORD" + if not record_path.is_file(): + return + + existing_text = record_path.read_text(encoding="utf-8") + out_buf = io.StringIO() + writer = csv.writer(out_buf, lineterminator="\n") + seen_touched: set[str] = set() + + for row in csv.reader(io.StringIO(existing_text)): + if not row: + continue + entry_path = row[0] + if entry_path not in touched_site_rel_paths: + writer.writerow(row) + continue + seen_touched.add(entry_path) + full_path = site_packages_dir / entry_path + if full_path.is_file(): + writer.writerow(_record_row(entry_path, full_path)) + + for entry_path in sorted(touched_site_rel_paths - seen_touched): + full_path = site_packages_dir / entry_path + if full_path.is_file(): + writer.writerow(_record_row(entry_path, full_path)) + + with open(record_path, "w", encoding="utf-8", newline="\n") as f: + f.write(out_buf.getvalue()) diff --git a/python/private/pypi/whl_archive.bzl b/python/private/pypi/whl_archive.bzl index 3ba32b1aa1..c1b06b8616 100644 --- a/python/private/pypi/whl_archive.bzl +++ b/python/private/pypi/whl_archive.bzl @@ -96,8 +96,18 @@ way to define whl_library and move whl patching to a separate place. INTERNAL US # legacy parameters that are global to the entire hub. "enable_implicit_namespace_pkgs", "envsubst", + "experimental_action_install", "pip_data_exclude", + "python_interpreter", + "python_interpreter_target", ] +} | { + "_inspect_whl": attr.label( + default = Label("//python/private/pypi:inspect_whl.py"), + ), + "_wheel_layout": attr.label( + default = Label("//python/private/pypi:wheel_layout.py"), + ), } | AUTH_ATTRS whl_archive = repository_rule( @@ -107,7 +117,7 @@ whl_archive = repository_rule( doc = """ Download and extracts a single wheel based into a bazel repo based on the requirement string passed in. -Does not depend on any python. +Does not depend on any python unless `experimental_action_install` is enabled. """, implementation = _whl_archive_impl, environ = [ diff --git a/python/private/pypi/whl_library.bzl b/python/private/pypi/whl_library.bzl index 3441a2c907..9349ef16d6 100644 --- a/python/private/pypi/whl_library.bzl +++ b/python/private/pypi/whl_library.bzl @@ -63,23 +63,30 @@ def whl_library(name, repo = None, **kwargs): # compatibility shim for cases for repo_prefix is still used by the called kwargs.setdefault("dep_template", "@{}{{name}}//:{{target}}".format(kwargs.pop("repo_prefix", ""))) - if whl_file or (urls and filename and filename.endswith(".whl")): - wheel_filename = filename or str(whl_file).split(":")[-1].split("/")[-1] - patches = get_whl_patches(kwargs.get("whl_patches", {}), wheel_filename) - if patches: - # Caller-owned wheels are often already supplied by _whl. - # Give their patched output a distinct repository name. - file_repo = name + ("_patched_whl" if whl_file else "_whl") - whl_file_repo( - name = file_repo, - patches = {patch: str(strip) for patch, strip in patches.items()}, - **_filter(kwargs, whl_file_repo_attrs) - ) - kwargs["whl_file"] = "@{}//:{}".format(file_repo, patched_whl_name(wheel_filename)) - kwargs["whl_patches"] = {} - elif not whl_file: - whl_file_repo(name = name + "_whl", **_filter(kwargs, whl_file_repo_attrs)) - kwargs["downloaded_whl"] = "@{}//:{}".format(name + "_whl", filename) - whl_archive(name = name, **_filter(kwargs, whl_archive_attrs)) - else: + is_direct_whl = bool(whl_file or (urls and filename and filename.endswith(".whl"))) + if not is_direct_whl: pip_archive(name = name, **_filter(kwargs, pip_archive_attrs)) + return + + wheel_filename = filename or str(whl_file).split(":")[-1].split("/")[-1] + patches = get_whl_patches(kwargs.get("whl_patches", {}), wheel_filename) + if patches: + # Caller-owned wheels are often already supplied by _whl. + # Give their patched output a distinct repository name. + file_repo = name + ("_patched_whl" if whl_file else "_whl") + whl_file_repo( + name = file_repo, + patches = {patch: str(strip) for patch, strip in patches.items()}, + **_filter(kwargs, whl_file_repo_attrs) + ) + kwargs["whl_file"] = "@{}//:{}".format(file_repo, patched_whl_name(wheel_filename)) + kwargs["whl_patches"] = {} + elif not whl_file: + whl_file_repo(name = name + "_whl", **_filter(kwargs, whl_file_repo_attrs)) + kwargs["downloaded_whl"] = "@{}//:{}".format(name + "_whl", filename) + + allowed_attrs = dict(whl_archive_attrs) + if not kwargs.get("experimental_action_install"): + allowed_attrs.pop("python_interpreter", None) + allowed_attrs.pop("python_interpreter_target", None) + whl_archive(name = name, **_filter(kwargs, allowed_attrs)) diff --git a/python/private/pypi/whl_library_srcs.bzl b/python/private/pypi/whl_library_srcs.bzl index 44d47eb250..02856ec7f8 100644 --- a/python/private/pypi/whl_library_srcs.bzl +++ b/python/private/pypi/whl_library_srcs.bzl @@ -6,12 +6,14 @@ load(":gen_wheel_record.bzl", "gen_wheel_record") load( ":labels.bzl", "DATA_LABEL", + "DEFAULT_DATA_EXCLUDE", "DIST_INFO_LABEL", "EXTRACTED_WHEEL_FILES", "PY_SRCS_LABEL", "WHEEL_FILE", ) load(":namespace_pkgs.bzl", _create_inits = "create_inits") +load(":py_wheel_library.bzl", "py_wheel_library") load(":venv_entry_point.bzl", "venv_entry_point") load(":venv_rewrite_shebang.bzl", "venv_rewrite_shebang") @@ -28,6 +30,79 @@ _BAZEL_REPO_FILE_GLOBS = [ _IS_VENV_SITE_PACKAGES_YES = Label("//python/config_settings:_is_venvs_site_packages_yes") _VENV_SITE_PACKAGES_FLAG = Label("//python/config_settings:venvs_site_packages") +def _add_copied_files_and_wheel_file( + *, + rules, + native, + copy_files, + copy_executables, + whl_file, + name, + visibility, + data): + for src, dest in copy_files.items(): + rules.copy_file( + name = dest + ".copy", + src = src, + out = dest, + visibility = visibility, + ) + data.append(dest) + for src, dest in copy_executables.items(): + rules.copy_file( + name = dest + ".copy", + src = src, + out = dest, + is_executable = True, + visibility = visibility, + ) + data.append(dest) + + if hasattr(native, "filegroup"): + native.filegroup( + name = WHEEL_FILE, + srcs = [whl_file or name], + visibility = visibility, + ) + +def _validate_action_install_args( + name, + *, + filegroups, + copy_files, + copy_executables, + extracted_files, + shebang_scripts, + _fail): + if filegroups != None: + _fail( + ( + "In '{}', custom glob-based 'filegroups' ({}) are not supported with experimental_action_install " + + "because wheel contents are extracted into the ':srcs' TreeArtifact during the build phase." + ).format(name, ", ".join(sorted(filegroups.keys()))), + ) + return False + + wheel_internal_srcs = {p: True for p in extracted_files} + for s in shebang_scripts: + wheel_internal_srcs["bin/" + s] = True + wheel_internal_srcs["bin/" + s + ".bat"] = True + bad_copy_srcs = sorted([ + src + for src in list(copy_files.keys()) + list(copy_executables.keys()) + if src in wheel_internal_srcs + ]) + if bad_copy_srcs: + _fail( + ( + "In '{}', 'copy_files'/'copy_executables' sources ({}) reference wheel-extracted paths, " + + "which are not available as repository files with experimental_action_install because wheel " + + "contents are extracted into the ':srcs' TreeArtifact during the build phase." + ).format(name, ", ".join(bad_copy_srcs)), + ) + return False + return True + def whl_library_srcs( *, name, @@ -44,10 +119,16 @@ def whl_library_srcs( native = native, enable_implicit_namespace_pkgs = False, namespace_package_files = [], + action_install = False, + extracted_files = [], + has_entry_points_txt = False, + shebang_scripts = [], visibility = ["//visibility:public"], + _fail = fail, rules = struct( copy_file = copy_file, py_library = py_library, + py_wheel_library = py_wheel_library, venv_entry_point = venv_entry_point, venv_rewrite_shebang = venv_rewrite_shebang, gen_wheel_record = gen_wheel_record, @@ -79,14 +160,29 @@ def whl_library_srcs( files for namespace pkgs. namespace_package_files: {type}`list[str]` A list of labels of files whose directories are namespace packages. + action_install: {type}`bool` Whether to install the wheel in a build action. + extracted_files: {type}`list[str]` Relative paths under the installed wheel directory. + has_entry_points_txt: {type}`bool` Whether a fetch-time `entry_points.txt` file exists in the package. + shebang_scripts: {type}`list[str]` Top-level script names in `.data/scripts/` with `#!python` shebangs. native: {type}`native` The native struct for overriding in tests. + _fail: {type}`callable` The fail function for overriding in tests. rules: {type}`struct` A struct with references to rules for creating targets. """ tags = sorted(tags) data = [] + data - bins_for_data_label = [] + if action_install and not _validate_action_install_args( + name, + filegroups = filegroups, + copy_files = copy_files, + copy_executables = copy_executables, + extracted_files = extracted_files, + shebang_scripts = shebang_scripts, + _fail = _fail, + ): + return + bins_for_data_label = [] for ep_dict in entry_points.values(): kwargs = dict(ep_dict) ep_name = kwargs.pop("name") @@ -98,6 +194,45 @@ def whl_library_srcs( bins_for_data_label.append(ep_target_name) data.append(ep_target_name) + if action_install: + _add_copied_files_and_wheel_file( + rules = rules, + native = native, + copy_files = copy_files, + copy_executables = copy_executables, + whl_file = whl_file, + name = name, + visibility = visibility, + data = data, + ) + if hasattr(native, "filegroup"): + for fg_name, fg_srcs in [ + (EXTRACTED_WHEEL_FILES, [PY_SRCS_LABEL]), + (DIST_INFO_LABEL, ["entry_points.txt"] if has_entry_points_txt else []), + (DATA_LABEL, [PY_SRCS_LABEL] + bins_for_data_label), + ]: + native.filegroup( + name = fg_name, + srcs = fg_srcs, + visibility = visibility, + ) + if hasattr(rules, "py_wheel_library"): + rules.py_wheel_library( + name = PY_SRCS_LABEL, + wheel = whl_file or name, + extracted_files = extracted_files, + shebang_scripts = shebang_scripts, + namespace_package_files = namespace_package_files, + srcs_exclude = srcs_exclude, + data_exclude = data_exclude, + enable_implicit_namespace_pkgs = enable_implicit_namespace_pkgs, + data = data, + tags = tags, + visibility = visibility, + experimental_venvs_site_packages = _VENV_SITE_PACKAGES_FLAG, + ) + return + existing_bin_names = {ep["name"].lower(): None for ep in entry_points.values()} for p in native.glob(["bin/*"], allow_empty = True): existing_bin_names[p[len("bin/"):].lower()] = None @@ -159,30 +294,16 @@ def whl_library_srcs( visibility = visibility, ) - for src, dest in copy_files.items(): - rules.copy_file( - name = dest + ".copy", - src = src, - out = dest, - visibility = visibility, - ) - data.append(dest) - for src, dest in copy_executables.items(): - rules.copy_file( - name = dest + ".copy", - src = src, - out = dest, - is_executable = True, - visibility = visibility, - ) - data.append(dest) - - if hasattr(native, "filegroup"): - native.filegroup( - name = WHEEL_FILE, - srcs = [whl_file or name], - visibility = visibility, - ) + _add_copied_files_and_wheel_file( + rules = rules, + native = native, + copy_files = copy_files, + copy_executables = copy_executables, + whl_file = whl_file, + name = name, + visibility = visibility, + data = data, + ) if hasattr(rules, "py_library"): srcs = native.glob( @@ -196,11 +317,7 @@ def whl_library_srcs( # NOTE: pyi files should probably be excluded because they're carried # by the pyi_srcs attribute. However, historical behavior included # them in data and some tools currently rely on that. - _data_exclude = [ - "**/*.py", - "**/*.pyc", - "**/*.pyc.*", # During pyc creation, temp files named *.pyc.NNNN are created - ] + _data_exclude = ["**/*.py"] + DEFAULT_DATA_EXCLUDE if sdist_filename: _data_exclude.append("**/*.dist-info/RECORD") for item in data_exclude: diff --git a/python/private/pypi/whl_library_targets.bzl b/python/private/pypi/whl_library_targets.bzl index a1cc727460..d365b4ca1d 100644 --- a/python/private/pypi/whl_library_targets.bzl +++ b/python/private/pypi/whl_library_targets.bzl @@ -41,6 +41,10 @@ def whl_library_targets( copy_executables = {}, srcs_exclude = [], data = [], + action_install = False, + extracted_files = [], + has_entry_points_txt = False, + shebang_scripts = [], visibility = ["//visibility:public"], **kwargs): """The macro to create whl targets from the METADATA. @@ -69,6 +73,10 @@ def whl_library_targets( copy_executables: {type}`dict[str, str]` The mapping between src and dest locations for executables. srcs_exclude: {type}`list[str]` The globs for srcs attribute exclusion. data: {type}`list[str]` A list of labels to include as part of the `data` attribute. + action_install: {type}`bool` Whether to install the wheel in a build action. + extracted_files: {type}`list[str]` Relative paths under the installed wheel directory. + has_entry_points_txt: {type}`bool` Whether a fetch-time `entry_points.txt` file exists in the package. + shebang_scripts: {type}`list[str]` Top-level script names in `.data/scripts/` with `#!python` shebangs. visibility: {type}`list[str]` The visibility of the targets. **kwargs: Extra args passed to the {obj}`whl_library_deps_targets` and {obj}`whl_library_srcs`. """ @@ -86,6 +94,10 @@ def whl_library_targets( copy_executables = copy_executables, enable_implicit_namespace_pkgs = enable_implicit_namespace_pkgs, namespace_package_files = namespace_package_files, + action_install = action_install, + extracted_files = extracted_files, + has_entry_points_txt = has_entry_points_txt, + shebang_scripts = shebang_scripts, **kwargs ) diff --git a/tests/pypi/extension/pip_parse.bzl b/tests/pypi/extension/pip_parse.bzl index d048f99bd0..2113d3825b 100644 --- a/tests/pypi/extension/pip_parse.bzl +++ b/tests/pypi/extension/pip_parse.bzl @@ -20,6 +20,7 @@ def pip_parse( auth_patterns = {}, download_only = False, enable_implicit_namespace_pkgs = False, + experimental_action_install = False, environment = {}, envsubst = [], experimental_extra_index_urls = [], @@ -52,6 +53,7 @@ def pip_parse( add_libdir_to_library_search_path = add_libdir_to_library_search_path, download_only = download_only, enable_implicit_namespace_pkgs = enable_implicit_namespace_pkgs, + experimental_action_install = experimental_action_install, environment = environment, envsubst = envsubst, experimental_extra_index_urls = experimental_extra_index_urls, diff --git a/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl b/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl index 646e4f2370..826efe60d5 100644 --- a/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl +++ b/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl @@ -268,6 +268,123 @@ whl_library_deps_targets( _tests.append(_test_deps_targets) +def _test_default_two_namespace_package_files(env): + want = """\ +load("@package_metadata//rules:package_metadata.bzl", "package_metadata") +load("@rules_python//python/private/pypi:whl_library_targets.bzl", "whl_library_targets") + +package(default_visibility = ["//visibility:public"]) + +whl_library_targets( + metadata_name = "foo", + name = "foo.whl", + namespace_package_files = ["site-packages/ns1/__init__.py", "site-packages/ns2/__init__.py"], + tags = [ + "pypi_name=foo", + "pypi_version=0", + ], +) +""" + actual = generate_whl_library_build_bazel( + metadata_version = "0", + metadata_name = "foo", + name = "foo.whl", + config_load = "@pypi//:config.bzl", + namespace_package_files = [ + "site-packages/ns1/__init__.py", + "site-packages/ns2/__init__.py", + ], + ) + env.expect.that_str(actual.replace("@@", "@")).equals(want) + +_tests.append(_test_default_two_namespace_package_files) + +def _test_action_install(env): + want = """\ +load("@package_metadata//rules:package_metadata.bzl", "package_metadata") +load("@rules_python//python/private/pypi:whl_library_targets.bzl", "whl_library_targets") + +package(default_visibility = ["//visibility:public"]) + +whl_library_targets( + action_install = True, + dep_template = "@pypi//{name}:{target}", + extracted_files = [ + "bin/bar", + "data/etc/d.txt", + "include/foo.h", + "site-packages/foo-0.dist-info/METADATA", + "site-packages/foo/__init__.py", + ], + has_entry_points_txt = True, + metadata_name = "foo", + name = "foo.whl", + namespace_package_files = ["site-packages/foo/__init__.py"], + shebang_scripts = ["baz"], + tags = [ + "pypi_name=foo", + "pypi_version=0", + ], +) +""" + actual = generate_whl_library_build_bazel( + metadata_version = "0", + metadata_name = "foo", + dep_template = "@pypi//{name}:{target}", + name = "foo.whl", + config_load = "@pypi//:config.bzl", + action_install = True, + extracted_files = [ + "bin/bar", + "data/etc/d.txt", + "include/foo.h", + "site-packages/foo-0.dist-info/METADATA", + "site-packages/foo/__init__.py", + ], + has_entry_points_txt = True, + namespace_package_files = ["site-packages/foo/__init__.py"], + shebang_scripts = ["baz"], + ) + env.expect.that_str(actual.replace("@@", "@")).equals(want) + +_tests.append(_test_action_install) + +def _test_action_install_glob_warning(env): + for action_install, content, want_warn in [ + (True, 'filegroup(name = "hdrs", srcs = glob(["site-packages/**/*.h"]))', True), + (True, 'load("//bazel:pip_parse_targets.bzl", "define_targets")\ndefine_targets()', False), + (False, 'filegroup(name = "hdrs", srcs = glob(["site-packages/**/*.h"]))', False), + (True, '# never use glob(["*.h"]) here\npy_library(name = "extra")', False), + (True, 'filegroup(name = "hdrs", srcs = glob (["site-packages/**/*.h"]))', True), + ]: + warnings = [] + generate_whl_library_build_bazel( + metadata_version = "0", + metadata_name = "foo", + dep_template = "@pypi//{name}:{target}", + name = "foo.whl", + config_load = "@pypi//:config.bzl", + action_install = action_install, + extracted_files = ["site-packages/foo/__init__.py"] if action_install else [], + annotation = struct( + copy_files = {}, + copy_executables = {}, + data = [], + data_exclude_glob = [], + srcs_exclude_glob = [], + additive_build_content = content, + ), + logger = struct(warn = warnings.append), + ) + env.expect.that_int(len(warnings)).equals(1 if want_warn else 0) + if want_warn: + env.expect.that_str(warnings[0]).contains( + "may glob wheel contents; globs match nothing under experimental_action_install", + ) + env.expect.that_str(warnings[0]).contains("':srcs' TreeArtifact") + +_tests.append(_test_action_install_glob_warning) + def generate_whl_library_build_bazel_test_suite(name): """Create the test suite. diff --git a/tests/pypi/hub_builder/hub_builder_tests.bzl b/tests/pypi/hub_builder/hub_builder_tests.bzl index dd7cd650b8..55c8040e70 100644 --- a/tests/pypi/hub_builder/hub_builder_tests.bzl +++ b/tests/pypi/hub_builder/hub_builder_tests.bzl @@ -17,6 +17,7 @@ load("@rules_testing//lib:test_suite.bzl", "test_suite") load("@rules_testing//lib:truth.bzl", "subjects") load("//python/private:repo_utils.bzl", "REPO_DEBUG_ENV_VAR", "REPO_VERBOSITY_ENV_VAR", "repo_utils") # buildifier: disable=bzl-visibility +load("//python/private/pypi:attrs.bzl", "use_action_install") # buildifier: disable=bzl-visibility load("//python/private/pypi:default_platforms.bzl", "default_platforms") # buildifier: disable=bzl-visibility load("//python/private/pypi:hub_builder.bzl", _hub_builder = "hub_builder") # buildifier: disable=bzl-visibility load("//python/private/pypi:parse_simpleapi_html.bzl", "parse_simpleapi_html") # buildifier: disable=bzl-visibility @@ -1830,6 +1831,95 @@ Attempting to create a duplicate library pypi_315_foo for foo with different arg _tests.append(_test_err_duplicate_repos) +def _test_experimental_action_install_precedence(env): + # When pip.parse sets experimental_action_install = True, RULES_PYTHON_EXPERIMENTAL_ACTION_INSTALL=0 + # in the environment must override it back to False. + builder_disabled = hub_builder(env) + builder_disabled.pip_parse( + _mock_mctx( + os_name = "osx", + arch_name = "aarch64", + environ = {"RULES_PYTHON_EXPERIMENTAL_ACTION_INSTALL": "0"}, + mock_files = { + "requirements.txt": "simple==0.0.1 @ https://example.org/simple-0.0.1-py3-none-any.whl --hash=sha256:deadbeef", + }, + ), + _parse( + hub_name = "pypi", + python_version = "3.15", + experimental_action_install = True, + requirements_lock = "requirements.txt", + ), + ) + pypi_disabled = builder_disabled.build() + pypi_disabled.whl_libraries().contains_exactly({ + "pypi_315_simple_py3_none_any_deadbeef": { + "config_load": "@pypi//:config.bzl", + "dep_template": "@pypi//{name}:{target}", + "filename": "simple-0.0.1-py3-none-any.whl", + "integrity": "sha256-3q2+7w==", + "requirement": "simple==0.0.1", + "urls": ["https://example.org/simple-0.0.1-py3-none-any.whl"], + }, + }) + + # When experimental_action_install is True (via pip.parse without env override), + # python_interpreter_target is forwarded even for direct wheel URLs. + builder_enabled = hub_builder(env) + builder_enabled.pip_parse( + _mock_mctx( + os_name = "osx", + arch_name = "aarch64", + mock_files = { + "requirements.txt": "simple==0.0.1 @ https://example.org/simple-0.0.1-py3-none-any.whl --hash=sha256:deadbeef", + }, + ), + _parse( + hub_name = "pypi", + python_version = "3.15", + experimental_action_install = True, + requirements_lock = "requirements.txt", + ), + ) + pypi_enabled = builder_enabled.build() + pypi_enabled.whl_libraries().contains_exactly({ + "pypi_315_simple_py3_none_any_deadbeef": { + "config_load": "@pypi//:config.bzl", + "dep_template": "@pypi//{name}:{target}", + "experimental_action_install": True, + "filename": "simple-0.0.1-py3-none-any.whl", + "integrity": "sha256-3q2+7w==", + "python_interpreter_target": "unit_test_interpreter_target", + "requirement": "simple==0.0.1", + "urls": ["https://example.org/simple-0.0.1-py3-none-any.whl"], + }, + }) + +_tests.append(_test_experimental_action_install_precedence) + +def _test_use_action_install_parsing(env): + for env_val in ("1", "true", "TRUE"): + ctx = struct(getenv = {"RULES_PYTHON_EXPERIMENTAL_ACTION_INSTALL": env_val}.get) + env.expect.that_bool( + use_action_install(ctx, struct(experimental_action_install = False)), + ).equals(True) + + for env_val in ("0", "false", "FALSE", ""): + ctx = struct(getenv = {"RULES_PYTHON_EXPERIMENTAL_ACTION_INSTALL": env_val}.get) + env.expect.that_bool( + use_action_install(ctx, struct(experimental_action_install = True)), + ).equals(False) + + unset_ctx = struct(getenv = {}.get) + env.expect.that_bool( + use_action_install(unset_ctx, struct(experimental_action_install = True)), + ).equals(True) + env.expect.that_bool( + use_action_install(unset_ctx, struct(experimental_action_install = False)), + ).equals(False) + +_tests.append(_test_use_action_install_parsing) + def hub_builder_test_suite(name): """Create the test suite. diff --git a/tests/pypi/py_wheel_library/BUILD.bazel b/tests/pypi/py_wheel_library/BUILD.bazel new file mode 100644 index 0000000000..6f29a887a2 --- /dev/null +++ b/tests/pypi/py_wheel_library/BUILD.bazel @@ -0,0 +1,12 @@ +load("//python:py_test.bzl", "py_test") +load(":py_wheel_library_bzl_tests.bzl", "py_wheel_library_bzl_test_suite") + +py_test( + name = "wheel_layout_and_installer_test", + srcs = ["wheel_layout_and_installer_test.py"], + deps = ["//python/private/pypi:wheel_installer_lib"], +) + +py_wheel_library_bzl_test_suite( + name = "py_wheel_library_bzl_tests", +) diff --git a/tests/pypi/py_wheel_library/py_wheel_library_bzl_tests.bzl b/tests/pypi/py_wheel_library/py_wheel_library_bzl_tests.bzl new file mode 100644 index 0000000000..437c318363 --- /dev/null +++ b/tests/pypi/py_wheel_library/py_wheel_library_bzl_tests.bzl @@ -0,0 +1,288 @@ +"""Analysis tests for py_wheel_library.""" + +load("@bazel_skylib//rules:write_file.bzl", "write_file") +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("@rules_testing//lib:util.bzl", rt_util = "util") +load("//python:py_info.bzl", "PyInfo") +load("//python/private:common_labels.bzl", "labels") # buildifier: disable=bzl-visibility +load("//python/private/pypi:py_wheel_library.bzl", "py_wheel_library") # buildifier: disable=bzl-visibility +load("//tests/support:py_info_subject.bzl", "py_info_subject") +load( + "//tests/support:support.bzl", + "CC_TOOLCHAIN", + "PY_TOOLCHAINS", +) + +_COMMON_CONFIG_SETTINGS = { + "//command_line_option:allow_unresolved_symlinks": True, + "//command_line_option:extra_toolchains": [PY_TOOLCHAINS, CC_TOOLCHAIN], + labels.EXEC_TOOLS_TOOLCHAIN: "enabled", + labels.PRECOMPILE: "auto", + labels.PRECOMPILE_SOURCE_RETENTION: "keep_source", +} + +_tests = [] + +def _test_pyi_files_exposed_when_stubs_present(name): + rt_util.helper_target( + write_file, + name = name + "_whl", + out = name + ".whl", + ) + rt_util.helper_target( + py_wheel_library, + name = name + "_with_pyi", + wheel = name + "_whl", + extracted_files = [ + "site-packages/foo/__init__.py", + "site-packages/foo/__init__.pyi", + ], + ) + rt_util.helper_target( + py_wheel_library, + name = name + "_with_py_typed", + wheel = name + "_whl", + extracted_files = [ + "site-packages/foo/__init__.py", + "site-packages/foo/py.typed", + ], + ) + rt_util.helper_target( + py_wheel_library, + name = name + "_with_py_typed_omit", + wheel = name + "_whl", + extracted_files = [ + "site-packages/foo/__init__.py", + "site-packages/foo/py.typed", + ], + precompile = "enabled", + precompile_source_retention = "omit_source", + ) + rt_util.helper_target( + py_wheel_library, + name = name + "_no_stubs", + wheel = name + "_whl", + extracted_files = [ + "site-packages/foo/__init__.py", + ], + ) + analysis_test( + name = name, + impl = _test_pyi_files_exposed_when_stubs_present_impl, + targets = { + "no_stubs": name + "_no_stubs", + "with_py_typed": name + "_with_py_typed", + "with_py_typed_omit": name + "_with_py_typed_omit", + "with_pyi": name + "_with_pyi", + }, + config_settings = _COMMON_CONFIG_SETTINGS, + ) + +def _test_pyi_files_exposed_when_stubs_present_impl(env, targets): + with_pyi_info = env.expect.that_target(targets.with_pyi).provider( + PyInfo, + factory = py_info_subject, + ) + with_pyi_info.direct_pyi_files().contains_exactly([ + "{package}/" + targets.with_pyi.label.name, + ]) + with_py_typed_info = env.expect.that_target(targets.with_py_typed).provider( + PyInfo, + factory = py_info_subject, + ) + with_py_typed_info.direct_pyi_files().contains_exactly([ + "{package}/" + targets.with_py_typed.label.name, + ]) + with_py_typed_omit_info = env.expect.that_target(targets.with_py_typed_omit).provider( + PyInfo, + factory = py_info_subject, + ) + with_py_typed_omit_info.direct_pyi_files().contains_exactly([]) + no_stubs_info = env.expect.that_target(targets.no_stubs).provider( + PyInfo, + factory = py_info_subject, + ) + no_stubs_info.direct_pyi_files().contains_exactly([]) + +_tests.append(_test_pyi_files_exposed_when_stubs_present) + +def _test_precompile_flags_and_providers(name): + rt_util.helper_target( + write_file, + name = name + "_whl", + out = name + ".whl", + ) + rt_util.helper_target( + py_wheel_library, + name = name + "_default", + wheel = name + "_whl", + extracted_files = ["site-packages/foo/__init__.py"], + ) + rt_util.helper_target( + py_wheel_library, + name = name + "_enabled", + wheel = name + "_whl", + extracted_files = ["site-packages/foo/__init__.py"], + precompile = "enabled", + ) + rt_util.helper_target( + py_wheel_library, + name = name + "_omit_source", + wheel = name + "_whl", + extracted_files = ["site-packages/foo/__init__.py"], + precompile = "enabled", + precompile_source_retention = "omit_source", + ) + analysis_test( + name = name, + impl = _test_precompile_flags_and_providers_impl, + targets = { + "default": name + "_default", + "enabled": name + "_enabled", + "omit_source": name + "_omit_source", + }, + config_settings = _COMMON_CONFIG_SETTINGS, + ) + +def _test_precompile_flags_and_providers_impl(env, targets): + default_t = env.expect.that_target(targets.default) + default_info = default_t.provider(PyInfo, factory = py_info_subject) + default_info.direct_pyc_files().contains_exactly([]) + default_info.transitive_sources().contains_exactly([ + "{package}/" + targets.default.label.name, + ]) + + enabled_t = env.expect.that_target(targets.enabled) + enabled_info = enabled_t.provider(PyInfo, factory = py_info_subject) + enabled_info.direct_pyc_files().contains_exactly([ + "{package}/" + targets.enabled.label.name, + ]) + enabled_info.transitive_sources().contains_exactly([ + "{package}/" + targets.enabled.label.name, + ]) + enabled_t.action_generating("{package}/" + targets.enabled.label.name).argv().contains_at_least([ + "--precompile", + "--pyc-tag", + "fakepy-45", + "--precompile-invalidation-mode", + "checked_hash", + "--precompile-source-retention", + "keep_source", + ]) + + omit_t = env.expect.that_target(targets.omit_source) + omit_info = omit_t.provider(PyInfo, factory = py_info_subject) + omit_info.direct_pyc_files().contains_exactly([ + "{package}/" + targets.omit_source.label.name, + ]) + omit_info.transitive_sources().contains_exactly([]) + omit_t.action_generating("{package}/" + targets.omit_source.label.name).argv().contains_at_least([ + "--precompile", + "--precompile-source-retention", + "omit_source", + ]) + +_tests.append(_test_precompile_flags_and_providers) + +def _test_package_and_version_from_dist_info(name): + rt_util.helper_target( + write_file, + name = name + "_whl", + out = name + ".whl", + ) + rt_util.helper_target( + py_wheel_library, + name = name + "_from_metadata", + wheel = name + "_whl", + extracted_files = [ + "site-packages/My_Pkg-1.2.0.dist-info/METADATA", + "site-packages/my_pkg/__init__.py", + "site-packages/my_pkg/_vendor/vendored-9.9.0.dist-info/METADATA", + ], + experimental_venvs_site_packages = labels.VENVS_SITE_PACKAGES, + ) + rt_util.helper_target( + py_wheel_library, + name = name + "_from_tags", + wheel = name + "_whl", + extracted_files = [ + "site-packages/tag_pkg/__init__.py", + ], + tags = [ + "pypi_name=Tag_Pkg", + "pypi_version=2.3.0", + ], + experimental_venvs_site_packages = labels.VENVS_SITE_PACKAGES, + ) + analysis_test( + name = name, + impl = _test_package_and_version_from_dist_info_impl, + targets = { + "from_metadata": name + "_from_metadata", + "from_tags": name + "_from_tags", + }, + config_settings = _COMMON_CONFIG_SETTINGS | { + labels.VENVS_SITE_PACKAGES: "yes", + }, + ) + +def _test_package_and_version_from_dist_info_impl(env, targets): + meta_entries = targets.from_metadata[PyInfo].venv_symlinks.to_list() + env.expect.that_collection([ + (e.venv_path, e.package, e.version) + for e in meta_entries + ]).contains_exactly([ + ("My_Pkg-1.2.0.dist-info", "my_pkg", "1.2.0"), + ("my_pkg", "my_pkg", "1.2.0"), + ]) + + tag_entries = targets.from_tags[PyInfo].venv_symlinks.to_list() + env.expect.that_collection([ + (e.venv_path, e.package, e.version) + for e in tag_entries + ]).contains_exactly([ + ("tag_pkg", "tag_pkg", "2.3.0"), + ]) + +_tests.append(_test_package_and_version_from_dist_info) + +def _test_missing_exec_tools_toolchain_fails(name): + rt_util.helper_target( + write_file, + name = name + "_whl", + out = name + ".whl", + ) + rt_util.helper_target( + py_wheel_library, + name = name + "_subject", + wheel = name + "_whl", + extracted_files = ["site-packages/foo/__init__.py"], + ) + analysis_test( + name = name, + impl = _test_missing_exec_tools_toolchain_fails_impl, + target = name + "_subject", + expect_failure = True, + config_settings = _COMMON_CONFIG_SETTINGS | { + "//command_line_option:extra_toolchains": [ + str(Label("//tests/support/py_toolchains:platform_toolchain")), + CC_TOOLCHAIN, + ], + labels.EXEC_TOOLS_TOOLCHAIN: "disabled", + }, + ) + +def _test_missing_exec_tools_toolchain_fails_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.contains("experimental_action_install requires the exec_tools toolchain"), + ) + +_tests.append(_test_missing_exec_tools_toolchain_fails) + +def py_wheel_library_bzl_test_suite(name): + test_suite( + name = name, + tests = _tests, + ) diff --git a/tests/pypi/py_wheel_library/wheel_layout_and_installer_test.py b/tests/pypi/py_wheel_library/wheel_layout_and_installer_test.py new file mode 100644 index 0000000000..6e8a9137f2 --- /dev/null +++ b/tests/pypi/py_wheel_library/wheel_layout_and_installer_test.py @@ -0,0 +1,548 @@ +"""Unit tests for wheel_layout, inspect_whl, and action_whl_installer.""" + +from __future__ import annotations + +import contextlib +import importlib.machinery +import importlib.util +import io +import json +import pathlib +import sys +import tempfile +import unittest +import zipfile + +import action_whl_installer +import inspect_whl +import wheel_layout + + +def _write_zip(path: pathlib.Path, entries: dict[str, bytes | str]) -> pathlib.Path: + with zipfile.ZipFile(path, "w") as zf: + for name, data in entries.items(): + info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) + info.external_attr = 0o644 << 16 + raw = data.encode("utf-8") if isinstance(data, str) else data + zf.writestr(info, raw) + return path + + +class WheelLayoutAndInstallerTest(unittest.TestCase): + def test_sanitize_wheel_entry_path_rejects_traversal(self): + for bad in [ + "/abs/path.py", + "\\backslash.py", + "a\\b.py", + "../escape.py", + "pkg/../../escape.py", + "pkg/./mod.py", + "pkg//mod.py", + "C:drive.py", + "C:/drive.py", + ]: + with self.subTest(bad=bad): + with self.assertRaises(ValueError): + wheel_layout.sanitize_wheel_entry_path(bad) + + self.assertEqual( + wheel_layout.sanitize_wheel_entry_path("pkg/sub/mod.py"), + ["pkg", "sub", "mod.py"], + ) + + def test_glob_matching(self): + patterns = [ + wheel_layout.glob_to_regex(p) for p in ["**/*.pyc", "pkg/skip_*.py"] + ] + self.assertTrue(wheel_layout.is_excluded("a/b/c.pyc", patterns)) + self.assertTrue(wheel_layout.is_excluded("c.pyc", patterns)) + self.assertTrue(wheel_layout.is_excluded("pkg/skip_me.py", patterns)) + self.assertFalse(wheel_layout.is_excluded("pkg/keep.py", patterns)) + + def test_data_dir_stem_and_root_data_file(self): + with tempfile.TemporaryDirectory() as tmp: + whl = _write_zip( + pathlib.Path(tmp) / "mylib-1.0-py3-none-any.whl", + { + "mylib-1.0.dist-info/METADATA": "Name: mylib\nVersion: 1.0\n", + "mylib-1.0.dist-info/WHEEL": "Wheel-Version: 1.0\n", + "mylib-1.0.dist-info/RECORD": "", + "mylib.data": "top-level file ending in .data", + "other.data/foo.txt": "not the wheel data dir", + "mylib-1.0.data/purelib/mylib/pure.py": "PURE = 1\n", + "mylib-1.0.data/platlib/mylib/plat.py": "PLAT = 1\n", + "mylib-1.0.data/headers/mylib.h": "#pragma once\n", + "mylib-1.0.data/data/etc/cfg.ini": "[cfg]\n", + "mylib-1.0.data/scripts/my_tool": "#!python -u\nprint('hi')\n", + "mylib-1.0.data/scripts/plain_sh": "#!/bin/sh\necho hi\n", + }, + ) + info = inspect_whl.inspect_wheel( + whl, + srcs_exclude_globs=[], + data_exclude_globs=[], + ) + self.assertFalse(info["has_entry_points_txt"]) + self.assertEqual(info["entry_points_content"], "") + self.assertIn("site-packages/mylib.data", info["extracted_files"]) + self.assertIn("site-packages/other.data/foo.txt", info["extracted_files"]) + self.assertIn("site-packages/mylib/pure.py", info["extracted_files"]) + self.assertIn("site-packages/mylib/plat.py", info["extracted_files"]) + self.assertIn("include/mylib.h", info["extracted_files"]) + self.assertIn("data/etc/cfg.ini", info["extracted_files"]) + self.assertIn("bin/plain_sh", info["extracted_files"]) + self.assertEqual(info["shebang_scripts"], ["my_tool"]) + + # Verify parity with action_whl_installer on both unix and windows. + for target_os in ("unix", "windows"): + dest = pathlib.Path(tmp) / f"installed_{target_os}" + action_whl_installer.install_wheel( + wheel_path=whl, + dest_dir=dest, + srcs_exclude_globs=[], + data_exclude_globs=[], + create_namespace_inits_flag=False, + target_os=target_os, + ) + actual_files = sorted( + p.relative_to(dest).as_posix() + for p in dest.rglob("*") + if p.is_file() + ) + expected_files = list(info["extracted_files"]) + for s in info["shebang_scripts"]: + if target_os == "windows": + expected_files.append(f"bin/{s}.bat") + else: + expected_files.append(f"bin/{s}") + expected_files.sort() + self.assertEqual(actual_files, expected_files) + if target_os == "unix": + script_text = (dest / "bin/my_tool").read_text(encoding="utf-8") + self.assertTrue( + script_text.startswith("#!/bin/sh\n"), + script_text, + ) + else: + self.assertTrue((dest / "bin/my_tool.bat").is_file()) + + def test_dist_info_validation_and_entry_points_matching(self): + with tempfile.TemporaryDirectory() as tmp: + no_meta = _write_zip( + pathlib.Path(tmp) / "nometa-1.0-py3-none-any.whl", + {"nometa/__init__.py": ""}, + ) + with self.assertRaisesRegex(ValueError, "no '\\*\\.dist-info/METADATA'"): + inspect_whl.inspect_wheel(no_meta) + + multi_meta = _write_zip( + pathlib.Path(tmp) / "multi-1.0-py3-none-any.whl", + { + "a-1.0.dist-info/METADATA": "Name: a\nVersion: 1.0\n", + "b-1.0.dist-info/METADATA": "Name: b\nVersion: 1.0\n", + }, + ) + with self.assertRaisesRegex( + ValueError, "multiple \\.dist-info directories" + ): + inspect_whl.inspect_wheel(multi_meta) + + stray_ep = _write_zip( + pathlib.Path(tmp) / "stray-1.0-py3-none-any.whl", + { + "other-2.0.dist-info/entry_points.txt": ( + "[console_scripts]\nbogus = other:main\n" + ), + "stray-1.0.dist-info/METADATA": "Name: stray\nVersion: 1.0\n", + }, + ) + stray_info = inspect_whl.inspect_wheel(stray_ep) + self.assertFalse(stray_info["has_entry_points_txt"]) + self.assertEqual(stray_info["entry_points_content"], "") + + with_ep = _write_zip( + pathlib.Path(tmp) / "ep-1.0-py3-none-any.whl", + { + "ep-1.0.dist-info/METADATA": "Name: ep\nVersion: 1.0\n", + "ep-1.0.dist-info/entry_points.txt": ( + "[console_scripts]\nmy-ep = ep:main\n" + ), + }, + ) + ep_info = inspect_whl.inspect_wheel(with_ep) + self.assertTrue(ep_info["has_entry_points_txt"]) + self.assertIn("my-ep = ep:main", ep_info["entry_points_content"]) + + def test_duplicate_destination_and_unknown_data_category_fail(self): + with tempfile.TemporaryDirectory() as tmp: + whl = _write_zip( + pathlib.Path(tmp) / "dup-1.0-py3-none-any.whl", + { + "dup-1.0.dist-info/METADATA": "Name: dup\nVersion: 1.0\n", + "dup-1.0.data/purelib/dup/mod.py": "X = 1\n", + "dup-1.0.data/platlib/dup/mod.py": "X = 2\n", + }, + ) + with self.assertRaisesRegex(ValueError, "Detected collision"): + inspect_whl.inspect_wheel( + whl, srcs_exclude_globs=[], data_exclude_globs=[] + ) + with self.assertRaisesRegex(ValueError, "Detected collision"): + action_whl_installer.install_wheel( + wheel_path=whl, + dest_dir=pathlib.Path(tmp) / "out", + srcs_exclude_globs=[], + data_exclude_globs=[], + create_namespace_inits_flag=False, + target_os="unix", + ) + + case_whl = _write_zip( + pathlib.Path(tmp) / "casedup-1.0-py3-none-any.whl", + { + "casedup-1.0.dist-info/METADATA": "Name: casedup\nVersion: 1.0\n", + "Foo/mod.py": "X = 1\n", + "foo/mod.py": "X = 2\n", + }, + ) + with self.assertRaisesRegex(ValueError, "Detected collision"): + inspect_whl.inspect_wheel(case_whl) + + bad_cat = _write_zip( + pathlib.Path(tmp) / "badcat-1.0-py3-none-any.whl", + { + "badcat-1.0.dist-info/METADATA": "Name: badcat\nVersion: 1.0\n", + "badcat-1.0.data/unknown_scheme/file.txt": "hi\n", + }, + ) + with self.assertRaisesRegex(ValueError, "Unknown \\.data category"): + inspect_whl.inspect_wheel(bad_cat) + + def test_cli_entrypoints_and_error_reporting(self): + with tempfile.TemporaryDirectory() as tmp: + not_a_zip = pathlib.Path(tmp) / "corrupt.whl" + not_a_zip.write_text("not a zip", encoding="utf-8") + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + rc = inspect_whl.main(["--wheel", str(not_a_zip)]) + self.assertEqual(rc, 1) + self.assertIn("inspect_whl: failed to inspect", stderr.getvalue()) + + good_whl = _write_zip( + pathlib.Path(tmp) / "cli-1.0-py3-none-any.whl", + { + "cli-1.0.dist-info/METADATA": "Name: cli\nVersion: 1.0\n", + "cli/__init__.py": "X = 1\n", + }, + ) + stdout = io.StringIO() + with contextlib.redirect_stdout(stdout): + rc = inspect_whl.main(["--wheel", str(good_whl)]) + self.assertEqual(rc, 0) + parsed = json.loads(stdout.getvalue()) + self.assertIn("site-packages/cli/__init__.py", parsed["extracted_files"]) + + cli_dest = pathlib.Path(tmp) / "cli_installed" + action_whl_installer.main( + ["--wheel", str(good_whl), "--directory", str(cli_dest)] + ) + self.assertTrue((cli_dest / "site-packages/cli/__init__.py").is_file()) + + def test_record_rewriting_and_namespace_inits(self): + with tempfile.TemporaryDirectory() as tmp: + whl = _write_zip( + pathlib.Path(tmp) / "ns-1.0-py3-none-any.whl", + { + "ns-1.0.dist-info/METADATA": "Name: ns\nVersion: 1.0\n", + "ns-1.0.dist-info/RECORD": ( + "ns-1.0.data/scripts/my_script,sha256=abc,12\n" + "ns-1.0.data/purelib/ns/sep\u2028file.txt,sha256=ghi,3\n" + "ns/sub/mod.py,sha256=def,10\n" + ), + "ns-1.0.data/scripts/my_script": "#!python\nprint(1)\n", + "ns-1.0.data/purelib/ns/sep\u2028file.txt": "ok\n", + "ns/sub/mod.py": "VAL = 1\n", + "ns/sub/__pycache__/mod.cpython-312.pyc": b"\x00\x01", + "pyc_only_dir/ stale.pyc": b"\x00\x01", + }, + ) + dest = pathlib.Path(tmp) / "out" + action_whl_installer.install_wheel( + wheel_path=whl, + dest_dir=dest, + srcs_exclude_globs=[], + data_exclude_globs=["**/*.pyc"], + create_namespace_inits_flag=True, + target_os="unix", + ) + with open( + dest / "site-packages/ns-1.0.dist-info/RECORD", encoding="utf-8" + ) as f: + record_lines = list(f) + self.assertEqual( + record_lines, + [ + "../../../bin/my_script,sha256=abc,12\n", + "ns/sep\u2028file.txt,sha256=ghi,3\n", + "ns/sub/mod.py,sha256=def,10\n", + ], + ) + self.assertTrue((dest / "site-packages/ns/__init__.py").is_file()) + self.assertTrue((dest / "site-packages/ns/sub/__init__.py").is_file()) + self.assertFalse( + (dest / "site-packages/ns/sub/__pycache__/__init__.py").exists() + ) + self.assertFalse((dest / "site-packages/pyc_only_dir/__init__.py").exists()) + + def test_precompile_keep_and_omit_source(self): + with tempfile.TemporaryDirectory() as tmp: + whl = _write_zip( + pathlib.Path(tmp) / "pcpkg-1.0-py3-none-any.whl", + { + "pcpkg-1.0.dist-info/METADATA": "Name: pcpkg\nVersion: 1.0\n", + "pcpkg-1.0.dist-info/RECORD": ( + "pcpkg/__init__.py,sha256=abc,10\npcpkg/mod.py,sha256=def,12\n" + ), + "pcpkg/__init__.py": "from .mod import ANSWER\n", + "pcpkg/mod.py": "ANSWER = 42\n", + }, + ) + pyc_tag = sys.implementation.cache_tag + py_ver = f"{sys.version_info.major}.{sys.version_info.minor}" + + # 1. precompile=False -> no pycs + dest_disabled = pathlib.Path(tmp) / "out_disabled" + action_whl_installer.install_wheel( + wheel_path=whl, + dest_dir=dest_disabled, + precompile=False, + ) + self.assertEqual(list(dest_disabled.rglob("*.pyc")), []) + + # 2. precompile=True, keep_source -> .py and __pycache__/*.pyc present + dest_keep = pathlib.Path(tmp) / "out_keep" + action_whl_installer.install_wheel( + wheel_path=whl, + dest_dir=dest_keep, + precompile=True, + pyc_tag=pyc_tag, + precompile_invalidation_mode="checked_hash", + precompile_source_retention="keep_source", + python_version=py_ver, + src_name_prefix="pkg/srcs", + ) + self.assertTrue((dest_keep / "site-packages/pcpkg/__init__.py").is_file()) + self.assertTrue((dest_keep / "site-packages/pcpkg/mod.py").is_file()) + self.assertTrue( + ( + dest_keep + / f"site-packages/pcpkg/__pycache__/__init__.{pyc_tag}.pyc" + ).is_file() + ) + self.assertTrue( + ( + dest_keep / f"site-packages/pcpkg/__pycache__/mod.{pyc_tag}.pyc" + ).is_file() + ) + record_keep = ( + dest_keep / "site-packages/pcpkg-1.0.dist-info/RECORD" + ).read_text(encoding="utf-8") + self.assertIn("pcpkg/mod.py,sha256=def,12\n", record_keep) + self.assertIn(f"pcpkg/__pycache__/mod.{pyc_tag}.pyc,,\n", record_keep) + + # 3. precompile=True, omit_source -> .py removed, only foo.pyc written (no __pycache__) + dest_omit = pathlib.Path(tmp) / "out_omit" + action_whl_installer.install_wheel( + wheel_path=whl, + dest_dir=dest_omit, + precompile=True, + pyc_tag=pyc_tag, + precompile_invalidation_mode="unchecked_hash", + precompile_source_retention="omit_source", + python_version=py_ver, + src_name_prefix="pkg/srcs", + ) + self.assertEqual(list(dest_omit.rglob("*.py")), []) + self.assertFalse((dest_omit / "site-packages/pcpkg/__pycache__").exists()) + self.assertTrue((dest_omit / "site-packages/pcpkg/__init__.pyc").is_file()) + self.assertTrue((dest_omit / "site-packages/pcpkg/mod.pyc").is_file()) + record_omit = ( + dest_omit / "site-packages/pcpkg-1.0.dist-info/RECORD" + ).read_text(encoding="utf-8") + self.assertNotIn("pcpkg/mod.py,", record_omit) + self.assertNotIn("__pycache__", record_omit) + self.assertIn("pcpkg/mod.pyc,,\n", record_omit) + + sp_str = str(dest_omit / "site-packages") + sys.path.insert(0, sp_str) + try: + sys.modules.pop("pcpkg", None) + sys.modules.pop("pcpkg.mod", None) + spec = importlib.util.find_spec("pcpkg") + self.assertIsNotNone(spec) + pcpkg = importlib.import_module("pcpkg") + self.assertEqual(pcpkg.ANSWER, 42) + finally: + sys.path.remove(sp_str) + sys.modules.pop("pcpkg", None) + sys.modules.pop("pcpkg.mod", None) + + def test_precompile_syntax_error_and_custom_precompiler(self): + with tempfile.TemporaryDirectory() as tmp: + whl = _write_zip( + pathlib.Path(tmp) / "badpy-1.0-py3-none-any.whl", + { + "badpy-1.0.dist-info/METADATA": "Name: badpy\nVersion: 1.0\n", + "badpy-1.0.dist-info/RECORD": ( + "badpy/__init__.py,sha256=abc,10\nbadpy/py2_only.py,sha256=def,12\n" + ), + "badpy/__init__.py": "OK = True\n", + "badpy/py2_only.py": "print 'py2 syntax'\n", + }, + ) + pyc_tag = sys.implementation.cache_tag + py_ver = f"{sys.version_info.major}.{sys.version_info.minor}" + + # 1. In-process py_compile with omit_source retains py2_only.py and writes stub py2_only.pyc + dest_inproc = pathlib.Path(tmp) / "out_inproc" + action_whl_installer.install_wheel( + wheel_path=whl, + dest_dir=dest_inproc, + precompile=True, + pyc_tag=pyc_tag, + precompile_source_retention="omit_source", + python_version=py_ver, + ) + self.assertTrue( + (dest_inproc / "site-packages/badpy/__init__.pyc").is_file() + ) + self.assertFalse((dest_inproc / "site-packages/badpy/__init__.py").exists()) + self.assertTrue((dest_inproc / "site-packages/badpy/py2_only.py").is_file()) + self.assertTrue( + (dest_inproc / "site-packages/badpy/py2_only.pyc").is_file() + ) + sp_inproc = str(dest_inproc / "site-packages") + sys.path.insert(0, sp_inproc) + try: + sys.modules.pop("badpy", None) + sys.modules.pop("badpy.py2_only", None) + with self.assertRaises(SyntaxError): + importlib.import_module("badpy.py2_only") + # Also verify the stub .pyc directly (as loaded in a venv that symlinks only .pyc): + loader = importlib.machinery.SourcelessFileLoader( + "badpy.py2_only", + str(dest_inproc / "site-packages/badpy/py2_only.pyc"), + ) + spec = importlib.util.spec_from_loader("badpy.py2_only", loader) + assert spec is not None # type assert + mod = importlib.util.module_from_spec(spec) + with self.assertRaises(SyntaxError) as cm: + loader.exec_module(mod) + self.assertEqual( + cm.exception.filename, "site-packages/badpy/py2_only.py" + ) + self.assertEqual(cm.exception.lineno, 1) + self.assertNotIn(tmp, cm.exception.msg) + finally: + sys.path.remove(sp_inproc) + sys.modules.pop("badpy", None) + sys.modules.pop("badpy.py2_only", None) + + # 2. Custom executable precompiler tool: batched on valid wheel, bisected on bad file + count_file = pathlib.Path(tmp) / "count.txt" + fake_py = pathlib.Path(tmp) / "fake_precompiler_impl.py" + fake_py.write_text( + "import pathlib, py_compile, sys\n" + f"count_p = pathlib.Path({str(count_file)!r})\n" + "n = int(count_p.read_text()) if count_p.exists() else 0\n" + "count_p.write_text(str(n + 1))\n" + "args = pathlib.Path(sys.argv[1][1:]).read_text().splitlines()\n" + "srcs = [args[i + 1] for i, a in enumerate(args) if a == '--src']\n" + "pycs = [args[i + 1] for i, a in enumerate(args) if a == '--pyc']\n" + "for s, c in zip(srcs, pycs):\n" + " py_compile.compile(s, cfile=c, doraise=True)\n", + encoding="utf-8", + ) + fake_tool = pathlib.Path(tmp) / "fake_precompiler.sh" + fake_tool.write_text( + f'#!/bin/sh\nexec "{sys.executable}" "{fake_py}" "$@"\n', + encoding="utf-8", + ) + fake_tool.chmod(0o755) + + valid_whl = _write_zip( + pathlib.Path(tmp) / "goodpy-1.0-py3-none-any.whl", + { + "goodpy-1.0.dist-info/METADATA": "Name: goodpy\nVersion: 1.0\n", + "goodpy-1.0.dist-info/RECORD": ( + "goodpy/a.py,sha256=abc,4\ngoodpy/b.py,sha256=def,4\n" + ), + "goodpy/a.py": "A = 1\n", + "goodpy/b.py": "B = 2\n", + }, + ) + dest_batch = pathlib.Path(tmp) / "out_batch" + action_whl_installer.install_wheel( + wheel_path=valid_whl, + dest_dir=dest_batch, + precompile=True, + pyc_tag=pyc_tag, + precompile_source_retention="keep_source", + python_version=py_ver, + precompiler_tool=fake_tool, + ) + self.assertEqual(int(count_file.read_text()), 1) + self.assertTrue( + ( + dest_batch / f"site-packages/goodpy/__pycache__/a.{pyc_tag}.pyc" + ).is_file() + ) + self.assertTrue( + ( + dest_batch / f"site-packages/goodpy/__pycache__/b.{pyc_tag}.pyc" + ).is_file() + ) + + # Bisection fallback when 1 of 8 files fails: 1 + 2*log2(8) = 7 spawns (< 1 + 8 = 9). + eight_whl = _write_zip( + pathlib.Path(tmp) / "eight-1.0-py3-none-any.whl", + { + "eight-1.0.dist-info/METADATA": "Name: eight\nVersion: 1.0\n", + "eight-1.0.dist-info/RECORD": "", + "eight/f0.py": "X = 0\n", + "eight/f1.py": "X = 1\n", + "eight/f2.py": "X = 2\n", + "eight/f3.py": "X = 3\n", + "eight/f4.py": "X = 4\n", + "eight/f5_bad.py": "print 'py2'\n", + "eight/f6.py": "X = 6\n", + "eight/f7.py": "X = 7\n", + }, + ) + count_file.unlink() + dest_fallback = pathlib.Path(tmp) / "out_fallback" + action_whl_installer.install_wheel( + wheel_path=eight_whl, + dest_dir=dest_fallback, + precompile=True, + pyc_tag=pyc_tag, + precompile_source_retention="keep_source", + python_version=py_ver, + precompiler_tool=fake_tool, + ) + self.assertEqual(int(count_file.read_text()), 7) + self.assertTrue( + ( + dest_fallback / f"site-packages/eight/__pycache__/f0.{pyc_tag}.pyc" + ).is_file() + ) + self.assertTrue( + ( + dest_fallback + / f"site-packages/eight/__pycache__/f5_bad.{pyc_tag}.pyc" + ).is_file() + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/pypi/whl_library_srcs/whl_library_srcs_tests.bzl b/tests/pypi/whl_library_srcs/whl_library_srcs_tests.bzl index 740d70e3fb..340980d185 100644 --- a/tests/pypi/whl_library_srcs/whl_library_srcs_tests.bzl +++ b/tests/pypi/whl_library_srcs/whl_library_srcs_tests.bzl @@ -265,6 +265,207 @@ def _test_exclude_bazel_files(env): _tests.append(_test_exclude_bazel_files) +def _test_default_mode_data_order(env): + py_library_calls = [] + m_glob = mocks.glob() + m_glob.results.append([]) # bin/* + m_glob.results.append(["rewrite-bin/rewritten_script"]) # rewrite-bin/* + m_glob.results.append(["rewrite-record/foo-1.0.dist-info/RECORD"]) # rewrite-record/*/RECORD + m_glob.results.append([]) # srcs + m_glob.results.append(["site-packages/foo/asset.dat"]) # site-packages/**/* data + m_glob.results.append([]) # pyi + + whl_library_srcs( + name = "foo.whl", + filegroups = {}, + data = ["user_data"], + entry_points = { + "ep_cli": { + "group": "console_scripts", + "module": "foo.cli", + "name": "ep_cli", + "object": "main", + }, + }, + copy_files = {"@ext//:file_src": "file_dest"}, + copy_executables = {"@ext//:exec_src": "exec_dest"}, + native = struct( + filegroup = lambda **_: None, + glob = m_glob.glob, + ), + rules = struct( + copy_file = lambda **_: None, + py_library = lambda **kwargs: py_library_calls.append(kwargs), + create_inits = lambda **_: [], + venv_entry_point = lambda **_: None, + venv_rewrite_shebang = lambda **_: None, + gen_wheel_record = lambda **_: None, + ), + ) + + env.expect.that_int(len(py_library_calls)).equals(1) + env.expect.that_collection(py_library_calls[0]["data"]).contains_exactly([ + "user_data", + "bin/ep_cli", + "bin/rewritten_script", + "record", + "file_dest", + "exec_dest", + "site-packages/foo/asset.dat", + "data", + ]).in_order() + +_tests.append(_test_default_mode_data_order) + +def _test_action_install(env): + filegroup_calls = [] + copy_calls = [] + entry_point_calls = [] + py_wheel_library_calls = [] + + whl_library_srcs( + name = "foo-1.0-py3-none-any.whl", + action_install = True, + sdist_filename = "foo-1.0.tar.gz", + extracted_files = [ + "bin/bin_tool", + "data/etc/cfg.txt", + "include/foo/foo.h", + "site-packages/foo-1.0.dist-info/METADATA", + "site-packages/foo/__init__.py", + ], + has_entry_points_txt = True, + namespace_package_files = ["site-packages/foo/__init__.py"], + shebang_scripts = ["shebang_tool"], + srcs_exclude = ["foo/exclude.py"], + data_exclude = ["foo/exclude.dat"], + copy_files = {"@ext//:file_src": "file_dest"}, + copy_executables = {"@ext//:exec_src": "exec_dest"}, + entry_points = { + "ep_cli": { + "group": "console_scripts", + "module": "foo.cli", + "name": "ep_cli", + "object": "main", + }, + }, + tags = ["pypi_name=foo", "pypi_version=1.0"], + native = struct( + filegroup = lambda **kwargs: filegroup_calls.append(kwargs), + glob = lambda *args, **kwargs: env.fail("glob should not be called when action_install=True"), + ), + rules = struct( + copy_file = lambda **kwargs: copy_calls.append(kwargs), + venv_entry_point = lambda **kwargs: entry_point_calls.append(kwargs), + py_wheel_library = lambda **kwargs: py_wheel_library_calls.append(kwargs), + ), + ) + + env.expect.that_int(len(entry_point_calls)).equals(1) + env.expect.that_int(len(copy_calls)).equals(2) + env.expect.that_collection(filegroup_calls).contains_exactly([ + { + "name": "whl_file", + "srcs": ["foo-1.0-py3-none-any.whl"], + "visibility": ["//visibility:public"], + }, + { + "name": "extracted_whl_files", + "srcs": ["srcs"], + "visibility": ["//visibility:public"], + }, + { + "name": "dist_info", + "srcs": ["entry_points.txt"], + "visibility": ["//visibility:public"], + }, + { + "name": "data", + "srcs": ["srcs", "bin/ep_cli"], + "visibility": ["//visibility:public"], + }, + ]) + env.expect.that_int(len(py_wheel_library_calls)).equals(1) + call = py_wheel_library_calls[0] + env.expect.that_str(call["name"]).equals("srcs") + env.expect.that_str(call["wheel"]).equals("foo-1.0-py3-none-any.whl") + env.expect.that_collection(call["extracted_files"]).contains_exactly([ + "bin/bin_tool", + "data/etc/cfg.txt", + "include/foo/foo.h", + "site-packages/foo-1.0.dist-info/METADATA", + "site-packages/foo/__init__.py", + ]) + env.expect.that_collection(call["namespace_package_files"]).contains_exactly([ + "site-packages/foo/__init__.py", + ]) + env.expect.that_collection(call["shebang_scripts"]).contains_exactly(["shebang_tool"]) + env.expect.that_collection(call["srcs_exclude"]).contains_exactly(["foo/exclude.py"]) + env.expect.that_collection(call["data_exclude"]).contains_exactly(["foo/exclude.dat"]) + env.expect.that_collection(call["data"]).contains_exactly([ + "bin/ep_cli", + "file_dest", + "exec_dest", + ]) + + ext_filegroup_calls = [] + ext_py_wheel_library_calls = [] + whl_library_srcs( + name = "foo-1.0-py3-none-any.whl", + whl_file = "@foo_whl//:foo-1.0-py3-none-any.whl", + action_install = True, + native = struct( + filegroup = lambda **kwargs: ext_filegroup_calls.append(kwargs), + glob = lambda *args, **kwargs: env.fail("glob should not be called when action_install=True"), + ), + rules = struct( + py_wheel_library = lambda **kwargs: ext_py_wheel_library_calls.append(kwargs), + ), + ) + ext_whl_fg = [c for c in ext_filegroup_calls if c["name"] == "whl_file"][0] + env.expect.that_collection(ext_whl_fg["srcs"]).contains_exactly([ + "@foo_whl//:foo-1.0-py3-none-any.whl", + ]) + ext_dist_info_fg = [c for c in ext_filegroup_calls if c["name"] == "dist_info"][0] + env.expect.that_collection(ext_dist_info_fg["srcs"]).contains_exactly([]) + env.expect.that_str(ext_py_wheel_library_calls[0]["wheel"]).equals( + "@foo_whl//:foo-1.0-py3-none-any.whl", + ) + +_tests.append(_test_action_install) + +def _test_action_install_fails_on_custom_filegroups(env): + errors = [] + whl_library_srcs( + name = "foo-1.0-py3-none-any.whl", + action_install = True, + filegroups = {"custom_fg": {"include": ["site-packages/**"]}}, + _fail = errors.append, + ) + env.expect.that_int(len(errors)).equals(1) + env.expect.that_str(errors[0]).contains("custom glob-based 'filegroups'") + env.expect.that_str(errors[0]).contains("custom_fg") + +_tests.append(_test_action_install_fails_on_custom_filegroups) + +def _test_action_install_fails_on_wheel_copy_files(env): + errors = [] + whl_library_srcs( + name = "foo-1.0-py3-none-any.whl", + action_install = True, + extracted_files = ["site-packages/foo/__init__.py"], + shebang_scripts = ["shebang_tool"], + copy_files = {"site-packages/foo/__init__.py": "copied.py"}, + copy_executables = {"bin/shebang_tool": "copied_tool"}, + _fail = errors.append, + ) + env.expect.that_int(len(errors)).equals(1) + env.expect.that_str(errors[0]).contains("reference wheel-extracted paths") + env.expect.that_str(errors[0]).contains("bin/shebang_tool") + env.expect.that_str(errors[0]).contains("site-packages/foo/__init__.py") + +_tests.append(_test_action_install_fails_on_wheel_copy_files) + def whl_library_srcs_test_suite(name): """create the test suite. diff --git a/tests/support/py_reconfig.bzl b/tests/support/py_reconfig.bzl index 64a4e14ddd..82a53b3fec 100644 --- a/tests/support/py_reconfig.bzl +++ b/tests/support/py_reconfig.bzl @@ -49,6 +49,10 @@ def _perform_transition_impl(input_settings, attr, base_impl): settings[labels.VENVS_USE_DECLARE_SYMLINK] = attr.venvs_use_declare_symlink if attr.venvs_site_packages: settings[labels.VENVS_SITE_PACKAGES] = attr.venvs_site_packages + if attr.precompile_flag: + settings[labels.PRECOMPILE] = attr.precompile_flag + if attr.precompile_source_retention_flag: + settings[labels.PRECOMPILE_SOURCE_RETENTION] = attr.precompile_source_retention_flag return settings _BUILTIN_BUILD_PYTHON_ZIP = [] if config.bazel_10_or_later else [ @@ -62,6 +66,8 @@ _RECONFIG_INPUTS = [ "//command_line_option:stamp", CUSTOM_RUNTIME, labels.BOOTSTRAP_IMPL, + labels.PRECOMPILE, + labels.PRECOMPILE_SOURCE_RETENTION, labels.PYTHON_SRC, labels.REPL_DEP, labels.VENVS_SITE_PACKAGES, @@ -89,6 +95,8 @@ to make the RBE presubmits happy, which disable auto-detection of a CC toolchain. """, ), + "precompile_flag": attrb.String(), + "precompile_source_retention_flag": attrb.String(), "python_src": attrb.Label(), "repl_dep": attrb.Label(), "venvs_site_packages": attrb.String(), diff --git a/tests/venv_site_packages_libs/app_files_building/app_files_building_tests.bzl b/tests/venv_site_packages_libs/app_files_building/app_files_building_tests.bzl index 4754e75e5d..cf1d8faff6 100644 --- a/tests/venv_site_packages_libs/app_files_building/app_files_building_tests.bzl +++ b/tests/venv_site_packages_libs/app_files_building/app_files_building_tests.bzl @@ -595,6 +595,8 @@ def _test_optimized_grouping_pkgutil_whls(name): impl = _test_optimized_grouping_pkgutil_whls_impl, target = name + "_lib", config_settings = { + labels.PRECOMPILE: "disabled", + labels.PRECOMPILE_SOURCE_RETENTION: "keep_source", labels.VENVS_SITE_PACKAGES: "yes", }, attr_values = dict( @@ -609,6 +611,39 @@ def _test_optimized_grouping_pkgutil_whls_impl(env, target): actual_raw_entries = target[PyInfo].venv_symlinks.to_list() actual = _venv_symlinks_from_entries(actual_raw_entries) + is_action_install = False + for entry in actual_raw_entries: + for f in entry.files.to_list(): + if f.is_directory: + is_action_install = True + break + if is_action_install: + break + sp_prefix = "srcs/site-packages" if is_action_install else "site-packages" + if is_action_install: + ns1_init_files = ["../+internal_dev_deps+pkgutil_nspkg1/srcs"] + ns1_one_files = ns1_init_files + ns1_dist_files = ns1_init_files + ns2_init_files = ["../+internal_dev_deps+pkgutil_nspkg2/srcs"] + ns2_two_files = ns2_init_files + ns2_dist_files = ns2_init_files + else: + ns1_init_files = ["../+internal_dev_deps+pkgutil_nspkg1/site-packages/nspkg/__init__.py"] + ns1_one_files = ["../+internal_dev_deps+pkgutil_nspkg1/site-packages/nspkg/one/a.txt"] + ns1_dist_files = [ + "../+internal_dev_deps+pkgutil_nspkg1/site-packages/pkgutil_nspkg1-1.0.dist-info/INSTALLER", + "../+internal_dev_deps+pkgutil_nspkg1/site-packages/pkgutil_nspkg1-1.0.dist-info/METADATA", + "../+internal_dev_deps+pkgutil_nspkg1/site-packages/pkgutil_nspkg1-1.0.dist-info/RECORD", + "../+internal_dev_deps+pkgutil_nspkg1/site-packages/pkgutil_nspkg1-1.0.dist-info/WHEEL", + ] + ns2_init_files = ["../+internal_dev_deps+pkgutil_nspkg2/site-packages/nspkg/__init__.py"] + ns2_two_files = ["../+internal_dev_deps+pkgutil_nspkg2/site-packages/nspkg/two/b.txt"] + ns2_dist_files = [ + "../+internal_dev_deps+pkgutil_nspkg2/site-packages/pkgutil_nspkg2-1.0.dist-info/INSTALLER", + "../+internal_dev_deps+pkgutil_nspkg2/site-packages/pkgutil_nspkg2-1.0.dist-info/METADATA", + "../+internal_dev_deps+pkgutil_nspkg2/site-packages/pkgutil_nspkg2-1.0.dist-info/RECORD", + "../+internal_dev_deps+pkgutil_nspkg2/site-packages/pkgutil_nspkg2-1.0.dist-info/WHEEL", + ] # The important condition is that the top-level 'nspkg' directory # is NOT linked because it's a pkgutil namespace package. @@ -616,52 +651,34 @@ def _test_optimized_grouping_pkgutil_whls_impl(env, target): # Entries from pkgutil_ns1 _venv_symlink( "nspkg/__init__.py", - link_to_path = "+internal_dev_deps+pkgutil_nspkg1/site-packages/nspkg/__init__.py", - files = [ - "../+internal_dev_deps+pkgutil_nspkg1/site-packages/nspkg/__init__.py", - ], + link_to_path = "+internal_dev_deps+pkgutil_nspkg1/" + sp_prefix + "/nspkg/__init__.py", + files = ns1_init_files, ), _venv_symlink( "nspkg/one", - link_to_path = "+internal_dev_deps+pkgutil_nspkg1/site-packages/nspkg/one", - files = [ - "../+internal_dev_deps+pkgutil_nspkg1/site-packages/nspkg/one/a.txt", - ], + link_to_path = "+internal_dev_deps+pkgutil_nspkg1/" + sp_prefix + "/nspkg/one", + files = ns1_one_files, ), _venv_symlink( "pkgutil_nspkg1-1.0.dist-info", - link_to_path = "+internal_dev_deps+pkgutil_nspkg1/site-packages/pkgutil_nspkg1-1.0.dist-info", - files = [ - "../+internal_dev_deps+pkgutil_nspkg1/site-packages/pkgutil_nspkg1-1.0.dist-info/INSTALLER", - "../+internal_dev_deps+pkgutil_nspkg1/site-packages/pkgutil_nspkg1-1.0.dist-info/METADATA", - "../+internal_dev_deps+pkgutil_nspkg1/site-packages/pkgutil_nspkg1-1.0.dist-info/RECORD", - "../+internal_dev_deps+pkgutil_nspkg1/site-packages/pkgutil_nspkg1-1.0.dist-info/WHEEL", - ], + link_to_path = "+internal_dev_deps+pkgutil_nspkg1/" + sp_prefix + "/pkgutil_nspkg1-1.0.dist-info", + files = ns1_dist_files, ), # Entries from pkgutil_ns2 _venv_symlink( "nspkg/__init__.py", - link_to_path = "+internal_dev_deps+pkgutil_nspkg2/site-packages/nspkg/__init__.py", - files = [ - "../+internal_dev_deps+pkgutil_nspkg2/site-packages/nspkg/__init__.py", - ], + link_to_path = "+internal_dev_deps+pkgutil_nspkg2/" + sp_prefix + "/nspkg/__init__.py", + files = ns2_init_files, ), _venv_symlink( "nspkg/two", - link_to_path = "+internal_dev_deps+pkgutil_nspkg2/site-packages/nspkg/two", - files = [ - "../+internal_dev_deps+pkgutil_nspkg2/site-packages/nspkg/two/b.txt", - ], + link_to_path = "+internal_dev_deps+pkgutil_nspkg2/" + sp_prefix + "/nspkg/two", + files = ns2_two_files, ), _venv_symlink( "pkgutil_nspkg2-1.0.dist-info", - link_to_path = "+internal_dev_deps+pkgutil_nspkg2/site-packages/pkgutil_nspkg2-1.0.dist-info", - files = [ - "../+internal_dev_deps+pkgutil_nspkg2/site-packages/pkgutil_nspkg2-1.0.dist-info/INSTALLER", - "../+internal_dev_deps+pkgutil_nspkg2/site-packages/pkgutil_nspkg2-1.0.dist-info/METADATA", - "../+internal_dev_deps+pkgutil_nspkg2/site-packages/pkgutil_nspkg2-1.0.dist-info/RECORD", - "../+internal_dev_deps+pkgutil_nspkg2/site-packages/pkgutil_nspkg2-1.0.dist-info/WHEEL", - ], + link_to_path = "+internal_dev_deps+pkgutil_nspkg2/" + sp_prefix + "/pkgutil_nspkg2-1.0.dist-info", + files = ns2_dist_files, ), ]) @@ -671,20 +688,26 @@ def _test_optimized_grouping_pkgutil_whls_impl(env, target): env.expect.that_collection(_venv_symlinks_from_entries(conflicts[0])).contains_exactly([ _venv_symlink( "nspkg/__init__.py", - link_to_path = "+internal_dev_deps+pkgutil_nspkg1/site-packages/nspkg/__init__.py", - files = [ - "../+internal_dev_deps+pkgutil_nspkg1/site-packages/nspkg/__init__.py", - ], + link_to_path = "+internal_dev_deps+pkgutil_nspkg1/" + sp_prefix + "/nspkg/__init__.py", + files = ns1_init_files, ), _venv_symlink( "nspkg/__init__.py", - link_to_path = "+internal_dev_deps+pkgutil_nspkg2/site-packages/nspkg/__init__.py", - files = [ - "../+internal_dev_deps+pkgutil_nspkg2/site-packages/nspkg/__init__.py", - ], + link_to_path = "+internal_dev_deps+pkgutil_nspkg2/" + sp_prefix + "/nspkg/__init__.py", + files = ns2_init_files, ), ]) env.expect.that_collection(conflicts).has_size(1) + if is_action_install: + by_venv_path = { + e.venv_path: e.link_to_subpaths.to_list() + for e in actual_raw_entries + if e.venv_path in ("nspkg/one", "nspkg/two") + } + env.expect.that_dict(by_venv_path).contains_exactly({ + "nspkg/one": ["a.txt"], + "nspkg/two": ["b.txt"], + }) def _test_package_version_filtering(name): analysis_test( diff --git a/tests/venv_site_packages_libs/tree_conflicts/BUILD.bazel b/tests/venv_site_packages_libs/tree_conflicts/BUILD.bazel new file mode 100644 index 0000000000..1f0f9aee89 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/BUILD.bazel @@ -0,0 +1,88 @@ +load("//python:py_library.bzl", "py_library") +load("//tests/support:py_reconfig.bzl", "py_reconfig_test") +load("//tests/support:support.bzl", "SUPPORTS_BZLMOD") + +_BOOTSTRAP_IMPL = select({ + "@platforms//os:windows": "system_python", + "//conditions:default": "script", +}) + +py_library( + name = "fp", + srcs = glob(["fp/site-packages/**/*.py"]), + experimental_venvs_site_packages = "//python/config_settings:venvs_site_packages", + imports = ["fp/site-packages"], + precompile_source_retention = "keep_source", +) + +py_library( + name = "fp2", + srcs = glob(["fp2/site-packages/**/*.py"]), + experimental_venvs_site_packages = "//python/config_settings:venvs_site_packages", + imports = ["fp2/site-packages"], + precompile_source_retention = "keep_source", +) + +# Stored in constants so buildifier does not sort `deps` alphabetically, +# preserving the dependency-order conflict precedence under test. +_DEPS_AB = [ + "@tree_conflict_a//:pkg", + "@tree_conflict_b//:pkg", + ":fp", + ":fp2", +] + +_DEPS_BA = [ + ":fp2", + ":fp", + "@tree_conflict_b//:pkg", + "@tree_conflict_a//:pkg", +] + +py_reconfig_test( + name = "tree_conflicts_test_ab", + srcs = ["tree_conflicts_test.py"], + bootstrap_impl = _BOOTSTRAP_IMPL, + env = {"EXPECTED_ORDER": "ab"}, + main = "tree_conflicts_test.py", + precompile_source_retention = "keep_source", + precompile_source_retention_flag = "keep_source", + target_compatible_with = SUPPORTS_BZLMOD, + venvs_site_packages = "yes", + deps = _DEPS_AB, +) + +py_reconfig_test( + name = "tree_conflicts_test_ba", + srcs = ["tree_conflicts_test.py"], + bootstrap_impl = _BOOTSTRAP_IMPL, + env = {"EXPECTED_ORDER": "ba"}, + main = "tree_conflicts_test.py", + precompile_source_retention = "keep_source", + precompile_source_retention_flag = "keep_source", + target_compatible_with = SUPPORTS_BZLMOD, + venvs_site_packages = "yes", + deps = _DEPS_BA, +) + +py_reconfig_test( + name = "tree_conflicts_test_ab_precompile_enabled", + srcs = ["tree_conflicts_test.py"], + bootstrap_impl = _BOOTSTRAP_IMPL, + env = { + "EXPECTED_ORDER": "ab", + "EXPECTED_PRECOMPILE": "enabled", + }, + main = "tree_conflicts_test.py", + precompile_flag = "enabled", + precompile_source_retention = "keep_source", + precompile_source_retention_flag = "keep_source", + target_compatible_with = SUPPORTS_BZLMOD, + venvs_site_packages = "yes", + deps = [ + ":fp", + ":fp2", + "@tree_conflict_a//:pkg", + "@tree_conflict_b//:pkg", + ], +) diff --git a/tests/venv_site_packages_libs/tree_conflicts/fp/site-packages/foo/plugins/c.py b/tests/venv_site_packages_libs/tree_conflicts/fp/site-packages/foo/plugins/c.py new file mode 100644 index 0000000000..c248ad11a4 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/fp/site-packages/foo/plugins/c.py @@ -0,0 +1 @@ +WHO = "c" diff --git a/tests/venv_site_packages_libs/tree_conflicts/fp/site-packages/gns/gamma/__init__.py b/tests/venv_site_packages_libs/tree_conflicts/fp/site-packages/gns/gamma/__init__.py new file mode 100644 index 0000000000..3d34ce9af8 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/fp/site-packages/gns/gamma/__init__.py @@ -0,0 +1 @@ +WHO = "gamma" diff --git a/tests/venv_site_packages_libs/tree_conflicts/fp/site-packages/pk/z.py b/tests/venv_site_packages_libs/tree_conflicts/fp/site-packages/pk/z.py new file mode 100644 index 0000000000..772f6dd197 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/fp/site-packages/pk/z.py @@ -0,0 +1 @@ +WHO = "z" diff --git a/tests/venv_site_packages_libs/tree_conflicts/fp2/site-packages/bar/__init__.py b/tests/venv_site_packages_libs/tree_conflicts/fp2/site-packages/bar/__init__.py new file mode 100644 index 0000000000..1c25fe7c3a --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/fp2/site-packages/bar/__init__.py @@ -0,0 +1 @@ +WHO = "bar-fp2" diff --git a/tests/venv_site_packages_libs/tree_conflicts/fp2/site-packages/bar/m.py b/tests/venv_site_packages_libs/tree_conflicts/fp2/site-packages/bar/m.py new file mode 100644 index 0000000000..deb8c2d905 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/fp2/site-packages/bar/m.py @@ -0,0 +1 @@ +WHO = "m" diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/bar/ext/e.py b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/bar/ext/e.py new file mode 100644 index 0000000000..8024a01eff --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/bar/ext/e.py @@ -0,0 +1 @@ +WHO = "e" diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/foo/__init__.py b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/foo/__init__.py new file mode 100644 index 0000000000..f7efbf5d9e --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/foo/__init__.py @@ -0,0 +1 @@ +WHO = "foo-from-a" diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/foo/a.py b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/foo/a.py new file mode 100644 index 0000000000..8f0a8619d0 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/foo/a.py @@ -0,0 +1 @@ +WHO = "a" diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/foo/plugins/shared.py b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/foo/plugins/shared.py new file mode 100644 index 0000000000..6487b3e2df --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/foo/plugins/shared.py @@ -0,0 +1 @@ +WHO = "A" diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/gns/alpha/__init__.py b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/gns/alpha/__init__.py new file mode 100644 index 0000000000..2e8d96bc0b --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/gns/alpha/__init__.py @@ -0,0 +1 @@ +WHO = "alpha" diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/gns/libs/libdummy_a.so b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/gns/libs/libdummy_a.so new file mode 100644 index 0000000000..c7ab248d0f --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/gns/libs/libdummy_a.so @@ -0,0 +1 @@ +not elf diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/pk/__init__.py b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/pk/__init__.py new file mode 100644 index 0000000000..65f42f54de --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/pk/__init__.py @@ -0,0 +1,2 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) +ORIGIN = "A" diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/pk/x.py b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/pk/x.py new file mode 100644 index 0000000000..fb1863ef16 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/pk/x.py @@ -0,0 +1 @@ +WHO = "x" diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.data/scripts/tc_a_only b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.data/scripts/tc_a_only new file mode 100644 index 0000000000..400af6918a --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.data/scripts/tc_a_only @@ -0,0 +1,2 @@ +#!python +print("a-only") diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.data/scripts/tc_tool b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.data/scripts/tc_tool new file mode 100644 index 0000000000..cc02f5af3e --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.data/scripts/tc_tool @@ -0,0 +1,2 @@ +#!python +print("tool-A") diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.dist-info/METADATA b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.dist-info/METADATA new file mode 100644 index 0000000000..3aee6ba549 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.dist-info/METADATA @@ -0,0 +1,3 @@ +Metadata-Version: 2.1 +Name: tree-conflict-a +Version: 1.0 diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.dist-info/RECORD b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.dist-info/RECORD new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.dist-info/WHEEL b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.dist-info/WHEEL new file mode 100644 index 0000000000..874bfdf932 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wa/tree_conflict_a-1.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: test +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/foo/plugins/b.py b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/foo/plugins/b.py new file mode 100644 index 0000000000..ddb4b7c1da --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/foo/plugins/b.py @@ -0,0 +1 @@ +WHO = "b" diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/foo/plugins/shared.py b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/foo/plugins/shared.py new file mode 100644 index 0000000000..d0c42e71dd --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/foo/plugins/shared.py @@ -0,0 +1 @@ +WHO = "B" diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/gns/beta/__init__.py b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/gns/beta/__init__.py new file mode 100644 index 0000000000..355d8ed278 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/gns/beta/__init__.py @@ -0,0 +1 @@ +WHO = "beta" diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/gns/libs/helper.py b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/gns/libs/helper.py new file mode 100644 index 0000000000..ac2c7d8430 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/gns/libs/helper.py @@ -0,0 +1 @@ +WHO = "helper" diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/gns/libs/libdummy_b.so b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/gns/libs/libdummy_b.so new file mode 100644 index 0000000000..c7ab248d0f --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/gns/libs/libdummy_b.so @@ -0,0 +1 @@ +not elf diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/pk/__init__.py b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/pk/__init__.py new file mode 100644 index 0000000000..54826a8b26 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/pk/__init__.py @@ -0,0 +1,2 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) +ORIGIN = "B" diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/pk/y.py b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/pk/y.py new file mode 100644 index 0000000000..7490433a2a --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/pk/y.py @@ -0,0 +1 @@ +WHO = "y" diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.data/scripts/tc_b_only b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.data/scripts/tc_b_only new file mode 100644 index 0000000000..cf18993128 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.data/scripts/tc_b_only @@ -0,0 +1,2 @@ +#!python +print("b-only") diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.data/scripts/tc_tool b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.data/scripts/tc_tool new file mode 100644 index 0000000000..0a29fae50f --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.data/scripts/tc_tool @@ -0,0 +1,2 @@ +#!python +print("tool-B") diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.dist-info/METADATA b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.dist-info/METADATA new file mode 100644 index 0000000000..a530912a83 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.dist-info/METADATA @@ -0,0 +1,3 @@ +Metadata-Version: 2.1 +Name: tree-conflict-b +Version: 1.0 diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.dist-info/RECORD b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.dist-info/RECORD new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.dist-info/WHEEL b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.dist-info/WHEEL new file mode 100644 index 0000000000..874bfdf932 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/testdata/wb/tree_conflict_b-1.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: test +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/tests/venv_site_packages_libs/tree_conflicts/tree_conflicts_test.py b/tests/venv_site_packages_libs/tree_conflicts/tree_conflicts_test.py new file mode 100644 index 0000000000..281a793ed6 --- /dev/null +++ b/tests/venv_site_packages_libs/tree_conflicts/tree_conflicts_test.py @@ -0,0 +1,152 @@ +from __future__ import annotations + +import importlib +import importlib.metadata +import os +import subprocess +import sys +import unittest +from pathlib import Path + + +class TreeConflictsTest(unittest.TestCase): + def setUp(self) -> None: + super().setUp() + self.assertNotEqual( + sys.prefix, sys.base_prefix, "Expected to run inside a venv" + ) + self.venv = Path(sys.prefix) + self.order = os.environ["EXPECTED_ORDER"] + self.precompile = os.environ.get("EXPECTED_PRECOMPILE", "") + + def _get_script_path(self, name: str) -> Path: + if sys.platform != "win32": + return self.venv / "bin" / name + bin_dir = self.venv / "Scripts" + pathexts = os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(";") + for ext in [""] + [e.lower() for e in pathexts]: + candidate = bin_dir / f"{name}{ext}" + if candidate.exists(): + return candidate + return bin_dir / name + + def _assert_in_venv(self, mod_file: str | None, mod_name: str) -> Path: + self.assertIsNotNone(mod_file, f"Expected __file__ on {mod_name}") + assert mod_file is not None # type assert + actual = str(Path(mod_file)).lower() if os.name == "nt" else mod_file + prefix = str(self.venv).lower() if os.name == "nt" else str(self.venv) + self.assertTrue( + actual.startswith(prefix), + f"{mod_name} ({mod_file}) was not loaded from venv ({self.venv})", + ) + return Path(mod_file) + + def test_merged_packages_and_conflict_priority(self) -> None: + foo = importlib.import_module("foo") + foo_a = importlib.import_module("foo.a") + foo_b = importlib.import_module("foo.plugins.b") + foo_c = importlib.import_module("foo.plugins.c") + foo_shared = importlib.import_module("foo.plugins.shared") + gns_alpha = importlib.import_module("gns.alpha") + gns_beta = importlib.import_module("gns.beta") + gns_gamma = importlib.import_module("gns.gamma") + gns_helper = importlib.import_module("gns.libs.helper") + pk = importlib.import_module("pk") + pk_x = importlib.import_module("pk.x") + pk_y = importlib.import_module("pk.y") + pk_z = importlib.import_module("pk.z") + bar = importlib.import_module("bar") + bar_m = importlib.import_module("bar.m") + bar_e = importlib.import_module("bar.ext.e") + + self.assertEqual(foo.WHO, "foo-from-a") + self.assertEqual(foo_a.WHO, "a") + self.assertEqual(foo_b.WHO, "b") + self.assertEqual(foo_c.WHO, "c") + # Shortest venv_path ("foo" vs "foo/plugins") expands first regardless of dep order. + self.assertEqual(foo_shared.WHO, "A") + + self.assertEqual(gns_alpha.WHO, "alpha") + self.assertEqual(gns_beta.WHO, "beta") + self.assertEqual(gns_gamma.WHO, "gamma") + self.assertEqual(gns_helper.WHO, "helper") + + # Equal venv_path ("pk/__init__.py"): first in dep order wins. + expected_pk_origin = "A" if self.order == "ab" else "B" + self.assertEqual(pk.ORIGIN, expected_pk_origin) + self.assertEqual(pk_x.WHO, "x") + self.assertEqual(pk_y.WHO, "y") + self.assertEqual(pk_z.WHO, "z") + + self.assertEqual(bar.WHO, "bar-fp2") + self.assertEqual(bar_m.WHO, "m") + self.assertEqual(bar_e.WHO, "e") + + for mod in ( + foo, + foo_a, + foo_b, + foo_c, + foo_shared, + gns_alpha, + gns_beta, + gns_gamma, + gns_helper, + pk, + pk_x, + pk_y, + pk_z, + bar, + bar_m, + bar_e, + ): + self._assert_in_venv(mod.__file__, mod.__name__) + + libs_dir = self._assert_in_venv(gns_helper.__file__, gns_helper.__name__).parent + self.assertFalse( + libs_dir.is_symlink(), "gns/libs must be a real merged directory" + ) + libs_entries = set(os.listdir(libs_dir)) + self.assertIn("libdummy_a.so", libs_entries) + self.assertIn("libdummy_b.so", libs_entries) + self.assertTrue( + "helper.py" in libs_entries or "helper.pyc" in libs_entries, + f"Expected helper module in {libs_entries}", + ) + + self.assertEqual(importlib.metadata.version("tree-conflict-a"), "1.0") + self.assertEqual(importlib.metadata.version("tree-conflict-b"), "1.0") + + if self.precompile == "enabled": + foo_dir = self._assert_in_venv(foo.__file__, foo.__name__).parent + has_pyc = (foo_dir / "a.pyc").exists() or ( + (foo_dir / "__pycache__").is_dir() + and any( + name.startswith("a.") and name.endswith(".pyc") + for name in os.listdir(foo_dir / "__pycache__") + ) + ) + self.assertTrue( + has_pyc, f"Expected precompiled bytecode for foo.a in {foo_dir}" + ) + + def test_bin_scripts_and_conflict_priority(self) -> None: + expected_tool = "tool-A" if self.order == "ab" else "tool-B" + for script_name, expected_stdout in ( + ("tc_tool", expected_tool), + ("tc_a_only", "a-only"), + ("tc_b_only", "b-only"), + ): + script_path = self._get_script_path(script_name) + self.assertTrue(script_path.exists(), f"Missing script {script_path}") + proc = subprocess.run( + [str(script_path)], + capture_output=True, + text=True, + check=True, + ) + self.assertEqual(proc.stdout.strip(), expected_stdout) + + +if __name__ == "__main__": + unittest.main() From 929414cc15bada3e77a6bb1add1258a2b0f361b4 Mon Sep 17 00:00:00 2001 From: Jeremy Volkman Date: Mon, 26 Oct 2026 00:48:50 +0000 Subject: [PATCH 2/9] feat(pypi): add PyInstalledWheelInfo, py_wheel_headers, py_wheel_transform, and post_install_patches --- python/BUILD.bazel | 3 + python/pip.bzl | 13 + python/private/pypi/BUILD.bazel | 60 ++ python/private/pypi/action_whl_installer.py | 302 ++++++++-- python/private/pypi/attrs.bzl | 11 +- python/private/pypi/extension.bzl | 14 +- .../pypi/generate_whl_library_build_bazel.bzl | 58 +- python/private/pypi/package_annotation.bzl | 7 + python/private/pypi/patch_and_extract_whl.bzl | 13 +- .../private/pypi/py_installed_wheel_info.bzl | 36 ++ .../private/pypi/py_wheel_extract_files.bzl | 516 ++++++++++++++++++ python/private/pypi/py_wheel_headers.bzl | 56 ++ python/private/pypi/py_wheel_library.bzl | 181 +++++- python/private/pypi/py_wheel_transform.bzl | 94 ++++ python/private/pypi/wheel_files_extractor.py | 141 +++++ python/private/pypi/wheel_layout.py | 297 ++++++++++ python/private/pypi/wheel_transformer.py | 87 +++ python/private/pypi/whl_library_srcs.bzl | 229 ++++++-- ...generate_whl_library_build_bazel_tests.bzl | 77 ++- tests/pypi/py_wheel_library/BUILD.bazel | 312 +++++++++++ tests/pypi/py_wheel_library/headers_test.cc | 6 + .../pypi/py_wheel_library/make_test_wheel.py | 57 ++ tests/pypi/py_wheel_library/marker.txt | 1 + .../pypi/py_wheel_library/post_install.patch | 6 + .../py_wheel_library/py_wheel_library_test.py | 78 +++ tests/pypi/py_wheel_library/sh_transform.sh | 20 + .../py_wheel_library/spoke_pkg/BUILD.bazel | 35 ++ .../spoke_pkg/wheel_files.bzl | 30 + .../pypi/py_wheel_library/transform_wheel.py | 28 + .../wheel_layout_and_installer_test.py | 308 +++++++++++ .../whl_library_srcs_tests.bzl | 292 +++++++++- .../app_files_building_tests.bzl | 6 +- 32 files changed, 3227 insertions(+), 147 deletions(-) create mode 100644 python/private/pypi/py_installed_wheel_info.bzl create mode 100644 python/private/pypi/py_wheel_extract_files.bzl create mode 100644 python/private/pypi/py_wheel_headers.bzl create mode 100644 python/private/pypi/py_wheel_transform.bzl create mode 100644 python/private/pypi/wheel_files_extractor.py create mode 100644 python/private/pypi/wheel_transformer.py create mode 100644 tests/pypi/py_wheel_library/headers_test.cc create mode 100644 tests/pypi/py_wheel_library/make_test_wheel.py create mode 100644 tests/pypi/py_wheel_library/marker.txt create mode 100644 tests/pypi/py_wheel_library/post_install.patch create mode 100644 tests/pypi/py_wheel_library/py_wheel_library_test.py create mode 100755 tests/pypi/py_wheel_library/sh_transform.sh create mode 100644 tests/pypi/py_wheel_library/spoke_pkg/BUILD.bazel create mode 100644 tests/pypi/py_wheel_library/spoke_pkg/wheel_files.bzl create mode 100644 tests/pypi/py_wheel_library/transform_wheel.py diff --git a/python/BUILD.bazel b/python/BUILD.bazel index d447a467a3..8d4df4d6e0 100644 --- a/python/BUILD.bazel +++ b/python/BUILD.bazel @@ -231,6 +231,9 @@ bzl_library( "//python/private/pypi:package_annotation", "//python/private/pypi:pip_compile", "//python/private/pypi:pip_repository", + "//python/private/pypi:py_wheel_extract_files", + "//python/private/pypi:py_wheel_headers", + "//python/private/pypi:py_wheel_transform", "//python/private/pypi:whl_library_alias", "//python/private/whl_filegroup", ], diff --git a/python/pip.bzl b/python/pip.bzl index 44ee69d65b..da553993cc 100644 --- a/python/pip.bzl +++ b/python/pip.bzl @@ -28,12 +28,25 @@ load("//python/private/pypi:multi_pip_parse.bzl", _multi_pip_parse = "multi_pip_ load("//python/private/pypi:package_annotation.bzl", _package_annotation = "package_annotation") load("//python/private/pypi:pip_compile.bzl", "pip_compile") load("//python/private/pypi:pip_repository.bzl", "pip_repository") +load("//python/private/pypi:py_installed_wheel_info.bzl", _PyInstalledWheelInfo = "PyInstalledWheelInfo") +load( + "//python/private/pypi:py_wheel_extract_files.bzl", + _py_wheel_extract_files = "py_wheel_extract_files", + _wheel_glob = "wheel_glob", +) +load("//python/private/pypi:py_wheel_headers.bzl", _py_wheel_headers = "py_wheel_headers") +load("//python/private/pypi:py_wheel_transform.bzl", _py_wheel_transform = "py_wheel_transform") load("//python/private/pypi:whl_library_alias.bzl", _whl_library_alias = "whl_library_alias") load("//python/private/whl_filegroup:whl_filegroup.bzl", _whl_filegroup = "whl_filegroup") +PyInstalledWheelInfo = _PyInstalledWheelInfo compile_pip_requirements = pip_compile package_annotation = _package_annotation pip_parse = pip_repository +py_wheel_extract_files = _py_wheel_extract_files +py_wheel_headers = _py_wheel_headers +py_wheel_transform = _py_wheel_transform +wheel_glob = _wheel_glob whl_filegroup = _whl_filegroup # Extra utilities visible to rules_python users. diff --git a/python/private/pypi/BUILD.bazel b/python/private/pypi/BUILD.bazel index 9d51b388ec..f725fdfdf9 100644 --- a/python/private/pypi/BUILD.bazel +++ b/python/private/pypi/BUILD.bazel @@ -44,6 +44,20 @@ py_interpreter_program( visibility = ["//visibility:public"], ) +py_interpreter_program( + name = "wheel_transformer", + interpreter_args = ["-B"], + main = "wheel_transformer.py", + visibility = ["//visibility:private"], +) + +py_interpreter_program( + name = "wheel_files_extractor", + interpreter_args = ["-B"], + main = "wheel_files_extractor.py", + visibility = ["//visibility:public"], +) + py_library( name = "rewriters_lib", srcs = [ @@ -58,7 +72,9 @@ py_library( srcs = [ "action_whl_installer.py", "inspect_whl.py", + "wheel_files_extractor.py", "wheel_layout.py", + "wheel_transformer.py", ], data = ["namespace_pkg_tmpl.py"], imports = ["."], @@ -656,10 +672,52 @@ bzl_library( ], ) +bzl_library( + name = "py_installed_wheel_info", + srcs = ["py_installed_wheel_info.bzl"], +) + +bzl_library( + name = "py_wheel_headers", + srcs = ["py_wheel_headers.bzl"], + deps = [ + ":py_installed_wheel_info", + "@bazel_skylib//lib:paths", + "@rules_cc//cc/common", + ], +) + +bzl_library( + name = "py_wheel_extract_files", + srcs = ["py_wheel_extract_files.bzl"], + deps = [ + ":py_installed_wheel_info", + "//python/private:attr_builders", + "//python/private:common", + "//python/private:rule_builders", + "//python/private:toolchain_types", + "@bazel_skylib//lib:paths", + "@bazel_skylib//lib:types", + ], +) + +bzl_library( + name = "py_wheel_transform", + srcs = ["py_wheel_transform.bzl"], + deps = [ + "//python/private:attr_builders", + "//python/private:common", + "//python/private:py_internal", + "//python/private:rule_builders", + "//python/private:toolchain_types", + ], +) + bzl_library( name = "py_wheel_library", srcs = ["py_wheel_library.bzl"], deps = [ + ":py_installed_wheel_info", "//python/private:attr_builders", "//python/private:attributes", "//python/private:builders", @@ -686,10 +744,12 @@ bzl_library( ":gen_wheel_record", ":labels", ":namespace_pkgs", + ":py_wheel_extract_files", ":py_wheel_library", ":venv_entry_point", ":venv_rewrite_shebang", "//python:py_library", + "@bazel_skylib//lib:types", "@bazel_skylib//rules:copy_file", ], ) diff --git a/python/private/pypi/action_whl_installer.py b/python/private/pypi/action_whl_installer.py index 3247fa3997..3c421ee5fc 100644 --- a/python/private/pypi/action_whl_installer.py +++ b/python/private/pypi/action_whl_installer.py @@ -29,12 +29,14 @@ from venv_shebang_rewriter import rewrite_shebang_bytes from wheel_layout import ( INSTALLER_URL, + apply_unified_patch, create_namespace_inits, expected_data_dir_for_dist_info, find_wheel_dist_info_and_entry_points, glob_to_regex, is_excluded, plan_wheel_entries, + single_wheel_in, update_record_for_touched_files, ) from wheel_record_rewriter import rewrite_record_lines @@ -360,30 +362,63 @@ def _finalize_dist_info( f.write("".join(lines)) -def install_wheel( +def _install_from_existing_dir( + installed_dir: Path, + dest_dir: Path, + site_packages_dir: Path, + srcs_exclude_rx: list[re.Pattern[str]], + data_exclude_rx: list[re.Pattern[str]], +) -> tuple[str, set[str]]: + shutil.copytree(installed_dir, dest_dir, dirs_exist_ok=True) + for p in dest_dir.rglob("*"): + try: + os.chmod(p, os.stat(p).st_mode | 0o200) + except OSError: + pass + site_packages_dir.mkdir(parents=True, exist_ok=True) + dist_info_dirs = sorted( + d.name + for d in site_packages_dir.iterdir() + if d.is_dir() and d.name.endswith(".dist-info") + ) + dist_info_dir = dist_info_dirs[0] if dist_info_dirs else "" + touched_site_rel: set[str] = set() + + for p in sorted(dest_dir.rglob("*")): + if not p.is_file(): + continue + if "__pycache__" in p.parts and p.suffix == ".pyc": + if p.is_relative_to(site_packages_dir): + touched_site_rel.add(p.relative_to(site_packages_dir).as_posix()) + p.unlink() + if not any(p.parent.iterdir()): + p.parent.rmdir() + continue + + rel_dest = p.relative_to(dest_dir).as_posix() + rx = srcs_exclude_rx if p.suffix == ".py" else data_exclude_rx + if not is_excluded(rel_dest, rx): + continue + if p.is_relative_to(site_packages_dir): + touched_site_rel.add(p.relative_to(site_packages_dir).as_posix()) + p.unlink() + + return dist_info_dir, touched_site_rel + + +def _extract_from_wheel( wheel_path: Path, dest_dir: Path, + site_packages_dir: Path, *, - target_os: str = "unix", - srcs_exclude_globs: list[str] | None = None, - data_exclude_globs: list[str] | None = None, - create_namespace_inits_flag: bool = False, - precompile: bool = False, - pyc_tag: str = "", - precompile_invalidation_mode: str = "checked_hash", - precompile_optimize_level: int = 0, - precompile_source_retention: str = "keep_source", - python_version: str = "", - src_name_prefix: str = "", - precompiler_tool: Path | None = None, -) -> None: - """Extract and install `wheel_path` into `dest_dir`.""" - site_packages_dir = dest_dir / "site-packages" + target_os: str, + srcs_exclude_rx: list[re.Pattern[str]], + data_exclude_rx: list[re.Pattern[str]], +) -> str: + if wheel_path.is_dir(): + wheel_path = single_wheel_in(wheel_path) site_packages_dir.mkdir(parents=True, exist_ok=True) - srcs_exclude_rx = [glob_to_regex(g) for g in (srcs_exclude_globs or ())] - data_exclude_rx = [glob_to_regex(g) for g in (data_exclude_globs or ())] - rewritten_scripts: set[str] = set() used_data_dir = False @@ -428,31 +463,188 @@ def install_wheel( target_os=target_os, rewritten_scripts=rewritten_scripts, ) + return dist_info_dir - if create_namespace_inits_flag: - create_namespace_inits( - site_packages_dir, _NAMESPACE_PKG_TMPL_PATH.read_text(encoding="utf-8") - ) - if not precompile: +def _validate_installed_site_packages( + site_packages_dir: Path, + expected_site_paths: list[str], + *, + srcs_exclude_rx: list[re.Pattern[str]], + data_exclude_rx: list[re.Pattern[str]], + omit_py_source: bool, + validation_source: str, +) -> None: + norm_paths = sorted( + { + sp.strip("/") + for sp in expected_site_paths + if sp.strip("/") and not sp.strip("/").endswith(".dist-info") + } + ) + + def _site_path_present(sp: str) -> bool: + if (site_packages_dir / sp).exists(): + return True + if omit_py_source and sp.endswith(".py"): + return (site_packages_dir / f"{sp[:-3]}.pyc").exists() + return False + + def _is_covered(rel: str) -> bool: + if "__pycache__" in rel.split("/"): + return True + if any(rel == sp or rel.startswith(sp + "/") for sp in norm_paths): + return True + if omit_py_source and rel.endswith(".pyc"): + py_equiv = rel[:-4] + ".py" + return any( + py_equiv == sp or py_equiv.startswith(sp + "/") for sp in norm_paths + ) + return False + + missing = [ + sp + for sp in norm_paths + if not _site_path_present(sp) + and not is_excluded( + f"site-packages/{sp}", + srcs_exclude_rx if sp.endswith(".py") else data_exclude_rx, + ) + ] + uncovered: list[str] = [] + for p in sorted(site_packages_dir.rglob("*")): + if not p.is_file(): + continue + rel = p.relative_to(site_packages_dir).as_posix() + if not rel.partition("/")[0].endswith(".dist-info") and not _is_covered(rel): + uncovered.append(rel) + if not missing and not uncovered: return - pyc_touched = precompile_site_packages( - dest_dir, - site_packages_dir, - pyc_tag=pyc_tag, - invalidation_mode=precompile_invalidation_mode, - optimize_level=precompile_optimize_level, - source_retention=precompile_source_retention, - python_version=python_version, - src_name_prefix=src_name_prefix, - precompiler_tool=precompiler_tool, + missing_str = ( + repr(missing) + if len(missing) <= 5 + else f"{missing[:5]!r} (+{len(missing) - 5} more)" ) - if pyc_touched: + uncovered_str = ( + repr(uncovered) + if len(uncovered) <= 5 + else f"{uncovered[:5]!r} (+{len(uncovered) - 5} more)" + ) + if validation_source == "extracted_files": + raise ValueError( + "Installed site-packages entries do not match extracted_files " + f"in venv mode (missing={missing_str}, uncovered={uncovered_str}); " + "transform/patch changed top-level entries " + "(update extracted_files or set venvs_site_packages=no)" + ) + remedy = ( + "fix site_paths or set venvs_site_packages=no" + if norm_paths + else "set site_paths (or extracted_files) or set venvs_site_packages=no" + ) + raise ValueError( + "Installed site-packages entries do not match expected site_paths " + f"in venv mode (missing={missing_str}, uncovered={uncovered_str}); " + f"{remedy}" + ) + + +def install_wheel( + wheel_path: Path | None, + dest_dir: Path, + *, + installed_dir: Path | None = None, + target_os: str = "unix", + srcs_exclude_globs: list[str] | None = None, + data_exclude_globs: list[str] | None = None, + create_namespace_inits_flag: bool = False, + patches: list[Path] | None = None, + patch_strip: int = 0, + expected_site_paths: list[str] | None = None, + validation_source: str = "extracted_files", + precompile: bool = False, + pyc_tag: str = "", + precompile_invalidation_mode: str = "checked_hash", + precompile_optimize_level: int = 0, + precompile_source_retention: str = "keep_source", + python_version: str = "", + src_name_prefix: str = "", + precompiler_tool: Path | None = None, +) -> None: + """Extract and install `wheel_path` (`.whl` or `.whldir`) or `installed_dir` into `dest_dir`.""" + site_packages_dir = dest_dir / "site-packages" + srcs_exclude_rx = [glob_to_regex(g) for g in (srcs_exclude_globs or ())] + data_exclude_rx = [glob_to_regex(g) for g in (data_exclude_globs or ())] + + if installed_dir is not None: + dist_info_dir, touched_site_rel = _install_from_existing_dir( + installed_dir, + dest_dir, + site_packages_dir, + srcs_exclude_rx, + data_exclude_rx, + ) + else: + if wheel_path is None: + raise ValueError("Either wheel_path or installed_dir must be provided") + dist_info_dir = _extract_from_wheel( + wheel_path, + dest_dir, + site_packages_dir, + target_os=target_os, + srcs_exclude_rx=srcs_exclude_rx, + data_exclude_rx=data_exclude_rx, + ) + touched_site_rel = set() + + for patch_file in patches or (): + touched_site_rel.update( + apply_unified_patch( + site_packages_dir, + patch_file, + strip=patch_strip, + ) + ) + if touched_site_rel and dist_info_dir: update_record_for_touched_files( site_packages_dir, dist_info_dir, - pyc_touched, + touched_site_rel, + ) + + if create_namespace_inits_flag: + create_namespace_inits( + site_packages_dir, _NAMESPACE_PKG_TMPL_PATH.read_text(encoding="utf-8") + ) + + if precompile: + pyc_touched = precompile_site_packages( + dest_dir, + site_packages_dir, + pyc_tag=pyc_tag, + invalidation_mode=precompile_invalidation_mode, + optimize_level=precompile_optimize_level, + source_retention=precompile_source_retention, + python_version=python_version, + src_name_prefix=src_name_prefix, + precompiler_tool=precompiler_tool, + ) + if pyc_touched and dist_info_dir: + update_record_for_touched_files( + site_packages_dir, + dist_info_dir, + pyc_touched, + ) + + if expected_site_paths is not None: + _validate_installed_site_packages( + site_packages_dir, + expected_site_paths, + srcs_exclude_rx=srcs_exclude_rx, + data_exclude_rx=data_exclude_rx, + omit_py_source=precompile and precompile_source_retention == "omit_source", + validation_source=validation_source, ) @@ -461,7 +653,8 @@ def main(argv: Sequence[str] | None = None) -> None: description="Extract a wheel into a TreeArtifact directory.", fromfile_prefix_chars="@", ) - parser.add_argument("--wheel", type=Path, required=True) + parser.add_argument("--wheel", type=Path, default=None) + parser.add_argument("--installed-dir", type=Path, default=None) parser.add_argument("--directory", type=Path, required=True) parser.add_argument( "--target-os", @@ -485,6 +678,34 @@ def main(argv: Sequence[str] | None = None) -> None: action="store_true", default=False, ) + parser.add_argument( + "--patch", + action="append", + dest="patches", + type=Path, + default=[], + ) + parser.add_argument( + "--patch-strip", + type=int, + default=0, + ) + parser.add_argument( + "--validate-site-packages", + action="store_true", + default=False, + ) + parser.add_argument( + "--validation-source", + choices=["extracted_files", "site_paths"], + default="extracted_files", + ) + parser.add_argument( + "--expected-site-path", + action="append", + dest="expected_site_paths", + default=[], + ) parser.add_argument( "--precompile", action="store_true", @@ -527,10 +748,17 @@ def main(argv: Sequence[str] | None = None) -> None: install_wheel( args.wheel, args.directory, + installed_dir=args.installed_dir, target_os=args.target_os, srcs_exclude_globs=args.srcs_exclude_globs, data_exclude_globs=args.data_exclude_globs, create_namespace_inits_flag=args.create_namespace_inits, + patches=args.patches, + patch_strip=args.patch_strip, + expected_site_paths=( + args.expected_site_paths if args.validate_site_packages else None + ), + validation_source=args.validation_source, precompile=args.precompile, pyc_tag=args.pyc_tag, precompile_invalidation_mode=args.precompile_invalidation_mode, diff --git a/python/private/pypi/attrs.bzl b/python/private/pypi/attrs.bzl index 19c414d7a5..9fce3153e2 100644 --- a/python/private/pypi/attrs.bzl +++ b/python/private/pypi/attrs.bzl @@ -95,10 +95,13 @@ In this mode: installation action using its documented CLI (`@params` file); worker settings (`--//tools/precompiler:execution_requirements` and `testing.ExecutionInfo`) do not apply. -- In `pip.whl_mods`, `filegroups` is not supported, `copy_files` / - `copy_executables` cannot reference wheel-extracted paths as sources, and - `native.glob()` in `additive_build_content` matches no wheel files (a warning - is emitted). +- In `pip.whl_mods`, `filegroups`, `copy_files`, and `copy_executables` extract + files from downloaded wheels via `py_wheel_extract_files`, and + `additive_build_content` should use `wheel_glob(...)` (or + `load(":wheel_files.bzl", "wheel_glob")` from external `.bzl` macros), + `py_wheel_headers`, `py_wheel_transform`, `post_install_patches`, or + `py_wheel_extract_files` instead of `native.glob(...)` over extracted wheel + paths (`site-packages/`, `include/`, `data/`). ::: :::{versionadded} VERSION_NEXT_FEATURE diff --git a/python/private/pypi/extension.bzl b/python/private/pypi/extension.bzl index fb6cac88e7..0d788319da 100644 --- a/python/private/pypi/extension.bzl +++ b/python/private/pypi/extension.bzl @@ -44,7 +44,8 @@ def _whl_mods_impl(whl_mods_dict): whl_mods = {} # create a struct that we can pass to the _whl_mods_repo rule - # to create the different JSON files. + # to create the different JSON files. Mock structs in unit tests + # may omit newer optional fields such as `filegroups`. for whl_name, mods in whl_maps.items(): whl_mods[whl_name] = json.encode(struct( additive_build_content = mods.build_content, @@ -53,6 +54,7 @@ def _whl_mods_impl(whl_mods_dict): data = mods.data, data_exclude_glob = mods.data_exclude_glob, srcs_exclude_glob = mods.srcs_exclude_glob, + **({"filegroups": mods.filegroups} if hasattr(mods, "filegroups") and mods.filegroups else {}) )) _whl_mods_repo( @@ -220,6 +222,7 @@ You cannot use both the additive_build_content and additive_build_content_file a copy_executables = whl_mod.copy_executables, data = whl_mod.data, data_exclude_glob = whl_mod.data_exclude_glob, + filegroups = whl_mod.filegroups, srcs_exclude_glob = whl_mod.srcs_exclude_glob, ) @@ -1075,6 +1078,15 @@ the generated `py_library` target.""", doc = """\ (list, optional): A list of exclude glob patterns to add as `data` to the generated `py_library` target.""", + ), + "filegroups": attr.string_list_dict( + doc = """ +(dict, optional): A mapping of filegroup target names to lists of glob patterns +relative to the installed wheel root (`site-packages/`, `data/`, `bin/`, `include/`). + +:::{versionadded} VERSION_NEXT_FEATURE +::: +""", ), "hub_name": attr.string( doc = """\ diff --git a/python/private/pypi/generate_whl_library_build_bazel.bzl b/python/private/pypi/generate_whl_library_build_bazel.bzl index 617f4e1639..fa0cb0386f 100644 --- a/python/private/pypi/generate_whl_library_build_bazel.bzl +++ b/python/private/pypi/generate_whl_library_build_bazel.bzl @@ -24,6 +24,7 @@ _RENDER = { "entry_points": render.dict_dict, "extracted_files": render.list, "extras": render.list, + "filegroups": render.dict, "group_deps": render.list, "include": str, "repo": lambda maybe_label: repr(str(maybe_label)), @@ -53,10 +54,11 @@ whl_package_metadata( """ def _check_additive_build_content_for_glob(content): - """Return True if `content` contains a `glob(` call outside comments.""" + """Return True if `content` contains a non-`wheel_glob` `glob(` call outside comments.""" for raw_line in content.splitlines(): line = raw_line.split("#", 1)[0] - if "glob(" in line or "glob (" in line: + without_wheel_glob = line.replace("wheel_glob(", "").replace("wheel_glob (", "") + if "glob(" in without_wheel_glob or "glob (" in without_wheel_glob: return True return False @@ -122,6 +124,8 @@ def generate_whl_library_build_bazel( kwargs["copy_executables"] = annotation.copy_executables kwargs["data_exclude"] = kwargs.get("data_exclude", []) + annotation.data_exclude_glob kwargs["srcs_exclude"] = annotation.srcs_exclude_glob + if hasattr(annotation, "filegroups") and annotation.filegroups and "filegroups" not in kwargs: + kwargs["filegroups"] = annotation.filegroups if annotation.additive_build_content: should_warn_glob = ( kwargs.get("action_install") and @@ -132,10 +136,25 @@ def generate_whl_library_build_bazel( logger.warn( ( "In '{}', annotation 'additive_build_content' may glob wheel contents; " + - "globs match nothing under experimental_action_install because wheel " + - "contents are extracted into the ':srcs' TreeArtifact during the build phase." + "globs match nothing under experimental_action_install — use wheel_glob(), " + + "py_wheel_headers, py_wheel_transform, post_install_patches, or " + + "py_wheel_extract_files instead." ).format(kwargs.get("name", kwargs.get("metadata_name", ""))), ) + if ( + "wheel_glob(" in annotation.additive_build_content or + "wheel_glob (" in annotation.additive_build_content + ): + loads.append( + """load("@rules_python//python/private/pypi:py_wheel_extract_files.bzl", "wheel_glob")""", + ) + if ( + "wheel_extract_prefix(" in annotation.additive_build_content or + "wheel_extract_prefix (" in annotation.additive_build_content + ): + loads.append( + """load("@rules_python//python/private/pypi:py_wheel_extract_files.bzl", "wheel_extract_prefix")""", + ) additional_content.append(annotation.additive_build_content) contents = "\n".join( @@ -156,3 +175,34 @@ def generate_whl_library_build_bazel( # NOTE: Ensure that we terminate with a new line return contents.rstrip() + "\n" + +def generate_wheel_files_bzl(extracted_files): + """Generate the contents of `wheel_files.bzl` for a wheel repository.""" + return """\ +\"\"\"Generated wheel file list and wheel_glob wrapper.\"\"\" + +load("@rules_python//python/private/pypi:py_wheel_extract_files.bzl", _wheel_glob = "wheel_glob") # buildifier: disable=bzl-visibility + +FILES = {files} + +def wheel_glob( + include, + exclude = [], + exclude_directories = 1, + allow_empty = True, + *, + wheel_library = Label("//:_wheel_install"), + is_executable = False): + \"\"\"Glob over wheel files in this repository.\"\"\" + return _wheel_glob( + include = include, + exclude = exclude, + exclude_directories = exclude_directories, + allow_empty = allow_empty, + files = FILES, + wheel_library = wheel_library, + is_executable = is_executable, + ) +""".format( + files = render.list(extracted_files), + ) diff --git a/python/private/pypi/package_annotation.bzl b/python/private/pypi/package_annotation.bzl index 4a54703ac4..191d035abb 100644 --- a/python/private/pypi/package_annotation.bzl +++ b/python/private/pypi/package_annotation.bzl @@ -20,11 +20,16 @@ def package_annotation( copy_executables = {}, data = [], data_exclude_glob = [], + filegroups = {}, srcs_exclude_glob = []): """Annotations to apply to the BUILD file content from package generated from a `pip_repository` rule. [cf]: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/copy_file_doc.md + :::{versionchanged} VERSION_NEXT_FEATURE + Added the `filegroups` parameter. + ::: + Args: additive_build_content (str, optional): Raw text to add to the generated `BUILD` file of a package. copy_files (dict, optional): A mapping of `src` and `out` files for [@bazel_skylib//rules:copy_file.bzl][cf] @@ -34,6 +39,7 @@ def package_annotation( data (list, optional): A list of labels to add as `data` dependencies to the generated `py_library` target. data_exclude_glob (list, optional): A list of exclude glob patterns to add as `data` to the generated `py_library` target. + filegroups (dict, optional): A mapping of filegroup target names to glob patterns (or include/exclude dicts). srcs_exclude_glob (list, optional): A list of labels to add as `srcs` to the generated `py_library` target. Returns: @@ -46,4 +52,5 @@ def package_annotation( data = data, data_exclude_glob = data_exclude_glob, srcs_exclude_glob = srcs_exclude_glob, + **({"filegroups": filegroups} if filegroups else {}) )) diff --git a/python/private/pypi/patch_and_extract_whl.bzl b/python/private/pypi/patch_and_extract_whl.bzl index d047d85c51..dc5008264a 100644 --- a/python/private/pypi/patch_and_extract_whl.bzl +++ b/python/private/pypi/patch_and_extract_whl.bzl @@ -2,7 +2,11 @@ load("//python/private:normalize_name.bzl", "normalize_name") load("//python/private:repo_utils.bzl", "repo_utils") -load(":generate_whl_library_build_bazel.bzl", "generate_whl_library_build_bazel") +load( + ":generate_whl_library_build_bazel.bzl", + "generate_wheel_files_bzl", + "generate_whl_library_build_bazel", +) load(":labels.bzl", "DEFAULT_DATA_EXCLUDE") load(":patch_whl.bzl", "get_whl_patches", "patch_whl") load(":pep508_requirement.bzl", "requirement") @@ -167,6 +171,13 @@ def _inspect_whl_for_action_install( rctx.file("entry_points.txt", inspection["entry_points_content"]) extra_kwargs["has_entry_points_txt"] = True + wheel_files_list = list(inspection["extracted_files"]) + for s in inspection.get("shebang_scripts", []): + bin_s = "bin/" + s + if bin_s not in wheel_files_list: + wheel_files_list.append(bin_s) + rctx.file("wheel_files.bzl", generate_wheel_files_bzl(sorted(wheel_files_list))) + return struct( metadata = metadata, entry_points = parse_entry_points(inspection["entry_points_content"]), diff --git a/python/private/pypi/py_installed_wheel_info.bzl b/python/private/pypi/py_installed_wheel_info.bzl new file mode 100644 index 0000000000..dac5d2342e --- /dev/null +++ b/python/private/pypi/py_installed_wheel_info.bzl @@ -0,0 +1,36 @@ +"""Provider for an installed wheel directory (TreeArtifact).""" + +PyInstalledWheelInfo = provider( + doc = """ +Information about an installed Python wheel TreeArtifact. + +:::{versionadded} VERSION_NEXT_FEATURE +::: +""", + fields = { + "directory": """ +:type: File +The installed wheel TreeArtifact directory containing site-packages/, data/, +bin/, and include/. +""", + "keep_source": """ +:type: bool +Whether `.py` source files are retained in `directory`. +""", + "precompiled": """ +:type: bool +Whether `.py` files in `directory` were precompiled into `.pyc` files. +""", + "settings_key": """ +:type: tuple +Tuple of install settings `(should_precompile, keep_source, invalidation_mode, +optimize_level, srcs_exclude, data_exclude, create_namespace_inits)` used to +determine whether an outer `py_wheel_library` can reuse `directory`. +""", + "wheel": """ +:type: File | None +The underlying `.whl` file (or `.whldir` directory) when the installed wheel has +no `post_install_patches`, or `None` if `post_install_patches` were applied. +""", + }, +) diff --git a/python/private/pypi/py_wheel_extract_files.bzl b/python/private/pypi/py_wheel_extract_files.bzl new file mode 100644 index 0000000000..bfd0360f0a --- /dev/null +++ b/python/private/pypi/py_wheel_extract_files.bzl @@ -0,0 +1,516 @@ +"""Rule and loading-time glob helper for extracting files from an action-installed wheel library.""" + +load("@bazel_skylib//lib:paths.bzl", "paths") +load("@bazel_skylib//lib:types.bzl", "types") +load("//python/private:attr_builders.bzl", "attrb") +load("//python/private:common.bzl", "actions_run") +load("//python/private:rule_builders.bzl", "ruleb") +load( + "//python/private:toolchain_types.bzl", + "EXEC_TOOLS_TOOLCHAIN_TYPE", +) +load(":py_installed_wheel_info.bzl", "PyInstalledWheelInfo") + +def _validate_rel_path(raw_path): + norm = paths.normalize(raw_path) + if ( + not raw_path or + paths.is_absolute(raw_path) or + norm in (".", "..") or + norm.startswith("../") + ): + fail( + "paths entries must be non-empty relative file paths within the wheel tree, got '{}'".format( + raw_path, + ), + ) + return norm + +def _py_wheel_extract_files_impl(ctx): + if not ctx.attr.paths: + return [DefaultInfo(files = depset())] + + installed_info = ctx.attr.wheel_library[PyInstalledWheelInfo] + wheel_dir = installed_info.directory + prefix = ctx.attr.out_prefix if ctx.attr.out_prefix else ("_extracted/" + ctx.attr.name) + + args = ctx.actions.args() + args.add_all("--wheel-dir", [wheel_dir], expand_directories = False) + if ctx.attr.is_executable: + args.add("--executable") + + inputs = [wheel_dir] + if not installed_info.keep_source and installed_info.wheel != None: + args.add_all("--fallback-wheel", [installed_info.wheel], expand_directories = False) + inputs.append(installed_info.wheel) + elif not installed_info.keep_source: + for raw_path in ctx.attr.paths: + if raw_path.startswith("site-packages/") and raw_path.endswith(".py"): + fail( + "Cannot extract .py source file '{}' from {} when precompile_source_retention is 'omit_source' and post_install_patches are applied".format( + raw_path, + ctx.attr.wheel_library.label, + ), + ) + + outputs = [] + if ctx.outputs.outs: + if len(ctx.outputs.outs) != len(ctx.attr.paths): + fail( + "outs length ({}) must match paths length ({})".format( + len(ctx.outputs.outs), + len(ctx.attr.paths), + ), + ) + for raw_path, out_file in zip(ctx.attr.paths, ctx.outputs.outs): + norm = _validate_rel_path(raw_path) + outputs.append(out_file) + args.add("--entry", "{}={}".format(norm, out_file.path)) + else: + seen = {} + for raw_path in ctx.attr.paths: + norm = _validate_rel_path(raw_path) + if norm in seen: + continue + seen[norm] = True + out_file = ctx.actions.declare_file(paths.join(prefix, norm)) + outputs.append(out_file) + args.add("--entry", "{}={}".format(norm, out_file.path)) + + actions_run( + ctx, + executable = ctx.attr._wheel_files_extractor, + arguments = [args], + env = { + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONPATH": ctx.file._wheel_layout.dirname, + }, + inputs = inputs + [ctx.file._wheel_layout], + outputs = outputs, + mnemonic = "PyWheelExtractFiles", + progress_message = "Extracting {} file(s) from {} for %{{label}}".format( + len(outputs), + wheel_dir.short_path, + ), + ) + + return [ + DefaultInfo( + files = depset(outputs), + runfiles = ctx.runfiles(files = outputs), + ), + ] + +py_wheel_extract_files = ruleb.Rule( + implementation = _py_wheel_extract_files_impl, + doc = """Extracts individual files at known relative paths from an installed wheel library. + +Given a target providing `PyInstalledWheelInfo` (such as a `py_wheel_library` target or +`@pypi//:srcs` when `experimental_action_install` is enabled), this rule copies each +path in `paths` out of the installed wheel directory tree into a declared output `File` +(reflecting any `py_wheel_transform` or `post_install_patches` applied to the wheel). + +:::{versionadded} VERSION_NEXT_FEATURE +::: +""", + attrs = { + "is_executable": lambda: attrb.Bool( + default = False, + doc = "If True, marks the extracted files as executable (`chmod +x`).", + ), + "out_prefix": lambda: attrb.String( + default = "", + doc = """ +Optional package-relative directory prefix under which extracted files are declared +when `outs` is not specified. Defaults to `_extracted/` to avoid colliding with +the wheel's `:srcs` directory. +""", + ), + "outs": lambda: attrb.OutputList( + doc = """ +Optional list of predeclared output files, one per entry in `paths`. When set, each +entry in `outs` is addressable as a file label in the package at loading time. +""", + ), + "paths": lambda: attrb.StringList( + mandatory = True, + doc = """ +Relative file paths within the installed wheel tree root (e.g. +`["site-packages/my_pkg/data.json", "bin/my_tool", "include/my_pkg/hdr.h"]`) +to extract as individual `File` outputs. +""", + ), + "wheel_library": lambda: attrb.Label( + mandatory = True, + providers = [PyInstalledWheelInfo], + doc = """ +A target providing `PyInstalledWheelInfo` (such as a `py_wheel_library` target or +`@pypi//:srcs` when `experimental_action_install` is enabled). +""", + ), + "_wheel_files_extractor": lambda: attrb.Label( + cfg = "exec", + default = Label("//python/private/pypi:wheel_files_extractor"), + ), + "_wheel_layout": lambda: attrb.Label( + allow_single_file = True, + default = Label("//python/private/pypi:wheel_layout.py"), + ), + }, + toolchains = [ + ruleb.ToolchainType(EXEC_TOOLS_TOOLCHAIN_TYPE, mandatory = True), + ], +).build() + +def _match_segment(pat, seg): + """Match a single path segment against a wildcard pattern with `*` and `?`.""" + if pat == "*": + return True + if "*" not in pat and "?" not in pat: + return pat == seg + n = len(seg) + dp = [True] + [False] * n + for pch in pat.elems(): + if pch == "*": + running = False + next_dp = [] + for j in range(n + 1): + if dp[j]: + running = True + next_dp.append(running) + dp = next_dp + else: + next_dp = [False] + for j in range(n): + next_dp.append(dp[j] and (pch == "?" or pch == seg[j])) + dp = next_dp + return dp[n] + +def _match_glob_pattern(pattern, path): + """Match a slash-separated path against a glob pattern supporting `*`, `?`, and `**`.""" + pat_segs = [s for s in pattern.split("/") if s] + path_segs = [s for s in path.split("/") if s] + m = len(path_segs) + dp = [True] + [False] * m + for pseg in pat_segs: + if pseg == "**": + running = False + next_dp = [] + for j in range(m + 1): + if dp[j]: + running = True + next_dp.append(running) + dp = next_dp + else: + next_dp = [False] + for j in range(m): + next_dp.append(dp[j] and _match_segment(pseg, path_segs[j])) + dp = next_dp + return dp[m] + +def match_wheel_glob(files, include, exclude = [], allow_empty = True, _fail = fail): + """Evaluate `include` / `exclude` glob patterns against `files` at loading time. + + Args: + files: {type}`list[str]` Candidate relative file paths in the wheel tree. + include: {type}`list[str]` Glob patterns to include (`*`, `?`, `**`). + exclude: {type}`list[str]` Glob patterns to exclude. + allow_empty: {type}`bool` If False, fail when no files match. + _fail: {type}`callable` Fail function for testing. + + Returns: + Sorted list of matching file paths from `files`. + """ + if not (types.is_list(include) or types.is_tuple(include)): + _fail("wheel_glob 'include' argument must be a list or tuple of strings, got {}".format(type(include))) + return [] + if not (types.is_list(exclude) or types.is_tuple(exclude)): + _fail("wheel_glob 'exclude' argument must be a list or tuple of strings, got {}".format(type(exclude))) + return [] + + for arg_name, pat_list in [("include", include), ("exclude", exclude)]: + for pat in pat_list: + if not types.is_string(pat) or not pat: + _fail( + "wheel_glob '{}' patterns must be non-empty strings, got {}".format( + arg_name, + repr(pat), + ), + ) + return [] + if pat.startswith("/") or pat.endswith("/") or "//" in pat: + _fail( + "wheel_glob '{}' pattern '{}' must not have leading, trailing, or consecutive slashes".format( + arg_name, + pat, + ), + ) + return [] + for seg in pat.split("/"): + if seg in (".", ".."): + _fail( + "wheel_glob '{}' pattern '{}' must not contain '.' or '..' segments".format( + arg_name, + pat, + ), + ) + return [] + if "**" in seg and seg != "**": + _fail( + "wheel_glob '{}' pattern '{}' contains invalid '**' segment '{}' ('**' must be a full path segment)".format( + arg_name, + pat, + seg, + ), + ) + return [] + + matched = {} + for f in files: + inc = False + for pat in include: + if _match_glob_pattern(pat, f): + inc = True + break + if not inc: + continue + exc = False + for pat in exclude: + if _match_glob_pattern(pat, f): + exc = True + break + if not exc: + matched[f] = True + + result = sorted(matched.keys()) + if not result and not allow_empty: + _fail( + "wheel_glob pattern(s) {} did not match any files in wheel (allow_empty = False)".format( + include, + ), + ) + return result + +_DEFAULT_MODE_REPO_EXCLUDES = [ + "BUILD", + "BUILD.bazel", + "MODULE.bazel", + "REPO.bazel", + "WORKSPACE", + "WORKSPACE.bzlmod", + "WORKSPACE.bazel", + "metadata.json", + "wheel_files.bzl", + "*.whl", + "*.tar.gz", + "*.tgz", + "*.zip", + "rewrite-bin/**", + "rewrite-record/**", +] + +def _collect_default_mode_excludes(exclude, native, has_existing_rule): + default_excludes = list(_DEFAULT_MODE_REPO_EXCLUDES) + whl_file_rule = native.existing_rule("whl_file") if has_existing_rule else None + if whl_file_rule != None: + for src_label in whl_file_rule.get("srcs", ()): + clean_src = src_label.lstrip(":") + if clean_src and clean_src not in default_excludes: + default_excludes.append(clean_src) + for item in exclude: + if item not in default_excludes: + default_excludes.append(item) + return default_excludes + +def _is_sdist_wheel_install(install_rule, native, has_existing_rule): + sdist_rule = ( + (native.existing_rule("whldir") or native.existing_rule("_sdist_whl")) if has_existing_rule else None + ) + if sdist_rule != None or install_rule == None: + return sdist_rule != None + if install_rule.get("site_paths"): + return True + if install_rule.get("wheel") in (":whldir", "whldir", ":_sdist_whl", "_sdist_whl"): + return True + return ( + install_rule.get("kind") == "py_wheel_library" and + not install_rule.get("extracted_files") and + not install_rule.get("shebang_scripts") + ) + +def wheel_extract_prefix(*, is_executable = False, native = native): + """Return the package-relative output directory prefix used by `wheel_glob` in the current package. + + Returns `"_extracted/"` (or `"_extracted_exec/"` when `is_executable = True`) when + `experimental_action_install` is active in the package, or `""` in default mode, + allowing mode-agnostic `includes = [wheel_extract_prefix() + "site-packages/pkg/include"]`. + + :::{versionadded} VERSION_NEXT_FEATURE + ::: + + Args: + is_executable: {type}`bool` Whether executable extraction prefix is requested. + native: {type}`struct` Native module (overridable in tests). + + Returns: + {type}`str` Output path prefix (`"_extracted/"`, `"_extracted_exec/"`, or `""`). + """ + has_existing_rule = hasattr(native, "existing_rule") + wheel_install_rule = native.existing_rule("_wheel_install") if has_existing_rule else None + srcs_rule = native.existing_rule("srcs") if has_existing_rule else None + install_rule = wheel_install_rule if wheel_install_rule != None else srcs_rule + if install_rule != None and install_rule.get("kind") == "py_wheel_library": + return "_extracted_exec/" if is_executable else "_extracted/" + return "" + +def wheel_glob( + include, + exclude = [], + exclude_directories = 1, + allow_empty = True, + *, + files = None, + wheel_library = None, + is_executable = False, + native = native, + extract_rule = py_wheel_extract_files, + _state = None, + _fail = fail): + """Glob over a downloaded wheel's known file list at loading time and extract matches. + + Usable in `additive_build_content` and in `.bzl` macros it loads as a drop-in + replacement for `native.glob(...)` when `experimental_action_install` is enabled. + Matches `include` / `exclude` against the wheel's `FILES` list, instantiates + `py_wheel_extract_files` for matched paths (de-duplicating across calls in the + same package), and returns the predeclared output file labels. + + :::{note} + In `additive_build_content`, `wheel_glob` is auto-loaded in both default and + `experimental_action_install` modes. However, the per-wheel `:wheel_files.bzl` file + (for external `load("@pypi_...//:wheel_files.bzl", "wheel_glob", "FILES")`) is + generated only when `experimental_action_install` is enabled (and its default + `wheel_library = Label("//:_wheel_install")` target is an internal implementation + detail exposed solely for cross-package `wheel_files.bzl` loads, not a public API). + ::: + + :::{note} + Returned file paths differ between modes: under `experimental_action_install`, + labels are emitted under `:_extracted/` (or `:_extracted_exec/` when + `is_executable = True`), whereas in default mode `wheel_glob` delegates to + `native.glob` (excluding repository bookkeeping files) and returns `` directly + (ignoring `is_executable` and rewritten `bin/` scripts). Do not hardcode + `"_extracted/..."` in attributes like `cc_import`/`cc_library` `includes`; use + `py_wheel_headers` or `wheel_extract_prefix() + ""` instead. + ::: + + :::{versionadded} VERSION_NEXT_FEATURE + ::: + + Args: + include: {type}`list[str]` Glob patterns to include (`*`, `?`, `**`). + exclude: {type}`list[str]` Glob patterns to exclude. + exclude_directories: {type}`int` Must be `0` or `1` (for `native.glob` compatibility; + wheel `FILES` contains only files). + allow_empty: {type}`bool` Whether to allow an empty match result. + files: {type}`list[str] | None` Optional explicit list of wheel file paths (e.g. `FILES` + from `:wheel_files.bzl`). When omitted, discovered automatically from the current + package's `py_wheel_library` target. + wheel_library: {type}`str | Label | None` Target providing `PyInstalledWheelInfo`. + Defaults to `":_wheel_install"` if present in the package, else `":srcs"`. + is_executable: {type}`bool` Whether extracted files should have the executable bit set. + native: {type}`struct` Native module (overridable in tests). + extract_rule: {type}`callable` Rule used to extract files (overridable in tests). + _state: {type}`dict | None` Optional per-package state dict for mock tests without + `native.existing_rule`. + _fail: {type}`callable` Fail function (overridable in tests). + + Returns: + {type}`list[str]` Labels of the extracted output `File` targets. + """ + if exclude_directories not in (0, 1): + _fail( + "wheel_glob 'exclude_directories' argument must be 0 or 1, got {}".format( + exclude_directories, + ), + ) + return [] + has_existing_rule = hasattr(native, "existing_rule") + wheel_install_rule = native.existing_rule("_wheel_install") if has_existing_rule else None + srcs_rule = native.existing_rule("srcs") if has_existing_rule else None + install_rule = wheel_install_rule if wheel_install_rule != None else srcs_rule + + if wheel_library == None: + wheel_library = ":_wheel_install" if wheel_install_rule != None else ":srcs" + + if files == None: + if _is_sdist_wheel_install(install_rule, native, has_existing_rule): + _fail( + "wheel_glob() cannot be used with an action-built sdist because wheel contents " + + "are not known at loading time under experimental_action_install. Use a " + + "pre-built wheel or py_wheel_headers / py_wheel_transform instead.", + ) + return [] + if install_rule != None and install_rule.get("kind") != "py_wheel_library" and hasattr(native, "glob"): + return native.glob( + include, + exclude = _collect_default_mode_excludes(exclude, native, has_existing_rule), + exclude_directories = exclude_directories, + allow_empty = allow_empty, + ) + if install_rule == None or install_rule.get("kind") != "py_wheel_library": + _fail( + "wheel_glob() requires either 'files' to be passed explicitly or an " + + "action-installed py_wheel_library target ('srcs') in the current package.", + ) + return [] + files = list(install_rule.get("extracted_files", ())) + for s in install_rule.get("shebang_scripts", ()): + bin_s = "bin/" + s + if bin_s not in files: + files.append(bin_s) + + matched = match_wheel_glob( + files, + include, + exclude = exclude, + allow_empty = allow_empty, + _fail = _fail, + ) + if not matched: + return [] + + rule_prefix = "_wheel_extract_exec" if is_executable else "_wheel_extract" + out_dir = "_extracted_exec" if is_executable else "_extracted" + already_extracted = {} + next_idx = 0 + + if has_existing_rule: + for i in range(10000): + existing = native.existing_rule("{}_{}".format(rule_prefix, i)) + if existing == None: + next_idx = i + break + for p in existing.get("paths", ()): + already_extracted[p] = True + elif _state != None: + already_extracted = _state.setdefault(rule_prefix + "_paths", {}) + next_idx = _state.get(rule_prefix + "_idx", 0) + + new_paths = [p for p in matched if p not in already_extracted] + if new_paths: + for p in new_paths: + already_extracted[p] = True + if _state != None and not has_existing_rule: + _state[rule_prefix + "_idx"] = next_idx + 1 + extract_kwargs = dict( + name = "{}_{}".format(rule_prefix, next_idx), + wheel_library = wheel_library, + paths = new_paths, + outs = ["{}/{}".format(out_dir, p) for p in new_paths], + visibility = ["//visibility:private"], + ) + if is_executable: + extract_kwargs["is_executable"] = True + extract_rule(**extract_kwargs) + + return [":{}/{}".format(out_dir, p) for p in matched] diff --git a/python/private/pypi/py_wheel_headers.bzl b/python/private/pypi/py_wheel_headers.bzl new file mode 100644 index 0000000000..ce49f4de10 --- /dev/null +++ b/python/private/pypi/py_wheel_headers.bzl @@ -0,0 +1,56 @@ +"""Rule for exposing C/C++ headers from an action-installed wheel library.""" + +load("@bazel_skylib//lib:paths.bzl", "paths") +load("@rules_cc//cc/common:cc_common.bzl", "cc_common") +load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") +load(":py_installed_wheel_info.bzl", "PyInstalledWheelInfo") + +def _py_wheel_headers_impl(ctx): + wheel_dir = ctx.attr.wheel_library[PyInstalledWheelInfo].directory + includes = [] + for raw_dir in ctx.attr.include_dirs: + norm = paths.normalize(raw_dir) + if not raw_dir or paths.is_absolute(raw_dir) or norm == ".." or norm.startswith("../"): + fail("include_dirs entries must be non-empty relative paths within the wheel tree, got '{}'".format(raw_dir)) + includes.append(wheel_dir.path if norm == "." else wheel_dir.path + "/" + norm) + + compilation_context = cc_common.create_compilation_context( + headers = depset([wheel_dir]), + includes = depset(includes), + ) + + return [ + DefaultInfo(files = depset([wheel_dir])), + CcInfo(compilation_context = compilation_context), + ] + +py_wheel_headers = rule( + implementation = _py_wheel_headers_impl, + provides = [CcInfo], + doc = """Exposes C/C++ headers from an installed wheel library (TreeArtifact) as CcInfo. + +Given a `py_wheel_library` target (or `@pypi//:srcs` when `experimental_action_install` +is enabled), this rule exposes the headers at `include_dirs` within the wheel's installed +directory tree without requiring `glob()` in the repository `BUILD` file. + +:::{versionadded} VERSION_NEXT_FEATURE +::: +""", + attrs = { + "include_dirs": attr.string_list( + default = ["include", "site-packages"], + doc = """ +Relative paths within the installed wheel tree root (e.g. `["site-packages/numpy/_core/include"]` +or `["include/python3.12"]`) to add to the C/C++ include search path. +""", + ), + "wheel_library": attr.label( + mandatory = True, + providers = [PyInstalledWheelInfo], + doc = """ +A target providing `PyInstalledWheelInfo` (such as a `py_wheel_library` target or +`@pypi//:srcs` when `experimental_action_install` is enabled). +""", + ), + }, +) diff --git a/python/private/pypi/py_wheel_library.bzl b/python/private/pypi/py_wheel_library.bzl index 425aad745d..286b37ac04 100644 --- a/python/private/pypi/py_wheel_library.bzl +++ b/python/private/pypi/py_wheel_library.bzl @@ -42,6 +42,7 @@ load( ) load("//python/private:venv_runfiles.bzl", "get_venv_symlinks") load("//python/private:version.bzl", "version") +load(":py_installed_wheel_info.bzl", "PyInstalledWheelInfo") PY_WHEEL_LIBRARY_ATTRS = COMMON_ATTRS | WINDOWS_CONSTRAINTS_ATTRS | { "data_exclude": lambda: attrb.StringList( @@ -67,6 +68,22 @@ namespace packages. default = [], doc = """ Relative paths to pkgutil-style namespace package __init__.py files. +""", + ), + "post_install_patch_strip": lambda: attrb.Int( + default = 0, + doc = """ +Number of leading path components to strip when applying `post_install_patches` +(for example, set to `1` to strip `a/` and `b/` from git-formatted diffs). +""", + ), + "post_install_patches": lambda: attrb.LabelList( + allow_files = True, + default = [], + doc = """ +Unified diff patch files to apply against the installed wheel's `site-packages/` +directory after extracting the wheel. Git-formatted diffs (`a/` and `b/` +prefixes) require `post_install_patch_strip = 1`. """, ), "precompile": PY_SRCS_ATTRS["precompile"], @@ -167,13 +184,23 @@ def _resolve_invalidation_mode(ctx): return PrecompileInvalidationModeAttr.UNCHECKED_HASH return PrecompileInvalidationModeAttr.CHECKED_HASH -def _add_precompile_args(ctx, args, out_short_path, exec_tools_toolchain, source_retention): +def _expected_site_paths_from_extracted(extracted_files): + seen = {} + for f in extracted_files: + if not f.startswith("site-packages/"): + continue + top = f[len("site-packages/"):].partition("/")[0] + if top and not top.endswith(".dist-info"): + seen[top] = True + return seen.keys() + +def _add_precompile_args(ctx, args, out_short_path, exec_tools_toolchain, invalidation_mode, source_retention): target_runtime = ctx.toolchains[TARGET_TOOLCHAIN_TYPE].py3_runtime version_info = target_runtime.interpreter_version_info python_version = "{}.{}".format(version_info.major, version_info.minor) args.add("--precompile") args.add("--pyc-tag", target_runtime.pyc_tag) - args.add("--precompile-invalidation-mode", _resolve_invalidation_mode(ctx)) + args.add("--precompile-invalidation-mode", invalidation_mode) args.add("--precompile-optimize-level", str(ctx.attr.precompile_optimize_level)) args.add("--precompile-source-retention", source_retention) args.add("--python-version", python_version) @@ -267,38 +294,56 @@ def _compute_wheel_venv_symlinks( )) return venv_symlinks -def _py_wheel_library_impl(ctx): - exec_tools_toolchain = ctx.toolchains[EXEC_TOOLS_TOOLCHAIN_TYPE] - if exec_tools_toolchain == None: - fail( - "experimental_action_install requires the exec_tools toolchain " + - "(set //python/config_settings:exec_tools_toolchain=enabled)", - ) - +def _run_wheel_install_action( + ctx, + *, + installed_info, + effective_srcs_exclude, + effective_data_exclude, + is_windows, + create_namespace_inits, + venvs_site_packages_enabled, + should_precompile, + invalidation_mode, + source_retention, + keep_source, + exec_tools_toolchain): out = ctx.actions.declare_directory(ctx.attr.name) - is_windows = is_windows_platform(ctx) - venvs_site_packages_enabled = VenvsSitePackages.is_enabled(ctx) - create_namespace_inits = ( - not ctx.attr.enable_implicit_namespace_pkgs and - not venvs_site_packages_enabled - ) - should_precompile = _should_precompile(ctx, exec_tools_toolchain) - source_retention = PrecompileSourceRetentionAttr.get_effective_value(ctx) - keep_source = ( - not should_precompile or - source_retention == PrecompileSourceRetentionAttr.KEEP_SOURCE - ) - args = ctx.actions.args() - args.add("--wheel", ctx.file.wheel) + + if installed_info != None and installed_info.wheel == None: + if not installed_info.keep_source and (keep_source or ctx.files.post_install_patches): + fail( + "Cannot apply post_install_patches or restore .py sources from '{}' because its .py sources were omitted (precompile_source_retention = 'omit_source')".format( + ctx.attr.wheel.label, + ), + ) + args.add_all("--installed-dir", [installed_info.directory], expand_directories = False) + install_source_file = installed_info.directory + underlying_wheel = None + else: + install_source_file = ( + installed_info.wheel if installed_info != None else ctx.file.wheel + ) + args.add_all("--wheel", [install_source_file], expand_directories = False) + underlying_wheel = None if ctx.files.post_install_patches else install_source_file + args.add_all("--directory", [out], expand_directories = False) args.add("--target-os", "windows" if is_windows else "unix") - for pattern in ctx.attr.srcs_exclude: + for pattern in effective_srcs_exclude: args.add("--srcs-exclude-glob", pattern) - for pattern in ctx.attr.data_exclude: + for pattern in effective_data_exclude: args.add("--data-exclude-glob", pattern) if create_namespace_inits: args.add("--create-namespace-inits") + if ctx.files.post_install_patches: + args.add("--patch-strip", str(ctx.attr.post_install_patch_strip)) + for patch_file in ctx.files.post_install_patches: + args.add("--patch", patch_file) + if venvs_site_packages_enabled: + args.add("--validate-site-packages") + for sp in _expected_site_paths_from_extracted(ctx.attr.extracted_files): + args.add("--expected-site-path", sp) extra_tools = [] if should_precompile: @@ -307,6 +352,7 @@ def _py_wheel_library_impl(ctx): args, out.short_path, exec_tools_toolchain, + invalidation_mode, source_retention, ) @@ -319,12 +365,82 @@ def _py_wheel_library_impl(ctx): "PYTHONDONTWRITEBYTECODE": "1", "PYTHONPATH": helper_files[0].dirname, }, - inputs = [ctx.file.wheel] + helper_files, + inputs = [install_source_file] + ctx.files.post_install_patches + helper_files, outputs = [out], tools = extra_tools, mnemonic = "PyWheelInstall", - progress_message = "Installing wheel {} into %{{output}}".format(ctx.file.wheel.basename), + progress_message = "Installing wheel {} into %{{output}}".format(install_source_file.basename), + ) + return out, underlying_wheel + +def _py_wheel_library_impl(ctx): + exec_tools_toolchain = ctx.toolchains[EXEC_TOOLS_TOOLCHAIN_TYPE] + if exec_tools_toolchain == None: + fail( + "experimental_action_install requires the exec_tools toolchain " + + "(set //python/config_settings:exec_tools_toolchain=enabled)", + ) + + is_windows = is_windows_platform(ctx) + venvs_site_packages_enabled = VenvsSitePackages.is_enabled(ctx) + create_namespace_inits = ( + not ctx.attr.enable_implicit_namespace_pkgs and + not venvs_site_packages_enabled + ) + should_precompile = _should_precompile(ctx, exec_tools_toolchain) + source_retention = PrecompileSourceRetentionAttr.get_effective_value(ctx) + keep_source = ( + not should_precompile or + source_retention == PrecompileSourceRetentionAttr.KEEP_SOURCE + ) + invalidation_mode = _resolve_invalidation_mode(ctx) if should_precompile else "" + + installed_info = ( + ctx.attr.wheel[PyInstalledWheelInfo] if PyInstalledWheelInfo in ctx.attr.wheel else None + ) + effective_srcs_exclude = list(ctx.attr.srcs_exclude) + effective_data_exclude = list(ctx.attr.data_exclude) + if installed_info != None: + for p in installed_info.settings_key[4]: + if p not in effective_srcs_exclude: + effective_srcs_exclude.append(p) + for p in installed_info.settings_key[5]: + if p not in effective_data_exclude: + effective_data_exclude.append(p) + + settings_key = ( + should_precompile, + keep_source, + invalidation_mode, + ctx.attr.precompile_optimize_level if should_precompile else 0, + tuple(effective_srcs_exclude), + tuple(effective_data_exclude), + create_namespace_inits, + ) + + can_reuse_installed = ( + installed_info != None and + not ctx.files.post_install_patches and + installed_info.settings_key == settings_key ) + if can_reuse_installed: + out = installed_info.directory + underlying_wheel = installed_info.wheel + else: + out, underlying_wheel = _run_wheel_install_action( + ctx, + installed_info = installed_info, + effective_srcs_exclude = effective_srcs_exclude, + effective_data_exclude = effective_data_exclude, + is_windows = is_windows, + create_namespace_inits = create_namespace_inits, + venvs_site_packages_enabled = venvs_site_packages_enabled, + should_precompile = should_precompile, + invalidation_mode = invalidation_mode, + source_retention = source_retention, + keep_source = keep_source, + exec_tools_toolchain = exec_tools_toolchain, + ) out_rf_path = runfiles_root_path(ctx, out.short_path) site_packages_rf_path = paths.join(out_rf_path, "site-packages") @@ -365,6 +481,13 @@ def _py_wheel_library_impl(ctx): providers = [ DefaultInfo(files = depset([out]), runfiles = runfiles), py_info, + PyInstalledWheelInfo( + directory = out, + keep_source = keep_source, + precompiled = should_precompile, + settings_key = settings_key, + wheel = underlying_wheel, + ), create_instrumented_files_info(ctx, source_attributes = []), PyCcLinkParamsInfo(cc_info = cc_info), create_output_group_info(py_info.transitive_sources, extra_groups = {}), @@ -402,7 +525,7 @@ consumers must handle directory `File`s. ::: """, attrs = PY_WHEEL_LIBRARY_ATTRS, - provides = [PyCcLinkParamsInfo, PyInfo] + _MaybeBuiltinPyInfo, + provides = [PyCcLinkParamsInfo, PyInfo, PyInstalledWheelInfo] + _MaybeBuiltinPyInfo, toolchains = [ ruleb.ToolchainType(TARGET_TOOLCHAIN_TYPE, mandatory = False), ruleb.ToolchainType(EXEC_TOOLS_TOOLCHAIN_TYPE, mandatory = False), diff --git a/python/private/pypi/py_wheel_transform.bzl b/python/private/pypi/py_wheel_transform.bzl new file mode 100644 index 0000000000..1bece1af4c --- /dev/null +++ b/python/private/pypi/py_wheel_transform.bzl @@ -0,0 +1,94 @@ +"""Rule for transforming a wheel file or .whldir TreeArtifact using a custom executable.""" + +load("//python/private:attr_builders.bzl", "attrb") +load("//python/private:common.bzl", "actions_run") +load("//python/private:py_internal.bzl", _py_builtins = "py_internal") +load("//python/private:rule_builders.bzl", "ruleb") +load("//python/private:toolchain_types.bzl", "EXEC_TOOLS_TOOLCHAIN_TYPE") + +def _py_wheel_transform_impl(ctx): + wheel_input = ctx.file.wheel + out_wheel_dir = ctx.actions.declare_directory(ctx.attr.name + ".whldir") + + args = ctx.actions.args() + args.add_all("--wheel", [wheel_input], expand_directories = False) + args.add_all("--out-wheel-dir", [out_wheel_dir], expand_directories = False) + args.add("--tool", ctx.executable.transform) + + targets = ctx.attr.data + [ctx.attr.transform] + for key, value in ctx.attr.env.items(): + expanded = _py_builtins.expand_location_and_make_variables( + ctx = ctx, + attribute_name = "env[{}]".format(key), + expression = value, + targets = targets, + ) + args.add("--env", "{}={}".format(key, expanded)) + + actions_run( + ctx, + executable = ctx.attr._wheel_transformer, + arguments = [args], + env = { + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONPATH": ctx.file._wheel_layout.dirname, + }, + inputs = depset( + [wheel_input, ctx.file._wheel_layout], + transitive = [dep[DefaultInfo].files for dep in ctx.attr.data], + ), + outputs = [out_wheel_dir], + tools = [ctx.attr.transform[DefaultInfo].files_to_run], + use_default_shell_env = True, + mnemonic = "PyWheelTransform", + progress_message = "Transforming wheel %{input} into %{output}", + ) + + return [DefaultInfo(files = depset([out_wheel_dir]))] + +py_wheel_transform = ruleb.Rule( + implementation = _py_wheel_transform_impl, + doc = """Runs a user-provided executable to transform a `.whl` file or `.whldir` TreeArtifact. + +The transform executable receives the default shell environment (`PATH`, etc.) scrubbed of the +wrapper's `RUNFILES_*` and `PYTHONSAFEPATH`/`PYTHONPATH`/`PYTHONHOME` launcher variables, along with: +- `WHEEL_FILE`: absolute path to the input `.whl` file. +- `WHEEL_OUTPUT_ROOT`: absolute path to the output directory where the single transformed + `.whl` file must be written. + +:::{versionadded} VERSION_NEXT_FEATURE +::: +""", + toolchains = [ + ruleb.ToolchainType(EXEC_TOOLS_TOOLCHAIN_TYPE, mandatory = True), + ], + attrs = { + "data": lambda: attrb.LabelList( + allow_files = True, + doc = "Additional data dependencies available to the transform tool.", + ), + "env": lambda: attrb.StringDict( + doc = "Environment variables passed to the transform tool (supports location and make variable expansion).", + ), + "transform": lambda: attrb.Label( + mandatory = True, + executable = True, + cfg = "exec", + doc = "The transform executable to run.", + ), + "wheel": lambda: attrb.Label( + mandatory = True, + allow_single_file = True, + doc = "The input `.whl` file or `.whldir` TreeArtifact directory.", + ), + "_wheel_layout": lambda: attrb.Label( + allow_single_file = True, + default = Label("//python/private/pypi:wheel_layout.py"), + ), + "_wheel_transformer": lambda: attrb.Label( + default = "//python/private/pypi:wheel_transformer", + executable = True, + cfg = "exec", + ), + }, +).build() diff --git a/python/private/pypi/wheel_files_extractor.py b/python/private/pypi/wheel_files_extractor.py new file mode 100644 index 0000000000..910dd50217 --- /dev/null +++ b/python/private/pypi/wheel_files_extractor.py @@ -0,0 +1,141 @@ +"""Build-action tool to extract individual files from an installed wheel TreeArtifact. + +Copies requested `REL_PATH=DEST_PATH` entries from `--wheel-dir` (or from +`--fallback-wheel` when `.py` sources were omitted during precompilation) into +declared output `File` paths. + +Usage: + python3 -B wheel_files_extractor.py --wheel-dir path/to/installed_dir \\ + --entry site-packages/pkg/data.json=bazel-out/.../data.json \\ + [--fallback-wheel path/to/pkg.whl] [--executable] +""" + +from __future__ import annotations + +import argparse +import os +import shutil +import zipfile +from collections.abc import Sequence +from pathlib import Path + +from wheel_layout import ( + find_wheel_dist_info_and_entry_points, + plan_wheel_entries, + single_wheel_in, +) + + +def _load_fallback_wheel_bytes(fallback_wheel: Path) -> dict[str, bytes]: + fallback_bytes: dict[str, bytes] = {} + whl_file = ( + single_wheel_in(fallback_wheel) if fallback_wheel.is_dir() else fallback_wheel + ) + with zipfile.ZipFile(whl_file) as z: + dist_info_dir, _, entry_points_content = find_wheel_dist_info_and_entry_points( + z + ) + for info, dest_or_script, is_shebang in plan_wheel_entries( + z, + dist_info_dir, + entry_points_content, + [], + [], + ): + dest_rel = f"bin/{dest_or_script}" if is_shebang else dest_or_script + fallback_bytes[dest_rel] = z.read(info) + return fallback_bytes + + +def extract_wheel_files( + wheel_dir: Path, + entries: list[tuple[str, Path]], + *, + executable: bool = False, + fallback_wheel: Path | None = None, +) -> None: + """Copy each `(rel_path, out_path)` from `wheel_dir` (or `fallback_wheel`) to `out_path`.""" + wheel_root = Path(os.path.abspath(wheel_dir)) + fallback_bytes: dict[str, bytes] | None = None + for rel_path, out_path in entries: + if not rel_path or rel_path.startswith("/") or "\\" in rel_path: + raise ValueError(f"Unsafe relative path for wheel extraction: {rel_path!r}") + src_path = wheel_dir / rel_path + src_abs = Path(os.path.abspath(src_path)) + if not src_abs.is_relative_to(wheel_root) or src_abs == wheel_root: + raise ValueError( + f"Extraction path '{rel_path}' escapes wheel directory '{wheel_dir}'" + ) + if ( + not src_path.is_file() + and rel_path.startswith("bin/") + and not rel_path.endswith(".bat") + ): + bat_candidate = wheel_dir / f"{rel_path}.bat" + if bat_candidate.is_file(): + src_path = bat_candidate + if src_path.is_file(): + out_path.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src_path, out_path) + if executable: + os.chmod(out_path, os.stat(out_path).st_mode | 0o111) + continue + + if fallback_wheel is None: + raise FileNotFoundError( + f"File '{rel_path}' does not exist in installed wheel directory '{wheel_dir}'" + ) + if fallback_bytes is None: + fallback_bytes = _load_fallback_wheel_bytes(fallback_wheel) + if rel_path not in fallback_bytes: + raise FileNotFoundError( + f"File '{rel_path}' does not exist in installed wheel directory '{wheel_dir}'" + ) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_bytes(fallback_bytes[rel_path]) + if executable: + os.chmod(out_path, os.stat(out_path).st_mode | 0o111) + + +def main(argv: Sequence[str] | None = None) -> None: + parser = argparse.ArgumentParser( + description="Extract individual files from an installed wheel TreeArtifact.", + fromfile_prefix_chars="@", + ) + parser.add_argument("--wheel-dir", type=Path, required=True) + parser.add_argument( + "--fallback-wheel", + type=Path, + default=None, + ) + parser.add_argument( + "--entry", + action="append", + dest="entries", + default=[], + help="Mapping of '='.", + ) + parser.add_argument( + "--executable", + action="store_true", + default=False, + ) + args = parser.parse_args(argv) + + parsed_entries: list[tuple[str, Path]] = [] + for item in args.entries: + rel_path, sep, out_str = item.partition("=") + if not sep or not rel_path or not out_str: + raise ValueError(f"Invalid --entry specification: {item!r}") + parsed_entries.append((rel_path, Path(out_str))) + + extract_wheel_files( + args.wheel_dir, + parsed_entries, + executable=args.executable, + fallback_wheel=args.fallback_wheel, + ) + + +if __name__ == "__main__": + main() diff --git a/python/private/pypi/wheel_layout.py b/python/private/pypi/wheel_layout.py index 55d76507c0..cbab8e93cb 100644 --- a/python/private/pypi/wheel_layout.py +++ b/python/private/pypi/wheel_layout.py @@ -296,6 +296,303 @@ def add_all(dirname: str, target: dict[str, None]) -> None: f.write(init_content) +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 += 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 + + def _record_row(entry_path: str, full_path: Path) -> list[str]: if entry_path.endswith((".pyc", ".pyo")): return [entry_path, "", ""] diff --git a/python/private/pypi/wheel_transformer.py b/python/private/pypi/wheel_transformer.py new file mode 100644 index 0000000000..f63c579180 --- /dev/null +++ b/python/private/pypi/wheel_transformer.py @@ -0,0 +1,87 @@ +"""Build-action wrapper to run a wheel transformation tool and output a .whldir TreeArtifact. + +Accepts an input `.whl` file or `.whldir` directory containing one `.whl`, +passes `WHEEL_FILE` and `WHEEL_OUTPUT_ROOT` to `--tool` in a scrubbed +environment, and validates that `--out-wheel-dir` contains a single `.whl`. + +Usage: + python3 -B wheel_transformer.py --wheel path/to/in.whl \\ + --out-wheel-dir path/to/out.whldir --tool path/to/transform_bin \\ + [--env KEY=VALUE ...] +""" + +from __future__ import annotations + +import argparse +import os +import subprocess +from pathlib import Path + +from wheel_layout import single_wheel_in + +_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 main() -> None: + parser = argparse.ArgumentParser( + description="Run a wheel transform tool and collect the transformed wheel.", + fromfile_prefix_chars="@", + ) + parser.add_argument( + "--wheel", + type=Path, + required=True, + help="Path to the input .whl file or .whldir directory.", + ) + parser.add_argument( + "--out-wheel-dir", + type=Path, + required=True, + help="Directory where the transform tool writes the output wheel.", + ) + parser.add_argument( + "--tool", + required=True, + help="Path to the user's transform tool executable.", + ) + parser.add_argument( + "--env", + action="append", + default=[], + help="Extra environment variable in KEY=VALUE format (can be repeated).", + ) + args = parser.parse_args() + + wheel_file = single_wheel_in(args.wheel) if args.wheel.is_dir() else args.wheel + args.out_wheel_dir.mkdir(parents=True, exist_ok=True) + + env = scrub_bazel_env(dict(os.environ)) + env["WHEEL_FILE"] = str(wheel_file.absolute()) + env["WHEEL_OUTPUT_ROOT"] = str(args.out_wheel_dir.absolute()) + + for env_entry in args.env: + key, sep, value = env_entry.partition("=") + if not sep or not key: + raise ValueError(f"Invalid --env entry '{env_entry}', expected KEY=VALUE") + env[key] = value + + subprocess.check_call([os.path.abspath(args.tool)], env=env) + single_wheel_in(args.out_wheel_dir, check_stray=True) + + +if __name__ == "__main__": + main() diff --git a/python/private/pypi/whl_library_srcs.bzl b/python/private/pypi/whl_library_srcs.bzl index 02856ec7f8..063ef02352 100644 --- a/python/private/pypi/whl_library_srcs.bzl +++ b/python/private/pypi/whl_library_srcs.bzl @@ -1,5 +1,6 @@ """Macro to generate all of the targets present in a {obj}`whl_library`.""" +load("@bazel_skylib//lib:types.bzl", "types") load("@bazel_skylib//rules:copy_file.bzl", "copy_file") load("//python:py_library.bzl", "py_library") load(":gen_wheel_record.bzl", "gen_wheel_record") @@ -13,6 +14,7 @@ load( "WHEEL_FILE", ) load(":namespace_pkgs.bzl", _create_inits = "create_inits") +load(":py_wheel_extract_files.bzl", "py_wheel_extract_files", "wheel_glob") load(":py_wheel_library.bzl", "py_wheel_library") load(":venv_entry_point.bzl", "venv_entry_point") load(":venv_rewrite_shebang.bzl", "venv_rewrite_shebang") @@ -65,43 +67,119 @@ def _add_copied_files_and_wheel_file( visibility = visibility, ) +def _is_wheel_internal_path(src, extracted_files, shebang_scripts): + if src.startswith(("@", "//", ":")): + return False + if src.startswith(("site-packages/", "data/", "bin/", "include/")): + return True + if src in extracted_files: + return True + for s in shebang_scripts: + if src == "bin/" + s or src == "bin/" + s + ".bat": + return True + return False + def _validate_action_install_args( name, *, filegroups, - copy_files, - copy_executables, extracted_files, shebang_scripts, _fail): - if filegroups != None: + if filegroups != None and not extracted_files and not shebang_scripts: _fail( ( "In '{}', custom glob-based 'filegroups' ({}) are not supported with experimental_action_install " + - "because wheel contents are extracted into the ':srcs' TreeArtifact during the build phase." + "unless wheel file paths are known at loading time (or use py_wheel_extract_files on downloaded wheels)." ).format(name, ", ".join(sorted(filegroups.keys()))), ) return False + return True - wheel_internal_srcs = {p: True for p in extracted_files} - for s in shebang_scripts: - wheel_internal_srcs["bin/" + s] = True - wheel_internal_srcs["bin/" + s + ".bat"] = True - bad_copy_srcs = sorted([ - src - for src in list(copy_files.keys()) + list(copy_executables.keys()) - if src in wheel_internal_srcs - ]) - if bad_copy_srcs: - _fail( - ( - "In '{}', 'copy_files'/'copy_executables' sources ({}) reference wheel-extracted paths, " + - "which are not available as repository files with experimental_action_install because wheel " + - "contents are extracted into the ':srcs' TreeArtifact during the build phase." - ).format(name, ", ".join(bad_copy_srcs)), +def _add_action_install_copies( + *, + rules, + native, + copy_files, + copy_executables, + all_wheel_files, + extracted_files, + shebang_scripts, + wheel_install_target, + extract_state, + visibility, + data, + _fail): + can_extract_internal = hasattr(rules, "py_wheel_extract_files") + for is_exec, copies in [(False, copy_files), (True, copy_executables)]: + for src, dest in copies.items(): + if can_extract_internal and _is_wheel_internal_path(src, extracted_files, shebang_scripts): + files_for_src = all_wheel_files if src in all_wheel_files else [src] + copy_src = wheel_glob( + [src], + allow_empty = False, + files = files_for_src, + wheel_library = ":" + wheel_install_target, + is_executable = is_exec, + native = native, + extract_rule = rules.py_wheel_extract_files, + _state = extract_state, + _fail = _fail, + )[0] + else: + copy_src = src + copy_kwargs = dict( + name = dest + ".copy", + src = copy_src, + out = dest, + visibility = visibility, + ) + if is_exec: + copy_kwargs["is_executable"] = True + rules.copy_file(**copy_kwargs) + data.append(dest) + +def _add_action_install_custom_filegroups( + *, + filegroups, + rules, + native, + all_wheel_files, + wheel_install_target, + extract_state, + bins_for_data_label, + visibility, + _fail): + if filegroups == None: + return + for fg_name, glob_spec in sorted(filegroups.items()): + if types.is_list(glob_spec): + fg_include = glob_spec + fg_exclude = [] + else: + fg_include = glob_spec.get("include", []) + fg_exclude = glob_spec.get("exclude", []) + fg_srcs = ( + wheel_glob( + fg_include, + exclude = fg_exclude, + allow_empty = True, + files = all_wheel_files, + wheel_library = ":" + wheel_install_target, + native = native, + extract_rule = rules.py_wheel_extract_files, + _state = extract_state, + _fail = _fail, + ) if hasattr(rules, "py_wheel_extract_files") else [] ) - return False - return True + if fg_name == DATA_LABEL: + fg_srcs = fg_srcs + bins_for_data_label + if hasattr(native, "filegroup"): + native.filegroup( + name = fg_name, + srcs = fg_srcs, + visibility = visibility, + ) def whl_library_srcs( *, @@ -128,6 +206,7 @@ def whl_library_srcs( rules = struct( copy_file = copy_file, py_library = py_library, + py_wheel_extract_files = py_wheel_extract_files, py_wheel_library = py_wheel_library, venv_entry_point = venv_entry_point, venv_rewrite_shebang = venv_rewrite_shebang, @@ -174,8 +253,6 @@ def whl_library_srcs( if action_install and not _validate_action_install_args( name, filegroups = filegroups, - copy_files = copy_files, - copy_executables = copy_executables, extracted_files = extracted_files, shebang_scripts = shebang_scripts, _fail = _fail, @@ -195,42 +272,93 @@ def whl_library_srcs( data.append(ep_target_name) if action_install: - _add_copied_files_and_wheel_file( + all_wheel_files = list(extracted_files) + for s in shebang_scripts: + bin_s = "bin/" + s + if bin_s not in all_wheel_files: + all_wheel_files.append(bin_s) + + wheel_install_target = "_wheel_install" + extract_state = {} + + _add_action_install_copies( rules = rules, native = native, copy_files = copy_files, copy_executables = copy_executables, - whl_file = whl_file, - name = name, + all_wheel_files = all_wheel_files, + extracted_files = extracted_files, + shebang_scripts = shebang_scripts, + wheel_install_target = wheel_install_target, + extract_state = extract_state, visibility = visibility, data = data, + _fail = _fail, ) + + if hasattr(native, "filegroup"): + native.filegroup( + name = WHEEL_FILE, + srcs = [whl_file or name], + visibility = visibility, + ) + + _add_action_install_custom_filegroups( + filegroups = filegroups, + rules = rules, + native = native, + all_wheel_files = all_wheel_files, + wheel_install_target = wheel_install_target, + extract_state = extract_state, + bins_for_data_label = bins_for_data_label, + visibility = visibility, + _fail = _fail, + ) + if hasattr(native, "filegroup"): for fg_name, fg_srcs in [ (EXTRACTED_WHEEL_FILES, [PY_SRCS_LABEL]), (DIST_INFO_LABEL, ["entry_points.txt"] if has_entry_points_txt else []), (DATA_LABEL, [PY_SRCS_LABEL] + bins_for_data_label), ]: + if filegroups != None and fg_name in filegroups: + continue native.filegroup( name = fg_name, srcs = fg_srcs, visibility = visibility, ) + if hasattr(rules, "py_wheel_library"): - rules.py_wheel_library( - name = PY_SRCS_LABEL, - wheel = whl_file or name, + common_wheel_kwargs = dict( extracted_files = extracted_files, shebang_scripts = shebang_scripts, namespace_package_files = namespace_package_files, srcs_exclude = srcs_exclude, data_exclude = data_exclude, enable_implicit_namespace_pkgs = enable_implicit_namespace_pkgs, - data = data, tags = tags, - visibility = visibility, experimental_venvs_site_packages = _VENV_SITE_PACKAGES_FLAG, ) + + # NOTE: `_wheel_install` is an internal implementation detail exposed with + # `visibility` solely so `:wheel_files.bzl` (`wheel_glob`) can reference it + # when loaded from external packages. Do not depend on `:_wheel_install` + # directly; depend on `:srcs` (or `:pkg`) instead. + rules.py_wheel_library( + name = wheel_install_target, + wheel = whl_file or name, + data = [], + visibility = visibility, + **common_wheel_kwargs + ) + rules.py_wheel_library( + name = PY_SRCS_LABEL, + wheel = ":" + wheel_install_target, + data = data, + visibility = visibility, + **common_wheel_kwargs + ) return existing_bin_names = {ep["name"].lower(): None for ep in entry_points.values()} @@ -263,25 +391,30 @@ def whl_library_srcs( ) data.append(record_target_name) - if filegroups == None: - filegroups = { - EXTRACTED_WHEEL_FILES: dict( - include = ["**"], - # The Bazel repo files are always excluded; only the sdist - # filename is conditional on `sdist_filename`. - exclude = _BAZEL_REPO_FILE_GLOBS + ( - [sdist_filename] if sdist_filename else [] - ), - ), - DIST_INFO_LABEL: dict( - include = ["site-packages/*.dist-info/**"], + default_filegroups = { + EXTRACTED_WHEEL_FILES: dict( + include = ["**"], + # The Bazel repo files are always excluded; only the sdist + # filename is conditional on `sdist_filename`. + exclude = _BAZEL_REPO_FILE_GLOBS + ( + [sdist_filename] if sdist_filename else [] ), - DATA_LABEL: dict( - include = ["data/**", "bin/**", "include/**"], - ), - } + ), + DIST_INFO_LABEL: dict( + include = ["site-packages/*.dist-info/**"], + ), + DATA_LABEL: dict( + include = ["data/**", "bin/**", "include/**"], + ), + } + if filegroups == None: + filegroups = default_filegroups + elif filegroups: + filegroups = default_filegroups | filegroups for filegroup_name, glob_kwargs in filegroups.items(): + if types.is_list(glob_kwargs): + glob_kwargs = {"include": glob_kwargs} glob_kwargs = {"allow_empty": True} | glob_kwargs srcs = native.glob(**glob_kwargs) if filegroup_name == DATA_LABEL: diff --git a/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl b/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl index 826efe60d5..07c0b8d5f4 100644 --- a/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl +++ b/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl @@ -15,7 +15,11 @@ "" load("@rules_testing//lib:test_suite.bzl", "test_suite") -load("//python/private/pypi:generate_whl_library_build_bazel.bzl", "generate_whl_library_build_bazel") # buildifier: disable=bzl-visibility +load( + "//python/private/pypi:generate_whl_library_build_bazel.bzl", + "generate_wheel_files_bzl", + "generate_whl_library_build_bazel", +) # buildifier: disable=bzl-visibility _tests = [] @@ -354,7 +358,11 @@ def _test_action_install_glob_warning(env): (True, 'filegroup(name = "hdrs", srcs = glob(["site-packages/**/*.h"]))', True), (True, 'load("//bazel:pip_parse_targets.bzl", "define_targets")\ndefine_targets()', False), (False, 'filegroup(name = "hdrs", srcs = glob(["site-packages/**/*.h"]))', False), - (True, '# never use glob(["*.h"]) here\npy_library(name = "extra")', False), + ( + True, + '# never use glob(["*.h"]) here\nload("@rules_python//python:pip.bzl", "wheel_glob")\nfilegroup(name = "hdrs", srcs = wheel_glob(["site-packages/**/*.h"]))', + False, + ), (True, 'filegroup(name = "hdrs", srcs = glob (["site-packages/**/*.h"]))', True), ]: warnings = [] @@ -378,10 +386,69 @@ def _test_action_install_glob_warning(env): ) env.expect.that_int(len(warnings)).equals(1 if want_warn else 0) if want_warn: - env.expect.that_str(warnings[0]).contains( + for substr in ( "may glob wheel contents; globs match nothing under experimental_action_install", - ) - env.expect.that_str(warnings[0]).contains("':srcs' TreeArtifact") + "wheel_glob()", + "py_wheel_headers", + "py_wheel_transform", + "post_install_patches", + "py_wheel_extract_files", + ): + env.expect.that_str(warnings[0]).contains(substr) + + # wheel_glob( in additive_build_content auto-loads wheel_glob and does not warn. + wheel_glob_warnings = [] + wheel_glob_build = generate_whl_library_build_bazel( + metadata_version = "0", + metadata_name = "foo", + dep_template = "@pypi//{name}:{target}", + name = "foo.whl", + config_load = "@pypi//:config.bzl", + action_install = True, + extracted_files = ["site-packages/foo/libfoo.so"], + annotation = struct( + copy_files = {}, + copy_executables = {}, + data = [], + data_exclude_glob = [], + srcs_exclude_glob = [], + additive_build_content = 'filegroup(name = "libs", srcs = wheel_glob(["site-packages/**/*.so"]))', + ), + logger = struct(warn = wheel_glob_warnings.append), + ) + env.expect.that_int(len(wheel_glob_warnings)).equals(0) + env.expect.that_str(wheel_glob_build).contains( + 'load("@rules_python//python/private/pypi:py_wheel_extract_files.bzl", "wheel_glob")', + ) + + wheel_files_bzl = generate_wheel_files_bzl([ + "site-packages/foo/__init__.py", + "site-packages/foo/libfoo.so", + ]) + env.expect.that_str(wheel_files_bzl).contains('"site-packages/foo/libfoo.so"') + env.expect.that_str(wheel_files_bzl).contains("def wheel_glob(") + env.expect.that_str(wheel_files_bzl).contains('wheel_library = Label("//:_wheel_install")') + env.expect.that_str(wheel_files_bzl).contains("is_executable = False") + + # Classic mode also auto-loads wheel_glob when additive_build_content uses wheel_glob(. + classic_wheel_glob_build = generate_whl_library_build_bazel( + metadata_version = "0", + metadata_name = "foo", + dep_template = "@pypi//{name}:{target}", + name = "foo.whl", + config_load = "@pypi//:config.bzl", + annotation = struct( + copy_files = {}, + copy_executables = {}, + data = [], + data_exclude_glob = [], + srcs_exclude_glob = [], + additive_build_content = 'filegroup(name = "libs", srcs = wheel_glob(["site-packages/**/*.so"]))', + ), + ) + env.expect.that_str(classic_wheel_glob_build).contains( + 'load("@rules_python//python/private/pypi:py_wheel_extract_files.bzl", "wheel_glob")', + ) _tests.append(_test_action_install_glob_warning) diff --git a/tests/pypi/py_wheel_library/BUILD.bazel b/tests/pypi/py_wheel_library/BUILD.bazel index 6f29a887a2..80f11308e0 100644 --- a/tests/pypi/py_wheel_library/BUILD.bazel +++ b/tests/pypi/py_wheel_library/BUILD.bazel @@ -1,4 +1,19 @@ +load("@bazel_skylib//rules:copy_file.bzl", "copy_file") +load("@rules_cc//cc:cc_import.bzl", "cc_import") +load("@rules_cc//cc:cc_test.bzl", "cc_test") +load("@rules_shell//shell:sh_binary.bzl", "sh_binary") +load("//python:py_binary.bzl", "py_binary") load("//python:py_test.bzl", "py_test") +load( + "//python/private/pypi:py_wheel_extract_files.bzl", + "py_wheel_extract_files", + "wheel_glob", +) # buildifier: disable=bzl-visibility +load("//python/private/pypi:py_wheel_headers.bzl", "py_wheel_headers") # buildifier: disable=bzl-visibility +load("//python/private/pypi:py_wheel_library.bzl", "py_wheel_library") # buildifier: disable=bzl-visibility +load("//python/private/pypi:py_wheel_transform.bzl", "py_wheel_transform") # buildifier: disable=bzl-visibility +load("//tests/pypi/py_wheel_library/spoke_pkg:wheel_files.bzl", spoke_wheel_glob = "wheel_glob") +load("//tests/support:py_reconfig.bzl", "py_reconfig_test") load(":py_wheel_library_bzl_tests.bzl", "py_wheel_library_bzl_test_suite") py_test( @@ -10,3 +25,300 @@ py_test( py_wheel_library_bzl_test_suite( name = "py_wheel_library_bzl_tests", ) + +py_binary( + name = "make_test_wheel", + srcs = ["make_test_wheel.py"], + main = "make_test_wheel.py", +) + +genrule( + name = "gen_demo_whl", + outs = ["demo_pkg-1.2.3-py3-none-any.whl"], + cmd = "$(execpath :make_test_wheel) $@", + tools = [":make_test_wheel"], + visibility = ["//visibility:public"], +) + +sh_binary( + name = "sh_transform", + srcs = ["sh_transform.sh"], +) + +py_binary( + name = "transform_wheel", + srcs = ["transform_wheel.py"], + main = "transform_wheel.py", +) + +py_wheel_transform( + name = "step1_transformed_demo_whl", + env = {"EXPECTED_SH_ENV": "from_transform"}, + transform = ":sh_transform", + wheel = ":gen_demo_whl", +) + +py_wheel_transform( + name = "transformed_demo_whl", + data = ["marker.txt"], + env = {"DATA_MARKER_FILE": "$(execpath marker.txt)"}, + transform = ":transform_wheel", + wheel = ":step1_transformed_demo_whl", +) + +_DEMO_EXTRACTED_FILES = [ + "site-packages/bad_top_mod.py", + "site-packages/demo_pkg-1.2.3.dist-info/METADATA", + "site-packages/demo_pkg/__init__.py", + "site-packages/demo_pkg/include/demo_header.h", + "site-packages/demo_pkg/lib/libdemo.so", +] + +py_wheel_library( + name = "demo_wheel_lib", + extracted_files = _DEMO_EXTRACTED_FILES, + post_install_patch_strip = 1, + post_install_patches = ["post_install.patch"], + wheel = ":transformed_demo_whl", +) + +py_wheel_library( + name = "demo_wheel_lib_venv", + experimental_venvs_site_packages = "//python/config_settings:venvs_site_packages", + extracted_files = _DEMO_EXTRACTED_FILES, + post_install_patch_strip = 1, + post_install_patches = ["post_install.patch"], + tags = [ + "pypi_name=demo-pkg", + "pypi_version=1.2.3", + ], + wheel = ":transformed_demo_whl", +) + +py_wheel_headers( + name = "demo_headers", + include_dirs = ["site-packages/demo_pkg/include"], + wheel_library = ":demo_wheel_lib", +) + +py_wheel_headers( + name = "demo_headers_root_default", + wheel_library = ":demo_wheel_lib", +) + +py_wheel_extract_files( + name = "extracted_patched_init", + paths = ["site-packages/demo_pkg/__init__.py"], + wheel_library = ":demo_wheel_lib", +) + +copy_file( + name = "copied_patched_init_copy", + src = ":extracted_patched_init", + out = "copied_patched_init.py", +) + +py_wheel_extract_files( + name = "extracted_exec_script", + is_executable = True, + paths = ["site-packages/demo_pkg/__init__.py"], + wheel_library = ":demo_wheel_lib", +) + +copy_file( + name = "copied_exec_script_copy", + src = ":extracted_exec_script", + out = "copied_exec_script.py", + is_executable = True, +) + +py_wheel_extract_files( + name = "extracted_fg_files", + paths = [ + "site-packages/demo_pkg/__init__.py", + "site-packages/demo_pkg/include/demo_header.h", + ], + wheel_library = ":demo_wheel_lib", +) + +_LIBDEMO_MATCHES = wheel_glob( + [ + "site-packages/demo_pkg/lib/libdemo.so", + "site-packages/demo_pkg/lib/libdemo.dylib", + ], + files = _DEMO_EXTRACTED_FILES, + wheel_library = ":demo_wheel_lib", +) + +cc_import( + name = "demo_shared_lib", + shared_library = _LIBDEMO_MATCHES[0] if len(_LIBDEMO_MATCHES) == 1 else fail("Expected 1 match"), +) + +# Second wheel_glob call in the same package with overlapping match (libdemo.so) +# to verify package-level de-duplication across calls. +_OVERLAPPING_GLOB_MATCHES = wheel_glob( + [ + "site-packages/demo_pkg/lib/libdemo.*", + "site-packages/demo_pkg/include/*.h", + ], + files = _DEMO_EXTRACTED_FILES, + wheel_library = ":demo_wheel_lib", +) + +# Cross-package wheel_files.bzl call using default wheel_library = Label("//...:_wheel_install"). +_CROSS_PKG_METADATA = spoke_wheel_glob([ + "site-packages/demo_pkg-1.2.3.dist-info/METADATA", +]) + +filegroup( + name = "custom_extracted_fg", + srcs = [":extracted_fg_files"] + _OVERLAPPING_GLOB_MATCHES + _CROSS_PKG_METADATA, +) + +cc_test( + name = "headers_test", + srcs = ["headers_test.cc"], + data = [":demo_shared_lib"], + deps = [ + ":demo_headers", + ":demo_headers_root_default", + ], +) + +py_test( + name = "py_wheel_library_test", + srcs = ["py_wheel_library_test.py"], + data = [ + "copied_exec_script.py", + "copied_patched_init.py", + ":custom_extracted_fg", + ], + env = { + "COPIED_EXEC_SCRIPT": "$(rootpath copied_exec_script.py)", + "COPIED_PATCHED_INIT": "$(rootpath copied_patched_init.py)", + "EXPECT_PRECOMPILE": "0", + }, + deps = [ + ":demo_wheel_lib", + ], +) + +py_reconfig_test( + name = "py_wheel_library_venv_test", + srcs = ["py_wheel_library_test.py"], + bootstrap_impl = "script", + data = [ + "copied_exec_script.py", + "copied_patched_init.py", + ":custom_extracted_fg", + ], + env = { + "COPIED_EXEC_SCRIPT": "$(rootpath copied_exec_script.py)", + "COPIED_PATCHED_INIT": "$(rootpath copied_patched_init.py)", + "EXPECT_PRECOMPILE": "0", + "EXPECT_VENV_SITE_PACKAGES": "1", + }, + main = "py_wheel_library_test.py", + venvs_site_packages = "yes", + deps = [ + ":demo_wheel_lib_venv", + ], +) + +py_reconfig_test( + name = "py_wheel_library_precompile_enabled_test", + srcs = ["py_wheel_library_test.py"], + data = [ + "copied_exec_script.py", + "copied_patched_init.py", + ":custom_extracted_fg", + ], + env = { + "COPIED_EXEC_SCRIPT": "$(rootpath copied_exec_script.py)", + "COPIED_PATCHED_INIT": "$(rootpath copied_patched_init.py)", + "EXPECT_PRECOMPILE": "1", + }, + main = "py_wheel_library_test.py", + precompile_flag = "enabled", + deps = [ + ":demo_wheel_lib", + ], +) + +py_reconfig_test( + name = "py_wheel_library_venv_precompile_test", + srcs = ["py_wheel_library_test.py"], + bootstrap_impl = "script", + data = [ + "copied_exec_script.py", + "copied_patched_init.py", + ":custom_extracted_fg", + ], + env = { + "COPIED_EXEC_SCRIPT": "$(rootpath copied_exec_script.py)", + "COPIED_PATCHED_INIT": "$(rootpath copied_patched_init.py)", + "EXPECT_PRECOMPILE": "1", + "EXPECT_VENV_SITE_PACKAGES": "1", + }, + main = "py_wheel_library_test.py", + precompile_flag = "enabled", + venvs_site_packages = "yes", + deps = [ + ":demo_wheel_lib_venv", + ], +) + +py_wheel_library( + name = "demo_wheel_lib_inner_nopc", + experimental_venvs_site_packages = "//python/config_settings:venvs_site_packages", + extracted_files = _DEMO_EXTRACTED_FILES, + precompile = "disabled", + tags = [ + "pypi_name=demo-pkg", + "pypi_version=1.2.3", + ], + wheel = ":transformed_demo_whl", +) + +py_wheel_library( + name = "demo_wheel_lib_reuse_omit", + experimental_venvs_site_packages = "//python/config_settings:venvs_site_packages", + extracted_files = _DEMO_EXTRACTED_FILES, + precompile_source_retention = "omit_source", + tags = [ + "pypi_name=demo-pkg", + "pypi_version=1.2.3", + ], + wheel = ":demo_wheel_lib_inner_nopc", +) + +py_wheel_extract_files( + name = "extracted_from_omit_source", + paths = ["site-packages/demo_pkg/__init__.py"], + wheel_library = ":demo_wheel_lib_reuse_omit", +) + +py_reconfig_test( + name = "py_wheel_library_venv_reuse_omit_test", + srcs = ["py_wheel_library_test.py"], + bootstrap_impl = "script", + data = [ + "copied_exec_script.py", + "copied_patched_init.py", + ":custom_extracted_fg", + ":extracted_from_omit_source", + ], + env = { + "COPIED_EXEC_SCRIPT": "$(rootpath copied_exec_script.py)", + "COPIED_PATCHED_INIT": "$(rootpath copied_patched_init.py)", + "EXPECT_OMIT_SOURCE": "1", + "EXPECT_VENV_SITE_PACKAGES": "1", + }, + main = "py_wheel_library_test.py", + precompile_flag = "enabled", + venvs_site_packages = "yes", + deps = [ + ":demo_wheel_lib_reuse_omit", + ], +) diff --git a/tests/pypi/py_wheel_library/headers_test.cc b/tests/pypi/py_wheel_library/headers_test.cc new file mode 100644 index 0000000000..7e51f26b8a --- /dev/null +++ b/tests/pypi/py_wheel_library/headers_test.cc @@ -0,0 +1,6 @@ +#include "demo_header.h" +#include "demo_pkg/include/demo_header.h" + +int main() { + return DEMO_MAGIC_NUMBER == 42 ? 0 : 1; +} diff --git a/tests/pypi/py_wheel_library/make_test_wheel.py b/tests/pypi/py_wheel_library/make_test_wheel.py new file mode 100644 index 0000000000..aeff93412b --- /dev/null +++ b/tests/pypi/py_wheel_library/make_test_wheel.py @@ -0,0 +1,57 @@ +"""Generate a synthetic wheel for testing py_wheel_library, py_wheel_headers, and py_wheel_transform.""" + +from __future__ import annotations + +import sys +import zipfile +from pathlib import Path + + +def _write_entry(zf: zipfile.ZipFile, name: str, content: str) -> None: + info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) + info.external_attr = 0o644 << 16 + zf.writestr(info, content.encode("utf-8")) + + +def main() -> None: + out_whl = Path(sys.argv[1]) + with zipfile.ZipFile(out_whl, "w") as zf: + _write_entry( + zf, + "demo_pkg-1.2.3.dist-info/METADATA", + "Metadata-Version: 2.1\nName: demo-pkg\nVersion: 1.2.3\n", + ) + _write_entry( + zf, + "demo_pkg-1.2.3.dist-info/WHEEL", + "Wheel-Version: 1.0\nGenerator: test\nRoot-Is-Purelib: true\nTag: py3-none-any\n", + ) + _write_entry( + zf, + "demo_pkg-1.2.3.dist-info/RECORD", + "bad_top_mod.py,sha256=old,10\ndemo_pkg/__init__.py,sha256=old,10\ndemo_pkg/lib/libdemo.so,sha256=old,10\n", + ) + _write_entry( + zf, + "bad_top_mod.py", + "print 'py2 syntax'\n", + ) + _write_entry( + zf, + "demo_pkg/__init__.py", + 'VALUE = "original"\nTRANSFORMED = False\n', + ) + _write_entry( + zf, + "demo_pkg/include/demo_header.h", + "#ifndef DEMO_HEADER_H\n#define DEMO_HEADER_H\n#define DEMO_MAGIC_NUMBER 42\n#endif\n", + ) + _write_entry( + zf, + "demo_pkg/lib/libdemo.so", + "fake_shared_library_bytes", + ) + + +if __name__ == "__main__": + main() diff --git a/tests/pypi/py_wheel_library/marker.txt b/tests/pypi/py_wheel_library/marker.txt new file mode 100644 index 0000000000..5636b2e64f --- /dev/null +++ b/tests/pypi/py_wheel_library/marker.txt @@ -0,0 +1 @@ +custom_marker diff --git a/tests/pypi/py_wheel_library/post_install.patch b/tests/pypi/py_wheel_library/post_install.patch new file mode 100644 index 0000000000..0018d1aea5 --- /dev/null +++ b/tests/pypi/py_wheel_library/post_install.patch @@ -0,0 +1,6 @@ +--- a/demo_pkg/__init__.py ++++ b/demo_pkg/__init__.py +@@ -1,2 +1,2 @@ +-VALUE = "original" ++VALUE = "patched_in_action" + TRANSFORMED = "custom_marker" diff --git a/tests/pypi/py_wheel_library/py_wheel_library_test.py b/tests/pypi/py_wheel_library/py_wheel_library_test.py new file mode 100644 index 0000000000..f6c33be20a --- /dev/null +++ b/tests/pypi/py_wheel_library/py_wheel_library_test.py @@ -0,0 +1,78 @@ +"""Tests for py_wheel_library post_install_patches, py_wheel_transform, py_wheel_extract_files, and precompile.""" + +from __future__ import annotations + +import importlib +import importlib.metadata +import importlib.util +import os +import pathlib +import sys +import unittest + + +class PyWheelLibraryTest(unittest.TestCase): + def test_post_install_patch_and_transform(self): + sys.dont_write_bytecode = True + demo_pkg = importlib.import_module("demo_pkg") + expect_omit = os.environ.get("EXPECT_OMIT_SOURCE") == "1" + if not expect_omit: + self.assertEqual(demo_pkg.VALUE, "patched_in_action") + self.assertEqual(demo_pkg.TRANSFORMED, "custom_marker") + self.assertEqual(importlib.metadata.version("demo-pkg"), "1.2.3") + expect_venv = os.environ.get("EXPECT_VENV_SITE_PACKAGES") == "1" + pkg_file = pathlib.Path(demo_pkg.__file__ or "") + self.assertEqual( + pkg_file.is_relative_to(sys.prefix), + expect_venv, + ) + + if expect_omit: + self.assertEqual(pkg_file.suffix, ".pyc") + self.assertFalse(pkg_file.with_suffix(".py").exists()) + else: + # Verify precompile flag-driven behavior (__pycache__/*.pyc presence). + pyc_files = list((pkg_file.parent / "__pycache__").glob("*.pyc")) + if os.environ.get("EXPECT_PRECOMPILE") == "1": + self.assertTrue( + pyc_files, + f"Expected precompiled .pyc in {pkg_file.parent / '__pycache__'}", + ) + spec = demo_pkg.__spec__ + assert spec is not None + cached = pathlib.Path(spec.cached or "") + self.assertTrue(cached.is_file(), f"Missing cached pyc: {cached}") + self.assertEqual(cached.read_bytes()[:4], importlib.util.MAGIC_NUMBER) + if expect_venv: + self.assertTrue(cached.is_symlink(), f"Expected symlink: {cached}") + else: + self.assertEqual(pyc_files, []) + + # Verify an uncompilable top-level module raises SyntaxError on import + # and never leaves dangling symlinks in the venv site-packages tree. + with self.assertRaises(SyntaxError): + importlib.import_module("bad_top_mod") + if expect_venv: + site_packages_dir = pkg_file.parent.parent + for entry in site_packages_dir.rglob("*"): + if entry.is_symlink(): + self.assertTrue( + entry.exists(), + f"Dangling venv symlink in site-packages: {entry} -> {os.readlink(entry)}", + ) + + # Verify py_wheel_extract_files + copy_files reflects post_install_patch + # and copy_executables preserves executable bit. + copied_init = pathlib.Path(os.environ["COPIED_PATCHED_INIT"]) + self.assertTrue(copied_init.is_file()) + copied_text = copied_init.read_text(encoding="utf-8") + self.assertIn('VALUE = "patched_in_action"', copied_text) + self.assertIn('TRANSFORMED = "custom_marker"', copied_text) + + copied_exec = pathlib.Path(os.environ["COPIED_EXEC_SCRIPT"]) + self.assertTrue(copied_exec.is_file()) + self.assertTrue(os.access(copied_exec, os.X_OK)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/pypi/py_wheel_library/sh_transform.sh b/tests/pypi/py_wheel_library/sh_transform.sh new file mode 100755 index 0000000000..d72469ae01 --- /dev/null +++ b/tests/pypi/py_wheel_library/sh_transform.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash + +set -euo pipefail + +if [[ -z "${PATH:-}" ]]; then + echo "ERROR: PATH is missing in sh_binary transform" >&2 + exit 1 +fi +if [[ "${EXPECTED_SH_ENV:-}" != "from_transform" ]]; then + echo "ERROR: EXPECTED_SH_ENV not forwarded: ${EXPECTED_SH_ENV:-}" >&2 + exit 1 +fi +for var in RUNFILES_DIR RUNFILES_MANIFEST_FILE PYTHONSAFEPATH PYTHONPATH PYTHONHOME; do + if [[ -n "${!var:-}" ]]; then + echo "ERROR: wrapper ${var} leaked into sh_binary transform: ${!var}" >&2 + exit 1 + fi +done + +cp "${WHEEL_FILE}" "${WHEEL_OUTPUT_ROOT}/$(basename "${WHEEL_FILE}")" diff --git a/tests/pypi/py_wheel_library/spoke_pkg/BUILD.bazel b/tests/pypi/py_wheel_library/spoke_pkg/BUILD.bazel new file mode 100644 index 0000000000..ded7332c8b --- /dev/null +++ b/tests/pypi/py_wheel_library/spoke_pkg/BUILD.bazel @@ -0,0 +1,35 @@ +load("@bazel_skylib//rules:diff_test.bzl", "diff_test") +load("@bazel_skylib//rules:write_file.bzl", "write_file") +load("//python/private/pypi:generate_whl_library_build_bazel.bzl", "generate_wheel_files_bzl") # buildifier: disable=bzl-visibility +load("//python/private/pypi:whl_library_srcs.bzl", "whl_library_srcs") # buildifier: disable=bzl-visibility +load(":wheel_files.bzl", "FILES") + +whl_library_srcs( + name = "//tests/pypi/py_wheel_library:gen_demo_whl", + action_install = True, + extracted_files = FILES, + tags = [ + "pypi_name=demo-pkg", + "pypi_version=1.2.3", + ], +) + +write_file( + name = "gen_expected_wheel_files_bzl", + out = "expected_wheel_files.bzl", + content = [ + generate_wheel_files_bzl(FILES) + .replace("@rules_python//", "//") + .replace( + 'Label("//:_wheel_install")', + 'Label("//tests/pypi/py_wheel_library/spoke_pkg:_wheel_install")', + ), + ], + newline = "unix", +) + +diff_test( + name = "wheel_files_bzl_sync_test", + file1 = "wheel_files.bzl", + file2 = ":gen_expected_wheel_files_bzl", +) diff --git a/tests/pypi/py_wheel_library/spoke_pkg/wheel_files.bzl b/tests/pypi/py_wheel_library/spoke_pkg/wheel_files.bzl new file mode 100644 index 0000000000..ab2f46c1ce --- /dev/null +++ b/tests/pypi/py_wheel_library/spoke_pkg/wheel_files.bzl @@ -0,0 +1,30 @@ +"""Generated wheel file list and wheel_glob wrapper.""" + +load("//python/private/pypi:py_wheel_extract_files.bzl", _wheel_glob = "wheel_glob") # buildifier: disable=bzl-visibility + +FILES = [ + "site-packages/bad_top_mod.py", + "site-packages/demo_pkg-1.2.3.dist-info/METADATA", + "site-packages/demo_pkg/__init__.py", + "site-packages/demo_pkg/include/demo_header.h", + "site-packages/demo_pkg/lib/libdemo.so", +] + +def wheel_glob( + include, + exclude = [], + exclude_directories = 1, + allow_empty = True, + *, + wheel_library = Label("//tests/pypi/py_wheel_library/spoke_pkg:_wheel_install"), + is_executable = False): + """Glob over wheel files in this repository.""" + return _wheel_glob( + include = include, + exclude = exclude, + exclude_directories = exclude_directories, + allow_empty = allow_empty, + files = FILES, + wheel_library = wheel_library, + is_executable = is_executable, + ) diff --git a/tests/pypi/py_wheel_library/transform_wheel.py b/tests/pypi/py_wheel_library/transform_wheel.py new file mode 100644 index 0000000000..e6ea63b07b --- /dev/null +++ b/tests/pypi/py_wheel_library/transform_wheel.py @@ -0,0 +1,28 @@ +"""Transform tool for testing py_wheel_transform.""" + +from __future__ import annotations + +import os +import zipfile +from pathlib import Path + + +def main() -> None: + in_whl = Path(os.environ["WHEEL_FILE"]) + out_dir = Path(os.environ["WHEEL_OUTPUT_ROOT"]) + marker = Path(os.environ["DATA_MARKER_FILE"]).read_text(encoding="utf-8").strip() + out_whl = out_dir / in_whl.name + + with zipfile.ZipFile(in_whl, "r") as zin, zipfile.ZipFile(out_whl, "w") as zout: + for item in zin.infolist(): + data = zin.read(item.filename) + if item.filename == "demo_pkg/__init__.py": + text = data.decode("utf-8").replace( + "TRANSFORMED = False", f'TRANSFORMED = "{marker}"' + ) + data = text.encode("utf-8") + zout.writestr(item, data) + + +if __name__ == "__main__": + main() diff --git a/tests/pypi/py_wheel_library/wheel_layout_and_installer_test.py b/tests/pypi/py_wheel_library/wheel_layout_and_installer_test.py index 6e8a9137f2..51f2ff97aa 100644 --- a/tests/pypi/py_wheel_library/wheel_layout_and_installer_test.py +++ b/tests/pypi/py_wheel_library/wheel_layout_and_installer_test.py @@ -15,7 +15,9 @@ import action_whl_installer import inspect_whl +import wheel_files_extractor import wheel_layout +import wheel_transformer def _write_zip(path: pathlib.Path, entries: dict[str, bytes | str]) -> pathlib.Path: @@ -543,6 +545,312 @@ def test_precompile_syntax_error_and_custom_precompiler(self): ).is_file() ) + def test_patch_behavior_and_record_update(self): + with tempfile.TemporaryDirectory() as tmp: + root = pathlib.Path(tmp) + target = root / "pkg/mod.py" + target.parent.mkdir(parents=True) + + # 1. Stale context fails strictly. + target.write_bytes(b"line1 = 1\r\nline2 = 'changed'\r\n") + stale_patch = root / "stale.patch" + stale_patch.write_bytes( + b"--- a/pkg/mod.py\n" + b"+++ b/pkg/mod.py\n" + b"@@ -1,2 +1,2 @@\n" + b" line1 = 1\n" + b"-line2 = 'expected'\n" + b"+line2 = 'patched'\n" + ) + with self.assertRaisesRegex(ValueError, "context mismatch"): + wheel_layout.apply_unified_patch(root, stale_patch, strip=1) + + # 2. CRLF preservation on LF patch with strip=1. + target.write_bytes(b"line1 = 1\r\nline2 = 'expected'\r\n") + touched = wheel_layout.apply_unified_patch(root, stale_patch, strip=1) + self.assertEqual(touched, {"pkg/mod.py"}) + self.assertEqual(target.read_bytes(), b"line1 = 1\r\nline2 = 'patched'\r\n") + + # 3. Table-driven patch engine edge cases (positive & negative). + for name, init_files, patch_bytes, strip, expected in [ + ( + "u0_insert_and_no_newline_and_format_patch_footer", + {"pkg/f.py": b"a\n-- keep\nb"}, + b"--- a/pkg/f.py\n+++ b/pkg/f.py\n" + b"@@ -1,0 +2,1 @@\n+mid\n" + b"@@ -2,2 +3,1 @@\n--- keep\n b\n\\ No newline at end of file\n" + b"-- \n2.45.0\n", + 1, + {"pkg/f.py": b"a\nmid\nb"}, + ), + ( + "non_utf8_bytes", + {"pkg/bin.py": b"# \xff\xfe\nx = 1\n"}, + b"--- a/pkg/bin.py\n+++ b/pkg/bin.py\n@@ -1,2 +1,2 @@\n # \xff\xfe\n-x = 1\n+x = 2\n", + 1, + {"pkg/bin.py": b"# \xff\xfe\nx = 2\n"}, + ), + ( + "create_over_existing", + {"pkg/e.py": b"old\n"}, + b"--- /dev/null\n+++ b/pkg/e.py\n@@ -0,0 +1 @@\n+new\n", + 1, + "attempts to create existing file", + ), + ( + "partial_delete", + {"pkg/d.py": b"1\n2\n"}, + b"--- a/pkg/d.py\n+++ /dev/null\n@@ -1,1 +0,0 @@\n-1\n", + 1, + "did not consume entire file", + ), + ( + "out_of_order_hunks", + {"pkg/o.py": b"1\n2\n3\n"}, + b"--- a/pkg/o.py\n+++ b/pkg/o.py\n@@ -3,1 +3,1 @@\n-3\n+three\n@@ -1,1 +1,1 @@\n-1\n+one\n", + 1, + "context mismatch", + ), + ( + "traversal", + {}, + b"--- /dev/null\n+++ b/../../escape.py\n@@ -0,0 +1 @@\n+x = 1\n", + 1, + "escapes root", + ), + ( + "abs_path", + {}, + b"--- /dev/null\n+++ /abs/escape.py\n@@ -0,0 +1 @@\n+x = 1\n", + 0, + "Unsafe patch path", + ), + ( + "binary_patch", + {}, + b"GIT binary patch\nliteral 0\n", + 1, + "Unsupported binary or rename/copy", + ), + ( + "rename_directive", + {}, + b"rename from a/x.py\nrename to b/y.py\n", + 1, + "Unsupported binary or rename/copy", + ), + ( + "orphan_hunk_before_header", + {}, + b"@@ -1,1 +1,1 @@\n-a\n+b\n", + 1, + "Hunk without preceding", + ), + ( + "stray_body_line", + {"pkg/s.py": b"a\n"}, + b"--- a/pkg/s.py\n+++ b/pkg/s.py\n@@ -1,1 +1,1 @@\nSTRAY\n", + 1, + "Malformed hunk line", + ), + ( + "git_create_at_strip_0", + {}, + b"--- /dev/null\n+++ b/pkg/new.py\n@@ -0,0 +1 @@\n+x = 1\n", + 0, + r"patch looks git-formatted \(a/ b/ prefixes\); use strip=1", + ), + ( + "git_modify_at_strip_0", + {"pkg/m.py": b"x = 1\n"}, + b"--- a/pkg/m.py\n+++ b/pkg/m.py\n@@ -1,1 +1,1 @@\n-x = 1\n+x = 2\n", + 0, + r"patch looks git-formatted \(a/ b/ prefixes\); use strip=1", + ), + ]: + with self.subTest(case=name), tempfile.TemporaryDirectory() as case_tmp: + case_root = pathlib.Path(case_tmp) + for rel, data in init_files.items(): + p = case_root / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_bytes(data) + pf = case_root / "case.patch" + pf.write_bytes(patch_bytes) + if isinstance(expected, str): + with self.assertRaisesRegex(ValueError, expected): + wheel_layout.apply_unified_patch(case_root, pf, strip=strip) + else: + wheel_layout.apply_unified_patch(case_root, pf, strip=strip) + for rel, exp_bytes in expected.items(): + self.assertEqual((case_root / rel).read_bytes(), exp_bytes) + + # 4. RECORD update for modified and comma-containing paths. + dist_info = root / "pkg-1.0.dist-info" + dist_info.mkdir(parents=True, exist_ok=True) + comma_file = root / "pkg/a,b.py" + comma_file.write_bytes(b"X = 10\n") + (dist_info / "RECORD").write_text( + '"pkg/a,b.py",sha256=old,1\npkg/mod.py,sha256=keep,5\n', + encoding="utf-8", + ) + wheel_layout.update_record_for_touched_files( + root, "pkg-1.0.dist-info", {"pkg/a,b.py"} + ) + record_text = (dist_info / "RECORD").read_text(encoding="utf-8") + self.assertIn('"pkg/a,b.py",sha256=', record_text) + self.assertNotIn("sha256=old", record_text) + self.assertIn("pkg/mod.py,sha256=keep,5\n", record_text) + + # 5. Venv site-packages validation catches added/removed top-level entries. + whl = _write_zip( + root / "vcheck-1.0-py3-none-any.whl", + { + "vcheck-1.0.dist-info/METADATA": "Name: vcheck\nVersion: 1.0\n", + "vcheck/__init__.py": "X = 1\n", + "extra_top.py": "Y = 2\n", + }, + ) + with self.assertRaisesRegex( + ValueError, + r"do not match extracted_files.*uncovered=\['extra_top\.py'\]", + ): + action_whl_installer.install_wheel( + wheel_path=whl, + dest_dir=root / "vcheck_out", + expected_site_paths=["vcheck"], + validation_source="extracted_files", + ) + with self.assertRaisesRegex( + ValueError, + r"do not match expected site_paths.*missing=\['missing_mod'\]", + ): + action_whl_installer.install_wheel( + wheel_path=whl, + dest_dir=root / "vcheck_out_missing", + expected_site_paths=["vcheck", "extra_top.py", "missing_mod"], + validation_source="site_paths", + ) + + def test_single_wheel_in_and_scrub_env(self): + env = { + "RUNFILES_DIR": "/some/runfiles", + "PYTHONSAFEPATH": "1", + "CUSTOM_VAR": "keep", + } + wheel_transformer.scrub_bazel_env(env) + self.assertEqual(env, {"CUSTOM_VAR": "keep"}) + + with tempfile.TemporaryDirectory() as tmp: + whldir = pathlib.Path(tmp) / "out.whldir" + whldir.mkdir() + with self.assertRaisesRegex(ValueError, "Expected 1 .whl file"): + wheel_layout.single_wheel_in(whldir) + + whl = _write_zip( + whldir / "pkg-1.0-py3-none-any.whl", + {"pkg-1.0.dist-info/METADATA": "Name: pkg\nVersion: 1.0\n"}, + ) + self.assertEqual( + wheel_layout.single_wheel_in(whldir, check_stray=True), whl + ) + + (whldir / "stray.txt").write_text("oops", encoding="utf-8") + with self.assertRaisesRegex(ValueError, "Unexpected non-wheel files"): + wheel_layout.single_wheel_in(whldir, check_stray=True) + + def test_wheel_files_extractor(self): + with tempfile.TemporaryDirectory() as tmp: + root = pathlib.Path(tmp) + whl = _write_zip( + root / "fgpkg-1.0-py3-none-any.whl", + { + "fgpkg-1.0.dist-info/METADATA": "Name: fgpkg\nVersion: 1.0\n", + "fgpkg/__init__.py": "X = 1\n", + "fgpkg/data.txt": "hello\n", + "fgpkg-1.0.data/headers/fg.h": "#pragma once\n", + "fgpkg-1.0.data/scripts/fg_cli": "#!python\nprint('cli')\n", + }, + ) + installed = root / "installed" + action_whl_installer.install_wheel(whl, installed) + out_data = root / "extracted/data.txt" + out_cli = root / "extracted/fg_cli" + wheel_files_extractor.extract_wheel_files( + installed, + [("site-packages/fgpkg/data.txt", out_data)], + executable=False, + ) + wheel_files_extractor.extract_wheel_files( + installed, + [("bin/fg_cli", out_cli)], + executable=True, + ) + self.assertEqual(out_data.read_text(encoding="utf-8"), "hello\n") + self.assertTrue(out_cli.stat().st_mode & 0o111) + + # Windows shebang script fallback (bin/fg_cli -> bin/fg_cli.bat) + installed_win = root / "installed_win" + action_whl_installer.install_wheel(whl, installed_win, target_os="windows") + out_win_cli = root / "extracted/fg_cli_win" + wheel_files_extractor.extract_wheel_files( + installed_win, + [("bin/fg_cli", out_win_cli)], + executable=True, + ) + self.assertTrue(out_win_cli.is_file()) + + # Fallback wheel extraction when installed tree has omit_source + pyc_tag = sys.implementation.cache_tag + py_ver = f"{sys.version_info.major}.{sys.version_info.minor}" + installed_omit = root / "installed_omit" + action_whl_installer.install_wheel( + whl, + installed_omit, + precompile=True, + pyc_tag=pyc_tag, + precompile_source_retention="omit_source", + python_version=py_ver, + ) + self.assertFalse( + (installed_omit / "site-packages/fgpkg/__init__.py").exists() + ) + out_init = root / "extracted/__init__.py" + wheel_files_extractor.extract_wheel_files( + installed_omit, + [("site-packages/fgpkg/__init__.py", out_init)], + fallback_wheel=whl, + ) + self.assertEqual(out_init.read_text(encoding="utf-8"), "X = 1\n") + + # Re-installing from installed_dir with different precompile settings + reinstalled_omit = root / "reinstalled_omit" + action_whl_installer.install_wheel( + None, + reinstalled_omit, + installed_dir=installed, + precompile=True, + pyc_tag=pyc_tag, + precompile_source_retention="omit_source", + python_version=py_ver, + ) + self.assertFalse( + (reinstalled_omit / "site-packages/fgpkg/__init__.py").exists() + ) + self.assertTrue( + (reinstalled_omit / "site-packages/fgpkg/__init__.pyc").is_file() + ) + + with self.assertRaisesRegex(ValueError, "escapes wheel directory"): + wheel_files_extractor.extract_wheel_files( + installed, + [("../outside.txt", root / "extracted/outside.txt")], + ) + with self.assertRaises(FileNotFoundError): + wheel_files_extractor.extract_wheel_files( + installed, + [("site-packages/fgpkg/missing.txt", root / "extracted/m.txt")], + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/pypi/whl_library_srcs/whl_library_srcs_tests.bzl b/tests/pypi/whl_library_srcs/whl_library_srcs_tests.bzl index 340980d185..1c4706de7f 100644 --- a/tests/pypi/whl_library_srcs/whl_library_srcs_tests.bzl +++ b/tests/pypi/whl_library_srcs/whl_library_srcs_tests.bzl @@ -15,6 +15,12 @@ "" load("@rules_testing//lib:test_suite.bzl", "test_suite") +load( + "//python/private/pypi:py_wheel_extract_files.bzl", + "match_wheel_glob", + "wheel_extract_prefix", + "wheel_glob", +) # buildifier: disable=bzl-visibility load("//python/private/pypi:whl_library_srcs.bzl", "whl_library_srcs") # buildifier: disable=bzl-visibility load("//tests/support/mocks:mocks.bzl", "mocks") @@ -385,10 +391,13 @@ def _test_action_install(env): "visibility": ["//visibility:public"], }, ]) - env.expect.that_int(len(py_wheel_library_calls)).equals(1) - call = py_wheel_library_calls[0] + env.expect.that_int(len(py_wheel_library_calls)).equals(2) + env.expect.that_str(py_wheel_library_calls[0]["name"]).equals("_wheel_install") + env.expect.that_str(py_wheel_library_calls[0]["wheel"]).equals("foo-1.0-py3-none-any.whl") + env.expect.that_collection(py_wheel_library_calls[0]["data"]).contains_exactly([]) + call = py_wheel_library_calls[1] env.expect.that_str(call["name"]).equals("srcs") - env.expect.that_str(call["wheel"]).equals("foo-1.0-py3-none-any.whl") + env.expect.that_str(call["wheel"]).equals(":_wheel_install") env.expect.that_collection(call["extracted_files"]).contains_exactly([ "bin/bin_tool", "data/etc/cfg.txt", @@ -428,9 +437,13 @@ def _test_action_install(env): ]) ext_dist_info_fg = [c for c in ext_filegroup_calls if c["name"] == "dist_info"][0] env.expect.that_collection(ext_dist_info_fg["srcs"]).contains_exactly([]) + env.expect.that_int(len(ext_py_wheel_library_calls)).equals(2) + env.expect.that_str(ext_py_wheel_library_calls[0]["name"]).equals("_wheel_install") env.expect.that_str(ext_py_wheel_library_calls[0]["wheel"]).equals( "@foo_whl//:foo-1.0-py3-none-any.whl", ) + env.expect.that_str(ext_py_wheel_library_calls[1]["name"]).equals("srcs") + env.expect.that_str(ext_py_wheel_library_calls[1]["wheel"]).equals(":_wheel_install") _tests.append(_test_action_install) @@ -445,26 +458,275 @@ def _test_action_install_fails_on_custom_filegroups(env): env.expect.that_int(len(errors)).equals(1) env.expect.that_str(errors[0]).contains("custom glob-based 'filegroups'") env.expect.that_str(errors[0]).contains("custom_fg") + env.expect.that_str(errors[0]).contains("py_wheel_extract_files") _tests.append(_test_action_install_fails_on_custom_filegroups) -def _test_action_install_fails_on_wheel_copy_files(env): - errors = [] +def _test_action_install_internal_copy_and_filegroups(env): + filegroup_calls = [] + copy_calls = [] + extract_calls = [] + py_wheel_library_calls = [] + whl_library_srcs( name = "foo-1.0-py3-none-any.whl", action_install = True, - extracted_files = ["site-packages/foo/__init__.py"], - shebang_scripts = ["shebang_tool"], - copy_files = {"site-packages/foo/__init__.py": "copied.py"}, - copy_executables = {"bin/shebang_tool": "copied_tool"}, - _fail = errors.append, + extracted_files = [ + "bin/bin_tool", + "data/etc/cfg.txt", + "include/foo/foo.h", + "site-packages/foo-1.0.dist-info/METADATA", + "site-packages/foo/__init__.py", + ], + filegroups = { + "custom_fg": [ + "data/**/*.txt", + "include/**/*.h", + ], + }, + copy_files = { + "@ext_repo//:ext.txt": "ext_dest.txt", + "data/etc/cfg.txt": "copied_cfg.txt", + }, + copy_executables = { + "bin/bin_tool": "copied_tool", + }, + tags = ["pypi_name=foo", "pypi_version=1.0"], + native = struct( + filegroup = lambda **kwargs: filegroup_calls.append(kwargs), + glob = lambda *args, **kwargs: env.fail("glob should not be called when action_install=True"), + ), + rules = struct( + copy_file = lambda **kwargs: copy_calls.append(kwargs), + py_wheel_extract_files = lambda **kwargs: extract_calls.append(kwargs), + py_wheel_library = lambda **kwargs: py_wheel_library_calls.append(kwargs), + ), ) - env.expect.that_int(len(errors)).equals(1) - env.expect.that_str(errors[0]).contains("reference wheel-extracted paths") - env.expect.that_str(errors[0]).contains("bin/shebang_tool") - env.expect.that_str(errors[0]).contains("site-packages/foo/__init__.py") -_tests.append(_test_action_install_fails_on_wheel_copy_files) + # Note: data/etc/cfg.txt is already extracted by _wheel_extract_0 for copy_files, + # so _wheel_extract_1 for custom_fg only extracts include/foo/foo.h (de-duplicated!). + env.expect.that_collection(extract_calls).contains_exactly([ + { + "name": "_wheel_extract_0", + "outs": ["_extracted/data/etc/cfg.txt"], + "paths": ["data/etc/cfg.txt"], + "visibility": ["//visibility:private"], + "wheel_library": ":_wheel_install", + }, + { + "is_executable": True, + "name": "_wheel_extract_exec_0", + "outs": ["_extracted_exec/bin/bin_tool"], + "paths": ["bin/bin_tool"], + "visibility": ["//visibility:private"], + "wheel_library": ":_wheel_install", + }, + { + "name": "_wheel_extract_1", + "outs": ["_extracted/include/foo/foo.h"], + "paths": ["include/foo/foo.h"], + "visibility": ["//visibility:private"], + "wheel_library": ":_wheel_install", + }, + ]) + env.expect.that_collection(copy_calls).contains_exactly([ + { + "name": "ext_dest.txt.copy", + "out": "ext_dest.txt", + "src": "@ext_repo//:ext.txt", + "visibility": ["//visibility:public"], + }, + { + "name": "copied_cfg.txt.copy", + "out": "copied_cfg.txt", + "src": ":_extracted/data/etc/cfg.txt", + "visibility": ["//visibility:public"], + }, + { + "is_executable": True, + "name": "copied_tool.copy", + "out": "copied_tool", + "src": ":_extracted_exec/bin/bin_tool", + "visibility": ["//visibility:public"], + }, + ]) + env.expect.that_collection(filegroup_calls).contains_at_least([ + { + "name": "custom_fg", + "srcs": [ + ":_extracted/data/etc/cfg.txt", + ":_extracted/include/foo/foo.h", + ], + "visibility": ["//visibility:public"], + }, + ]) + env.expect.that_int(len(py_wheel_library_calls)).equals(2) + env.expect.that_str(py_wheel_library_calls[0]["name"]).equals("_wheel_install") + env.expect.that_str(py_wheel_library_calls[0]["wheel"]).equals("foo-1.0-py3-none-any.whl") + env.expect.that_collection(py_wheel_library_calls[0]["data"]).contains_exactly([]) + env.expect.that_collection(py_wheel_library_calls[0]["visibility"]).contains_exactly(["//visibility:public"]) + env.expect.that_str(py_wheel_library_calls[1]["name"]).equals("srcs") + env.expect.that_str(py_wheel_library_calls[1]["wheel"]).equals(":_wheel_install") + env.expect.that_collection(py_wheel_library_calls[1]["data"]).contains_exactly([ + "ext_dest.txt", + "copied_cfg.txt", + "copied_tool", + ]) + +_tests.append(_test_action_install_internal_copy_and_filegroups) + +def _test_wheel_glob_dedup_and_sdist_failure(env): + rules_by_name = { + "srcs": { + "extracted_files": [ + "site-packages/torch/lib/libc10.so", + "site-packages/torch/lib/libtorch_cpu.so", + "site-packages/torch/include/torch.h", + ], + "kind": "py_wheel_library", + "shebang_scripts": [], + }, + } + extract_calls = [] + + def record_extract(**kwargs): + extract_calls.append(kwargs) + rules_by_name[kwargs["name"]] = kwargs + + mock_native = struct( + existing_rule = lambda name: rules_by_name.get(name), + ) + + # First call: pattern pair (.so vs .dylib) where only .so exists. + c10 = wheel_glob( + [ + "site-packages/torch/lib/libc10.so", + "site-packages/torch/lib/libc10.dylib", + ], + native = mock_native, + extract_rule = record_extract, + ) + env.expect.that_collection(c10).contains_exactly([ + ":_extracted/site-packages/torch/lib/libc10.so", + ]) + + # Second call: wildcard over all .so files; libc10.so is already extracted + # so only libtorch_cpu.so should be added in _wheel_extract_1. + all_so = wheel_glob( + ["site-packages/torch/**/*.so"], + native = mock_native, + extract_rule = record_extract, + ) + env.expect.that_collection(all_so).contains_exactly([ + ":_extracted/site-packages/torch/lib/libc10.so", + ":_extracted/site-packages/torch/lib/libtorch_cpu.so", + ]) + env.expect.that_int(len(extract_calls)).equals(2) + env.expect.that_collection(extract_calls[0]["paths"]).contains_exactly([ + "site-packages/torch/lib/libc10.so", + ]) + env.expect.that_collection(extract_calls[1]["paths"]).contains_exactly([ + "site-packages/torch/lib/libtorch_cpu.so", + ]) + + # Sdist-built wheel fails with a clear message (both with site_paths and empty site_paths). + sdist_errors = [] + wheel_glob( + ["site-packages/**"], + native = struct( + existing_rule = lambda name: {"kind": "py_wheel_library", "site_paths": ["pkg"]} if name == "srcs" else None, + ), + _fail = sdist_errors.append, + ) + env.expect.that_int(len(sdist_errors)).equals(1) + env.expect.that_str(sdist_errors[0]).contains("cannot be used with an action-built sdist") + + empty_site_paths_sdist_errors = [] + wheel_glob( + ["site-packages/**"], + native = struct( + existing_rule = lambda name: {"kind": "py_wheel_library", "site_paths": [], "wheel": ":whldir"} if name == "srcs" else ({"kind": "py_sdist_wheel"} if name == "whldir" else None), + ), + _fail = empty_site_paths_sdist_errors.append, + ) + env.expect.that_int(len(empty_site_paths_sdist_errors)).equals(1) + env.expect.that_str(empty_site_paths_sdist_errors[0]).contains("cannot be used with an action-built sdist") + + # Invalid exclude_directories and invalid glob patterns fail clearly. + excl_dir_errors = [] + wheel_glob( + ["site-packages/**"], + exclude_directories = 2, + files = ["site-packages/a.py"], + _fail = excl_dir_errors.append, + ) + env.expect.that_int(len(excl_dir_errors)).equals(1) + env.expect.that_str(excl_dir_errors[0]).contains("exclude_directories") + + for bad_pat in ["", "/abs", "trail/", "a//b", "../up", "a/./b", "a/**b", "a/b**"]: + pat_errors = [] + match_wheel_glob(["a/b.py"], [bad_pat], _fail = pat_errors.append) + env.expect.that_int(len(pat_errors)).equals(1) + + # Default mode merges custom filegroups with built-in extracted_whl_files, dist_info, data. + fg_calls = [] + whl_library_srcs( + name = "foo.whl", + filegroups = {"custom_fg": ["site-packages/**/*.so"]}, + native = struct( + filegroup = lambda **kwargs: fg_calls.append(kwargs["name"]), + glob = lambda *args, **kwargs: [], + ), + rules = struct( + venv_rewrite_shebang = lambda **kwargs: None, + gen_wheel_record = lambda **kwargs: None, + ), + ) + env.expect.that_collection(fg_calls).contains_exactly([ + "whl_file", + "extracted_whl_files", + "dist_info", + "data", + "custom_fg", + ]) + + # Default mode wheel_glob delegates to native.glob while excluding repo bookkeeping files. + default_glob_excludes = [] + wheel_glob( + ["*"], + exclude = ["custom_excl.txt"], + native = struct( + existing_rule = lambda name: ( + {"kind": "py_library"} if name == "srcs" else ( + {"srcs": [":foo-1.0-py3-none-any.whl"]} if name == "whl_file" else None + ) + ), + glob = lambda include, exclude = [], **kwargs: default_glob_excludes.extend(exclude) or include, + ), + ) + env.expect.that_collection(default_glob_excludes).contains_at_least([ + "BUILD", + "BUILD.bazel", + "MODULE.bazel", + "REPO.bazel", + "WORKSPACE", + "WORKSPACE.bzlmod", + "WORKSPACE.bazel", + "metadata.json", + "wheel_files.bzl", + "*.whl", + "foo-1.0-py3-none-any.whl", + "custom_excl.txt", + ]) + env.expect.that_str(wheel_extract_prefix(native = mock_native)).equals("_extracted/") + env.expect.that_str(wheel_extract_prefix(is_executable = True, native = mock_native)).equals("_extracted_exec/") + env.expect.that_str( + wheel_extract_prefix( + native = struct(existing_rule = lambda name: {"kind": "py_library"} if name == "srcs" else None), + ), + ).equals("") + +_tests.append(_test_wheel_glob_dedup_and_sdist_failure) def whl_library_srcs_test_suite(name): """create the test suite. diff --git a/tests/venv_site_packages_libs/app_files_building/app_files_building_tests.bzl b/tests/venv_site_packages_libs/app_files_building/app_files_building_tests.bzl index cf1d8faff6..5b68ba3ffe 100644 --- a/tests/venv_site_packages_libs/app_files_building/app_files_building_tests.bzl +++ b/tests/venv_site_packages_libs/app_files_building/app_files_building_tests.bzl @@ -619,12 +619,12 @@ def _test_optimized_grouping_pkgutil_whls_impl(env, target): break if is_action_install: break - sp_prefix = "srcs/site-packages" if is_action_install else "site-packages" + sp_prefix = "_wheel_install/site-packages" if is_action_install else "site-packages" if is_action_install: - ns1_init_files = ["../+internal_dev_deps+pkgutil_nspkg1/srcs"] + ns1_init_files = ["../+internal_dev_deps+pkgutil_nspkg1/_wheel_install"] ns1_one_files = ns1_init_files ns1_dist_files = ns1_init_files - ns2_init_files = ["../+internal_dev_deps+pkgutil_nspkg2/srcs"] + ns2_init_files = ["../+internal_dev_deps+pkgutil_nspkg2/_wheel_install"] ns2_two_files = ns2_init_files ns2_dist_files = ns2_init_files else: From c677164aa70c5f282e892158456f35c349497553 Mon Sep 17 00:00:00 2001 From: Jeremy Volkman Date: Mon, 26 Oct 2026 00:54:59 +0000 Subject: [PATCH 3/9] feat(pypi): add py_sdist_wheel rule for building sdists in actions --- python/private/pypi/BUILD.bazel | 39 ++ python/private/pypi/py_sdist_wheel.bzl | 424 ++++++++++++++ python/private/pypi/sdist_wheel_builder.py | 522 ++++++++++++++++++ tests/pypi/py_wheel_library/BUILD.bazel | 202 +++++++ .../classic_bdep-1.0.dist-info/METADATA | 3 + .../site-packages/classic_bdep/__init__.py | 1 + .../custom_build_helper/helper_data.txt | 1 + .../custom_build_helper/helper_mod.py | 11 + .../custom_shadow_dep/packaging/__init__.py | 3 + .../pypi/py_wheel_library/make_test_sdist.py | 94 ++++ tests/pypi/py_wheel_library/pre_build.patch | 5 + .../pypi/py_wheel_library/sdist_cext_test.py | 41 ++ .../sdist_wheel_builder_test.py | 223 ++++++++ 13 files changed, 1569 insertions(+) create mode 100644 python/private/pypi/py_sdist_wheel.bzl create mode 100644 python/private/pypi/sdist_wheel_builder.py create mode 100644 tests/pypi/py_wheel_library/classic_bdep/site-packages/classic_bdep-1.0.dist-info/METADATA create mode 100644 tests/pypi/py_wheel_library/classic_bdep/site-packages/classic_bdep/__init__.py create mode 100644 tests/pypi/py_wheel_library/custom_build_helper/helper_data.txt create mode 100644 tests/pypi/py_wheel_library/custom_build_helper/helper_mod.py create mode 100644 tests/pypi/py_wheel_library/custom_shadow_dep/packaging/__init__.py create mode 100644 tests/pypi/py_wheel_library/make_test_sdist.py create mode 100644 tests/pypi/py_wheel_library/pre_build.patch create mode 100644 tests/pypi/py_wheel_library/sdist_cext_test.py create mode 100644 tests/pypi/py_wheel_library/sdist_wheel_builder_test.py diff --git a/python/private/pypi/BUILD.bazel b/python/private/pypi/BUILD.bazel index f725fdfdf9..a2f502b483 100644 --- a/python/private/pypi/BUILD.bazel +++ b/python/private/pypi/BUILD.bazel @@ -44,6 +44,21 @@ py_interpreter_program( visibility = ["//visibility:public"], ) +filegroup( + name = "sdist_wheel_builder_helpers", + srcs = [ + "wheel_layout.py", + "wheel_transformer.py", + ], +) + +py_interpreter_program( + name = "sdist_wheel_builder", + interpreter_args = ["-B"], + main = "sdist_wheel_builder.py", + visibility = ["//visibility:public"], +) + py_interpreter_program( name = "wheel_transformer", interpreter_args = ["-B"], @@ -82,6 +97,14 @@ py_library( deps = [":rewriters_lib"], ) +py_library( + name = "sdist_wheel_builder_lib", + srcs = ["sdist_wheel_builder.py"], + imports = ["."], + visibility = ["//tests:__subpackages__"], + deps = [":wheel_installer_lib"], +) + alias( name = "venv_entry_point_template", actual = select({ @@ -713,6 +736,22 @@ bzl_library( ], ) +bzl_library( + name = "py_sdist_wheel", + srcs = ["py_sdist_wheel.bzl"], + deps = [ + ":py_installed_wheel_info", + "//python/private:attr_builders", + "//python/private:attributes", + "//python/private:builders", + "//python/private:common", + "//python/private:py_info", + "//python/private:reexports", + "//python/private:rule_builders", + "//python/private:toolchain_types", + ], +) + bzl_library( name = "py_wheel_library", srcs = ["py_wheel_library.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..c999d804d3 --- /dev/null +++ b/python/private/pypi/py_sdist_wheel.bzl @@ -0,0 +1,424 @@ +"""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") +load(":py_installed_wheel_info.bzl", "PyInstalledWheelInfo") + +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) + if PyInstalledWheelInfo not in dep: + imports.add(py.imports) + if hasattr(py, "venv_symlinks"): + venv_symlinks.add(py.venv_symlinks) + if PyInstalledWheelInfo in dep: + files.add([dep[PyInstalledWheelInfo].directory]) + sources.add([dep[PyInstalledWheelInfo].directory]) + 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)) + + 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("=") + args.add("--target-" + kind, val) + + 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..197cb9f912 --- /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 wheel_layout import ( + apply_unified_patch, + sanitize_wheel_entry_path, + single_wheel_in, +) +from wheel_transformer import scrub_bazel_env + + +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/tests/pypi/py_wheel_library/BUILD.bazel b/tests/pypi/py_wheel_library/BUILD.bazel index 80f11308e0..d4c72c9f76 100644 --- a/tests/pypi/py_wheel_library/BUILD.bazel +++ b/tests/pypi/py_wheel_library/BUILD.bazel @@ -1,9 +1,13 @@ +load("@bazel_skylib//rules:common_settings.bzl", "string_flag") load("@bazel_skylib//rules:copy_file.bzl", "copy_file") load("@rules_cc//cc:cc_import.bzl", "cc_import") load("@rules_cc//cc:cc_test.bzl", "cc_test") load("@rules_shell//shell:sh_binary.bzl", "sh_binary") +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( "//python/private/pypi:py_wheel_extract_files.bzl", "py_wheel_extract_files", @@ -186,6 +190,204 @@ cc_test( ], ) +py_binary( + name = "make_test_sdist", + srcs = ["make_test_sdist.py"], + main = "make_test_sdist.py", +) + +genrule( + name = "gen_demo_sdist", + outs = ["sdist_demo-main.tar.gz"], + cmd = "$(execpath :make_test_sdist) $@", + tools = [":make_test_sdist"], +) + +string_flag( + name = "always_venvs_site_packages", + build_setting_default = "yes", + values = [ + "yes", + "no", + ], +) + +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"], + experimental_venvs_site_packages = ":always_venvs_site_packages", + imports = ["classic_bdep/site-packages"], + tags = [ + "pypi_name=classic_bdep", + "pypi_version=1.0", + ], +) + +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", + ":demo_wheel_lib", + ], + config_settings_list = { + "--global-option": [ + "--quiet", + "--verbose", + ], + }, + distribution = "sdist-demo", + pre_build_patch_strips = [1], + pre_build_patches = ["pre_build.patch"], + sdist = ":gen_demo_sdist", + version = "0.5.0", +) + +# Verify two bare-named py_sdist_wheel targets building the same sdist in one +# package do not collide on declared output filenames. +py_sdist_wheel( + name = "sdist_demo_bare_a", + build_deps = [ + ":classic_bdep", + ":custom_build_helper", + ":custom_shadow_dep", + ":demo_wheel_lib", + ], + distribution = "sdist-demo", + pre_build_patch_strips = [1], + pre_build_patches = ["pre_build.patch"], + sdist = ":gen_demo_sdist", + version = "0.5.0", +) + +py_sdist_wheel( + name = "sdist_demo_bare_b", + build_deps = [ + ":classic_bdep", + ":custom_build_helper", + ":custom_shadow_dep", + ":demo_wheel_lib", + ], + distribution = "sdist-demo", + pre_build_patch_strips = [1], + pre_build_patches = ["pre_build.patch"], + sdist = ":gen_demo_sdist", + version = "0.5.0", +) + +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/__init__.py", + runfiles = True, + whl = ":sdist_demo-0.5.0.whldir", +) + +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_wheel_library( + name = "sdist_cext_wheel_lib", + target_compatible_with = select({ + "@platforms//os:windows": ["@platforms//:incompatible"], + "//conditions:default": [], + }), + wheel = ":sdist_cext_a.whldir", +) + +py_test( + name = "sdist_cext_test", + 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 = [ + ":sdist_cext_wheel_lib", + "//python/runfiles", + ], +) + +py_test( + name = "sdist_wheel_builder_test", + 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", + ], +) + py_test( name = "py_wheel_library_test", srcs = ["py_wheel_library_test.py"], diff --git a/tests/pypi/py_wheel_library/classic_bdep/site-packages/classic_bdep-1.0.dist-info/METADATA b/tests/pypi/py_wheel_library/classic_bdep/site-packages/classic_bdep-1.0.dist-info/METADATA new file mode 100644 index 0000000000..517762ce2d --- /dev/null +++ b/tests/pypi/py_wheel_library/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_wheel_library/classic_bdep/site-packages/classic_bdep/__init__.py b/tests/pypi/py_wheel_library/classic_bdep/site-packages/classic_bdep/__init__.py new file mode 100644 index 0000000000..1e8445dab2 --- /dev/null +++ b/tests/pypi/py_wheel_library/classic_bdep/site-packages/classic_bdep/__init__.py @@ -0,0 +1 @@ +CLASSIC_BDEP_OK = True diff --git a/tests/pypi/py_wheel_library/custom_build_helper/helper_data.txt b/tests/pypi/py_wheel_library/custom_build_helper/helper_data.txt new file mode 100644 index 0000000000..3c719ead7e --- /dev/null +++ b/tests/pypi/py_wheel_library/custom_build_helper/helper_data.txt @@ -0,0 +1 @@ +helper_data_ok diff --git a/tests/pypi/py_wheel_library/custom_build_helper/helper_mod.py b/tests/pypi/py_wheel_library/custom_build_helper/helper_mod.py new file mode 100644 index 0000000000..9f33bcab0b --- /dev/null +++ b/tests/pypi/py_wheel_library/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_wheel_library/custom_shadow_dep/packaging/__init__.py b/tests/pypi/py_wheel_library/custom_shadow_dep/packaging/__init__.py new file mode 100644 index 0000000000..a19780d8ab --- /dev/null +++ b/tests/pypi/py_wheel_library/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_wheel_library/make_test_sdist.py b/tests/pypi/py_wheel_library/make_test_sdist.py new file mode 100644 index 0000000000..e0d6a95a6c --- /dev/null +++ b/tests/pypi/py_wheel_library/make_test_sdist.py @@ -0,0 +1,94 @@ +"""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", "demo-pkg>=1.0", "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, demo_pkg, helper_mod, packaging, packaging.version\n" + "from setuptools import setup\n" + "assert classic_bdep.CLASSIC_BDEP_OK is True\n" + "assert demo_pkg.VALUE == 'patched_in_action'\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_wheel_library/pre_build.patch b/tests/pypi/py_wheel_library/pre_build.patch new file mode 100644 index 0000000000..595b7e7339 --- /dev/null +++ b/tests/pypi/py_wheel_library/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_wheel_library/sdist_cext_test.py b/tests/pypi/py_wheel_library/sdist_cext_test.py new file mode 100644 index 0000000000..0050cf1209 --- /dev/null +++ b/tests/pypi/py_wheel_library/sdist_cext_test.py @@ -0,0 +1,41 @@ +"""Tests C-extension sdist building and determinism in py_sdist_wheel.""" + +from __future__ import annotations + +import importlib +import importlib.metadata +import pathlib +import unittest + +from python.runfiles import runfiles + + +class SdistCextTest(unittest.TestCase): + def test_import_cext_and_metadata(self): + 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") + + 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_wheel_library/sdist_cext_a.whldir" + ) + rloc_b = rf.Rlocation( + "rules_python/tests/pypi/py_wheel_library/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_wheel_library/sdist_wheel_builder_test.py b/tests/pypi/py_wheel_library/sdist_wheel_builder_test.py new file mode 100644 index 0000000000..c28815dafe --- /dev/null +++ b/tests/pypi/py_wheel_library/sdist_wheel_builder_test.py @@ -0,0 +1,223 @@ +"""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 + +from python.runfiles import runfiles +from tests.pypi.py_wheel_library.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_wheel_library/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 (:whl) 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_wheel_library/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_wheel_library/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_wheel_library/{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, []) + + +if __name__ == "__main__": + unittest.main() From cfefe3dea9bfd1256d60c373d94ee328d24cd9b6 Mon Sep 17 00:00:00 2001 From: Jeremy Volkman Date: Mon, 26 Oct 2026 01:01:24 +0000 Subject: [PATCH 4/9] feat(pypi): install action-built wheels in py_wheel_library Extends py_wheel_library and action_whl_installer to consume action-built wheels (.whldir TreeArtifacts): - Adds site_paths, distribution, and version attributes to py_wheel_library and consumes PyBuiltWheelInfo. - Exposes extracted .dist-info/entry_points.txt via OutputGroupInfo.dist_info (--entry-points-output) for action-built wheel console scripts. - Normalizes the installed .dist-info directory name via --dist-info-dir (and updates RECORD entries) so importlib.metadata works in venv mode. - Validates predicted site_paths against installed site-packages contents in action_whl_installer when venvs_site_packages=yes (--expected-site-path). --- python/private/pypi/BUILD.bazel | 5 + python/private/pypi/action_whl_installer.py | 83 +++++- .../private/pypi/py_installed_wheel_info.bzl | 10 +- python/private/pypi/py_wheel_library.bzl | 263 +++++++++++++++--- python/private/pypi/py_wheel_transform.bzl | 23 +- python/private/pypi/wheel_layout.py | 45 ++- python/private/pypi/wheel_record_rewriter.py | 29 +- tests/pypi/py_wheel_library/BUILD.bazel | 31 ++- .../py_wheel_library_bzl_tests.bzl | 36 +++ .../py_wheel_library/py_wheel_library_test.py | 6 + tests/pypi/py_wheel_library/sh_transform.sh | 4 + .../wheel_layout_and_installer_test.py | 74 +++++ 12 files changed, 533 insertions(+), 76 deletions(-) diff --git a/python/private/pypi/BUILD.bazel b/python/private/pypi/BUILD.bazel index a2f502b483..972b020baa 100644 --- a/python/private/pypi/BUILD.bazel +++ b/python/private/pypi/BUILD.bazel @@ -728,6 +728,7 @@ bzl_library( name = "py_wheel_transform", srcs = ["py_wheel_transform.bzl"], deps = [ + ":py_sdist_wheel", "//python/private:attr_builders", "//python/private:common", "//python/private:py_internal", @@ -745,10 +746,12 @@ bzl_library( "//python/private:attributes", "//python/private:builders", "//python/private:common", + "//python/private:normalize_name", "//python/private:py_info", "//python/private:reexports", "//python/private:rule_builders", "//python/private:toolchain_types", + "//python/private:version", ], ) @@ -756,7 +759,9 @@ bzl_library( name = "py_wheel_library", srcs = ["py_wheel_library.bzl"], deps = [ + ":parse_whl_name", ":py_installed_wheel_info", + ":py_sdist_wheel", "//python/private:attr_builders", "//python/private:attributes", "//python/private:builders", diff --git a/python/private/pypi/action_whl_installer.py b/python/private/pypi/action_whl_installer.py index 3c421ee5fc..a1b30b9e81 100644 --- a/python/private/pypi/action_whl_installer.py +++ b/python/private/pypi/action_whl_installer.py @@ -333,6 +333,7 @@ def _finalize_dist_info( site_packages_dir: Path, dist_info_dir: str, *, + wheel_dist_info_dir: str = "", data_exclude_rx: list[re.Pattern[str]], used_data_dir: bool, expected_data_dir: str, @@ -348,27 +349,52 @@ def _finalize_dist_info( f.write(INSTALLER_URL) record_path = dist_info_path / "RECORD" - if not (used_data_dir and record_path.is_file()): + renamed_dist_info = bool( + wheel_dist_info_dir and dist_info_dir != wheel_dist_info_dir + ) + if not ((used_data_dir or renamed_dist_info) and record_path.is_file()): return with open(record_path, encoding="utf-8") as f: lines = rewrite_record_lines( f, target_os, - expected_data_dir, + expected_data_dir if used_data_dir else "", rewritten_scripts, + wheel_dist_info_dir=wheel_dist_info_dir, + target_dist_info_dir=dist_info_dir, ) with open(record_path, "w", encoding="utf-8", newline="\n") as f: f.write("".join(lines)) +def _write_entry_points_output( + entry_points_output: Path, + site_packages_dir: Path, + dist_info_dir: str, + fallback_text: str, + touched_site_rel: set[str], +) -> None: + ep_rel = f"{dist_info_dir}/entry_points.txt" if dist_info_dir else "" + ep_path = site_packages_dir / ep_rel if ep_rel else None + if ep_path is not None and ep_path.is_file(): + text = ep_path.read_text(encoding="utf-8") + elif ep_rel and ep_rel in touched_site_rel: + text = "" + else: + text = fallback_text + entry_points_output.parent.mkdir(parents=True, exist_ok=True) + with open(entry_points_output, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + + def _install_from_existing_dir( installed_dir: Path, dest_dir: Path, site_packages_dir: Path, srcs_exclude_rx: list[re.Pattern[str]], data_exclude_rx: list[re.Pattern[str]], -) -> tuple[str, set[str]]: +) -> tuple[str, set[str], str]: shutil.copytree(installed_dir, dest_dir, dirs_exist_ok=True) for p in dest_dir.rglob("*"): try: @@ -382,6 +408,16 @@ def _install_from_existing_dir( if d.is_dir() and d.name.endswith(".dist-info") ) dist_info_dir = dist_info_dirs[0] if dist_info_dirs else "" + ep_file = ( + site_packages_dir / dist_info_dir / "entry_points.txt" + if dist_info_dir + else None + ) + entry_points_text = ( + ep_file.read_text(encoding="utf-8") + if ep_file is not None and ep_file.is_file() + else "" + ) touched_site_rel: set[str] = set() for p in sorted(dest_dir.rglob("*")): @@ -403,7 +439,7 @@ def _install_from_existing_dir( touched_site_rel.add(p.relative_to(site_packages_dir).as_posix()) p.unlink() - return dist_info_dir, touched_site_rel + return dist_info_dir, touched_site_rel, entry_points_text def _extract_from_wheel( @@ -414,7 +450,8 @@ def _extract_from_wheel( target_os: str, srcs_exclude_rx: list[re.Pattern[str]], data_exclude_rx: list[re.Pattern[str]], -) -> str: + dist_info_dir_override: str = "", +) -> tuple[str, str]: if wheel_path.is_dir(): wheel_path = single_wheel_in(wheel_path) site_packages_dir.mkdir(parents=True, exist_ok=True) @@ -423,18 +460,20 @@ def _extract_from_wheel( used_data_dir = False with zipfile.ZipFile(wheel_path) as z: - dist_info_dir, _, entry_points_content = find_wheel_dist_info_and_entry_points( - z + wheel_dist_info_dir, _, entry_points_content = ( + find_wheel_dist_info_and_entry_points(z) ) - expected_data_dir = expected_data_dir_for_dist_info(dist_info_dir) + expected_data_dir = expected_data_dir_for_dist_info(wheel_dist_info_dir) data_dir_prefix = f"{expected_data_dir}/" + dist_info_dir = dist_info_dir_override or wheel_dist_info_dir for info, dest_or_script, is_shebang in plan_wheel_entries( z, - dist_info_dir, + wheel_dist_info_dir, entry_points_content, srcs_exclude_rx, data_exclude_rx, + target_dist_info_dir=dist_info_dir, ): if info.filename.startswith(data_dir_prefix): used_data_dir = True @@ -457,13 +496,14 @@ def _extract_from_wheel( _finalize_dist_info( site_packages_dir, dist_info_dir, + wheel_dist_info_dir=wheel_dist_info_dir, data_exclude_rx=data_exclude_rx, used_data_dir=used_data_dir, expected_data_dir=expected_data_dir, target_os=target_os, rewritten_scripts=rewritten_scripts, ) - return dist_info_dir + return dist_info_dir, entry_points_content or "" def _validate_installed_site_packages( @@ -555,6 +595,7 @@ def install_wheel( dest_dir: Path, *, installed_dir: Path | None = None, + entry_points_output: Path | None = None, target_os: str = "unix", srcs_exclude_globs: list[str] | None = None, data_exclude_globs: list[str] | None = None, @@ -563,6 +604,7 @@ def install_wheel( patch_strip: int = 0, expected_site_paths: list[str] | None = None, validation_source: str = "extracted_files", + dist_info_dir_override: str = "", precompile: bool = False, pyc_tag: str = "", precompile_invalidation_mode: str = "checked_hash", @@ -578,7 +620,7 @@ def install_wheel( data_exclude_rx = [glob_to_regex(g) for g in (data_exclude_globs or ())] if installed_dir is not None: - dist_info_dir, touched_site_rel = _install_from_existing_dir( + dist_info_dir, touched_site_rel, entry_points_text = _install_from_existing_dir( installed_dir, dest_dir, site_packages_dir, @@ -588,13 +630,14 @@ def install_wheel( else: if wheel_path is None: raise ValueError("Either wheel_path or installed_dir must be provided") - dist_info_dir = _extract_from_wheel( + dist_info_dir, entry_points_text = _extract_from_wheel( wheel_path, dest_dir, site_packages_dir, target_os=target_os, srcs_exclude_rx=srcs_exclude_rx, data_exclude_rx=data_exclude_rx, + dist_info_dir_override=dist_info_dir_override, ) touched_site_rel = set() @@ -613,6 +656,15 @@ def install_wheel( touched_site_rel, ) + if entry_points_output is not None: + _write_entry_points_output( + entry_points_output, + site_packages_dir, + dist_info_dir, + entry_points_text, + touched_site_rel, + ) + if create_namespace_inits_flag: create_namespace_inits( site_packages_dir, _NAMESPACE_PKG_TMPL_PATH.read_text(encoding="utf-8") @@ -656,6 +708,7 @@ def main(argv: Sequence[str] | None = None) -> None: parser.add_argument("--wheel", type=Path, default=None) parser.add_argument("--installed-dir", type=Path, default=None) parser.add_argument("--directory", type=Path, required=True) + parser.add_argument("--entry-points-output", type=Path, default=None) parser.add_argument( "--target-os", choices=["unix", "windows"], @@ -706,6 +759,10 @@ def main(argv: Sequence[str] | None = None) -> None: dest="expected_site_paths", default=[], ) + parser.add_argument( + "--dist-info-dir", + default="", + ) parser.add_argument( "--precompile", action="store_true", @@ -749,6 +806,7 @@ def main(argv: Sequence[str] | None = None) -> None: args.wheel, args.directory, installed_dir=args.installed_dir, + entry_points_output=args.entry_points_output, target_os=args.target_os, srcs_exclude_globs=args.srcs_exclude_globs, data_exclude_globs=args.data_exclude_globs, @@ -759,6 +817,7 @@ def main(argv: Sequence[str] | None = None) -> None: args.expected_site_paths if args.validate_site_packages else None ), validation_source=args.validation_source, + dist_info_dir_override=args.dist_info_dir, precompile=args.precompile, pyc_tag=args.pyc_tag, precompile_invalidation_mode=args.precompile_invalidation_mode, diff --git a/python/private/pypi/py_installed_wheel_info.bzl b/python/private/pypi/py_installed_wheel_info.bzl index dac5d2342e..b3c54d43fb 100644 --- a/python/private/pypi/py_installed_wheel_info.bzl +++ b/python/private/pypi/py_installed_wheel_info.bzl @@ -12,6 +12,11 @@ Information about an installed Python wheel TreeArtifact. :type: File The installed wheel TreeArtifact directory containing site-packages/, data/, bin/, and include/. +""", + "entry_points": """ +:type: File +The extracted `.dist-info/entry_points.txt` file (empty when the wheel has no +`entry_points.txt`), exposed via `OutputGroupInfo.dist_info`. """, "keep_source": """ :type: bool @@ -24,8 +29,9 @@ Whether `.py` files in `directory` were precompiled into `.pyc` files. "settings_key": """ :type: tuple Tuple of install settings `(should_precompile, keep_source, invalidation_mode, -optimize_level, srcs_exclude, data_exclude, create_namespace_inits)` used to -determine whether an outer `py_wheel_library` can reuse `directory`. +optimize_level, srcs_exclude, data_exclude, create_namespace_inits, +dist_info_dir)` used to determine whether an outer `py_wheel_library` can reuse +`directory`. """, "wheel": """ :type: File | None diff --git a/python/private/pypi/py_wheel_library.bzl b/python/private/pypi/py_wheel_library.bzl index 286b37ac04..3ce852730d 100644 --- a/python/private/pypi/py_wheel_library.bzl +++ b/python/private/pypi/py_wheel_library.bzl @@ -30,7 +30,12 @@ load( ) load("//python/private:normalize_name.bzl", "normalize_name") load("//python/private:py_cc_link_params_info.bzl", "PyCcLinkParamsInfo") -load("//python/private:py_info.bzl", "PyInfo") +load( + "//python/private:py_info.bzl", + "PyInfo", + "VenvSymlinkEntry", + "VenvSymlinkKind", +) load("//python/private:py_interpreter_program.bzl", "PyInterpreterProgramInfo") load("//python/private:py_library.bzl", "LIBRARY_ATTRS") load("//python/private:reexports.bzl", "BuiltinPyInfo") @@ -42,7 +47,9 @@ load( ) load("//python/private:venv_runfiles.bzl", "get_venv_symlinks") load("//python/private:version.bzl", "version") +load(":parse_whl_name.bzl", "parse_whl_name") load(":py_installed_wheel_info.bzl", "PyInstalledWheelInfo") +load(":py_sdist_wheel.bzl", "PyBuiltWheelInfo") PY_WHEEL_LIBRARY_ATTRS = COMMON_ATTRS | WINDOWS_CONSTRAINTS_ATTRS | { "data_exclude": lambda: attrb.StringList( @@ -52,6 +59,10 @@ Glob patterns to exclude from non-.py files when extracting the wheel. """, ), "deps": PY_SRCS_ATTRS["deps"], + "distribution": lambda: attrb.String( + default = "", + doc = "Optional Python distribution name; overrides `PyBuiltWheelInfo.distribution` and `pypi_name=` tag.", + ), "enable_implicit_namespace_pkgs": lambda: attrb.Bool( default = False, doc = """ @@ -94,12 +105,23 @@ prefixes) require `post_install_patch_strip = 1`. default = [], doc = """ Top-level script names in .data/scripts/ whose #!python shebang is rewritten. +""", + ), + "site_paths": lambda: attrb.StringList( + default = [], + doc = """ +Top-level or leaf paths under `site-packages/` when `extracted_files` is not +populated (e.g. for action-built sdists). Only used when `venvs_site_packages=yes`. """, ), "srcs_exclude": lambda: attrb.StringList( default = [], doc = "Glob patterns to exclude from .py files when extracting the wheel.", ), + "version": lambda: attrb.String( + default = "", + doc = "Optional PEP 440 package version; overrides `PyBuiltWheelInfo.version` and `pypi_version=` tag.", + ), "wheel": lambda: attrb.Label( allow_single_file = True, mandatory = True, @@ -223,62 +245,140 @@ def _add_precompile_args(ctx, args, out_short_path, exec_tools_toolchain, invali args.add("--precompiler-tool", files_to_run.executable) return [files_to_run] +def _expand_py_entry(path, keep_source, should_precompile, pyc_tag): + if not keep_source: + return [path[:-len(".py")] + ".pyc"] + if not (should_precompile and pyc_tag): + return [path] + stem = paths.basename(path)[:-len(".py")] + dirname = paths.dirname(path) + pyc_rel = ( + "{}/__pycache__/{}.{}.pyc".format(dirname, stem, pyc_tag) if dirname else "__pycache__/{}.{}.pyc".format(stem, pyc_tag) + ) + return [path, pyc_rel] + +def _resolve_meta_value(explicit_val, built_val, tag_val, whl_val, use_site_paths): + if explicit_val: + return explicit_val + if built_val: + return built_val + if use_site_paths: + return whl_val + return tag_val or whl_val + def _collect_installed_tree_files( extracted_files, shebang_scripts, *, is_windows, keep_source, + should_precompile, pyc_tag): tree_files = [] for f in extracted_files: - is_site_py = f.startswith("site-packages/") and f.endswith(".py") - if not is_site_py: + if f.startswith("site-packages/") and f.endswith(".py"): + tree_files.extend(_expand_py_entry(f, keep_source, should_precompile, pyc_tag)) + else: tree_files.append(f) - continue - if not keep_source: - tree_files.append(f[:-len(".py")] + ".pyc") - continue - tree_files.append(f) - if pyc_tag: - stem = paths.basename(f)[:-len(".py")] - tree_files.append( - "{}/__pycache__/{}.{}.pyc".format(paths.dirname(f), stem, pyc_tag), - ) for s in shebang_scripts: tree_files.append("bin/" + ((s + ".bat") if is_windows else s)) return tree_files +def _venv_symlinks_for_site_paths( + ctx, + out_files, + out_rf_path, + site_packages_rf_path, + package, + version_str, + dist_info_dir, + is_windows, + keep_source, + should_precompile = False, + pyc_tag = ""): + symlinks = [] + seen = {} + entries = [] + for sp in list(ctx.attr.site_paths) + list(ctx.attr.namespace_package_files): + if sp.endswith(".py"): + entries.extend(_expand_py_entry(sp, keep_source, should_precompile, pyc_tag)) + else: + entries.append(sp) + if dist_info_dir: + entries.append(dist_info_dir) + for sp in entries: + if not sp or sp in seen: + continue + seen[sp] = True + symlinks.append(VenvSymlinkEntry( + kind = VenvSymlinkKind.LIB, + link_to_path = paths.join(site_packages_rf_path, sp), + link_to_file = None, + package = package, + version = version_str, + venv_path = sp, + files = out_files, + )) + for s in ctx.attr.shebang_scripts: + script_name = (s + ".bat") if is_windows else s + symlinks.append(VenvSymlinkEntry( + kind = VenvSymlinkKind.BIN, + link_to_path = paths.join(out_rf_path, "bin", script_name), + link_to_file = None, + package = package, + version = version_str, + venv_path = script_name, + files = out_files, + )) + return symlinks + def _compute_wheel_venv_symlinks( ctx, out, + out_rf_path, + site_packages_rf_path, *, + package, + version_str, + dist_info_dir, is_windows, should_precompile, keep_source): - package, version_str = _get_package_and_version( - ctx.attr.extracted_files, - ctx.attr.tags, - ) pyc_tag = ( ctx.toolchains[TARGET_TOOLCHAIN_TYPE].py3_runtime.pyc_tag if should_precompile else "" ) - tree_files = _collect_installed_tree_files( - ctx.attr.extracted_files, - ctx.attr.shebang_scripts, - is_windows = is_windows, - keep_source = keep_source, - pyc_tag = pyc_tag, - ) - venv_symlinks = list(get_venv_symlinks( - ctx, - tree_files, - package, - version_str, - site_packages_root = "site-packages", - namespace_package_files = ctx.attr.namespace_package_files, - tree_artifact = out, - )) + if ctx.attr.extracted_files: + tree_files = _collect_installed_tree_files( + ctx.attr.extracted_files, + ctx.attr.shebang_scripts, + is_windows = is_windows, + keep_source = keep_source, + should_precompile = should_precompile, + pyc_tag = pyc_tag, + ) + venv_symlinks = list(get_venv_symlinks( + ctx, + tree_files, + package, + version_str, + site_packages_root = "site-packages", + namespace_package_files = ctx.attr.namespace_package_files, + tree_artifact = out, + )) + else: + venv_symlinks = _venv_symlinks_for_site_paths( + ctx, + depset([out]), + out_rf_path, + site_packages_rf_path, + package, + version_str, + dist_info_dir, + is_windows, + keep_source, + should_precompile = should_precompile, + pyc_tag = pyc_tag, + ) extra_data_files = [f for f in ctx.files.data if not f.is_directory] if extra_data_files: site_packages_root = paths.normalize(paths.join( @@ -297,7 +397,10 @@ def _compute_wheel_venv_symlinks( def _run_wheel_install_action( ctx, *, + built_info, installed_info, + dist_info_dir, + use_site_paths, effective_srcs_exclude, effective_data_exclude, is_windows, @@ -309,6 +412,8 @@ def _run_wheel_install_action( keep_source, exec_tools_toolchain): out = ctx.actions.declare_directory(ctx.attr.name) + entry_points_out = ctx.actions.declare_file(ctx.attr.name + ".dist_info/entry_points.txt") + wheel_input = built_info.directory if built_info != None else ctx.file.wheel args = ctx.actions.args() if installed_info != None and installed_info.wheel == None: @@ -323,13 +428,16 @@ def _run_wheel_install_action( underlying_wheel = None else: install_source_file = ( - installed_info.wheel if installed_info != None else ctx.file.wheel + installed_info.wheel if installed_info != None else wheel_input ) args.add_all("--wheel", [install_source_file], expand_directories = False) underlying_wheel = None if ctx.files.post_install_patches else install_source_file args.add_all("--directory", [out], expand_directories = False) + args.add("--entry-points-output", entry_points_out) args.add("--target-os", "windows" if is_windows else "unix") + if dist_info_dir: + args.add("--dist-info-dir", dist_info_dir) for pattern in effective_srcs_exclude: args.add("--srcs-exclude-glob", pattern) for pattern in effective_data_exclude: @@ -342,7 +450,11 @@ def _run_wheel_install_action( args.add("--patch", patch_file) if venvs_site_packages_enabled: args.add("--validate-site-packages") - for sp in _expected_site_paths_from_extracted(ctx.attr.extracted_files): + args.add("--validation-source", "site_paths" if use_site_paths else "extracted_files") + expected_paths = ( + ctx.attr.site_paths + ctx.attr.namespace_package_files if use_site_paths else _expected_site_paths_from_extracted(ctx.attr.extracted_files) + ) + for sp in expected_paths: args.add("--expected-site-path", sp) extra_tools = [] @@ -366,12 +478,12 @@ def _run_wheel_install_action( "PYTHONPATH": helper_files[0].dirname, }, inputs = [install_source_file] + ctx.files.post_install_patches + helper_files, - outputs = [out], + outputs = [out, entry_points_out], tools = extra_tools, mnemonic = "PyWheelInstall", progress_message = "Installing wheel {} into %{{output}}".format(install_source_file.basename), ) - return out, underlying_wheel + return out, entry_points_out, underlying_wheel def _py_wheel_library_impl(ctx): exec_tools_toolchain = ctx.toolchains[EXEC_TOOLS_TOOLCHAIN_TYPE] @@ -395,6 +507,46 @@ def _py_wheel_library_impl(ctx): ) invalidation_mode = _resolve_invalidation_mode(ctx) if should_precompile else "" + built_info = ( + ctx.attr.wheel[PyBuiltWheelInfo] if PyBuiltWheelInfo in ctx.attr.wheel else None + ) + tag_package, tag_version = _get_package_and_version( + ctx.attr.extracted_files, + ctx.attr.tags, + ) + whl_package = None + whl_version = None + if built_info == None and ctx.file.wheel.basename.endswith(".whl") and ctx.file.wheel.basename.count("-") >= 4: + parsed_whl = parse_whl_name(ctx.file.wheel.basename) + whl_package = normalize_name(parsed_whl.distribution) + parsed_ver = version.parse(parsed_whl.version, strict = False) + whl_version = parsed_ver.string if parsed_ver else None + + use_site_paths = bool(ctx.attr.site_paths) or not ctx.attr.extracted_files + package = _resolve_meta_value( + normalize_name(ctx.attr.distribution) if ctx.attr.distribution else None, + built_info.distribution if built_info else None, + tag_package, + whl_package, + use_site_paths, + ) + version_str = _resolve_meta_value( + version.normalize(ctx.attr.version) if ctx.attr.version else None, + built_info.version if built_info else None, + tag_version, + whl_version, + use_site_paths, + ) + if (ctx.attr.site_paths or (venvs_site_packages_enabled and use_site_paths)) and (not package or not version_str): + fail( + "py_wheel_library requires distribution and version (via PyBuiltWheelInfo " + + "or the distribution and version attributes) when site_paths is used or " + + "extracted_files is empty in venvs_site_packages mode", + ) + dist_info_dir = ( + "{}-{}.dist-info".format(package, version_str) if use_site_paths and package and version_str else "" + ) + installed_info = ( ctx.attr.wheel[PyInstalledWheelInfo] if PyInstalledWheelInfo in ctx.attr.wheel else None ) @@ -416,20 +568,26 @@ def _py_wheel_library_impl(ctx): tuple(effective_srcs_exclude), tuple(effective_data_exclude), create_namespace_inits, + dist_info_dir, ) can_reuse_installed = ( installed_info != None and + installed_info.entry_points != None and not ctx.files.post_install_patches and installed_info.settings_key == settings_key ) if can_reuse_installed: out = installed_info.directory + entry_points_out = installed_info.entry_points underlying_wheel = installed_info.wheel else: - out, underlying_wheel = _run_wheel_install_action( + out, entry_points_out, underlying_wheel = _run_wheel_install_action( ctx, + built_info = built_info, installed_info = installed_info, + dist_info_dir = dist_info_dir, + use_site_paths = use_site_paths, effective_srcs_exclude = effective_srcs_exclude, effective_data_exclude = effective_data_exclude, is_windows = is_windows, @@ -450,6 +608,11 @@ def _py_wheel_library_impl(ctx): venv_symlinks = _compute_wheel_venv_symlinks( ctx, out, + out_rf_path, + site_packages_rf_path, + package = package, + version_str = version_str, + dist_info_dir = dist_info_dir, is_windows = is_windows, should_precompile = should_precompile, keep_source = keep_source, @@ -464,6 +627,13 @@ def _py_wheel_library_impl(ctx): runfiles = runfiles.build(ctx) cc_info = collect_cc_info(ctx) + has_pyi = ( + _has_pyi_files(ctx.attr.extracted_files, keep_source = keep_source) or + _has_pyi_files( + ["site-packages/" + sp.strip("/") for sp in ctx.attr.site_paths if sp.strip("/")], + keep_source = keep_source, + ) + ) py_info, builtins_py_info = create_py_info( ctx, original_sources = [out], @@ -473,7 +643,7 @@ def _py_wheel_library_impl(ctx): implicit_pyc_source_files = [], imports = imports, venv_symlinks = venv_symlinks, - pyi_files = [out] if _has_pyi_files(ctx.attr.extracted_files, keep_source = keep_source) else [], + pyi_files = [out] if has_pyi else [], srcs_version = "ALL", pyi_deps = [], ) @@ -483,6 +653,7 @@ def _py_wheel_library_impl(ctx): py_info, PyInstalledWheelInfo( directory = out, + entry_points = entry_points_out, keep_source = keep_source, precompiled = should_precompile, settings_key = settings_key, @@ -490,7 +661,10 @@ def _py_wheel_library_impl(ctx): ), create_instrumented_files_info(ctx, source_attributes = []), PyCcLinkParamsInfo(cc_info = cc_info), - create_output_group_info(py_info.transitive_sources, extra_groups = {}), + create_output_group_info( + py_info.transitive_sources, + extra_groups = {"dist_info": depset([entry_points_out])}, + ), ] if builtins_py_info: providers.append(builtins_py_info) @@ -518,10 +692,13 @@ settings (`--//tools/precompiler:execution_requirements` and `TreeArtifact` (and `PyInfo.direct_original_sources` / `transitive_original_sources` reference that sourceless directory, so static analysis and coverage tools will not see `.py` sources for the wheel). When -`.pyi` stubs or `py.typed` markers are present (`py.typed` without `.pyi` files -is ignored when sources are omitted), `PyInfo.direct_pyi_files` / +`.pyi` stubs or `py.typed` markers are present in `extracted_files` (or +explicitly listed in `site_paths` for action-built sdists; `py.typed` without +`.pyi` files is ignored when sources are omitted), `PyInfo.direct_pyi_files` / `transitive_pyi_files` contains the installed wheel `TreeArtifact` directory; -consumers must handle directory `File`s. +consumers must handle directory `File`s. For action-built sdists whose +`site_paths` only list package directory names, `pyi_files` is empty unless +`.pyi` or `py.typed` paths are included in `site_paths`. ::: """, attrs = PY_WHEEL_LIBRARY_ATTRS, diff --git a/python/private/pypi/py_wheel_transform.bzl b/python/private/pypi/py_wheel_transform.bzl index 1bece1af4c..0a2dd2beff 100644 --- a/python/private/pypi/py_wheel_transform.bzl +++ b/python/private/pypi/py_wheel_transform.bzl @@ -5,9 +5,13 @@ load("//python/private:common.bzl", "actions_run") load("//python/private:py_internal.bzl", _py_builtins = "py_internal") load("//python/private:rule_builders.bzl", "ruleb") load("//python/private:toolchain_types.bzl", "EXEC_TOOLS_TOOLCHAIN_TYPE") +load(":py_sdist_wheel.bzl", "PyBuiltWheelInfo") def _py_wheel_transform_impl(ctx): - wheel_input = ctx.file.wheel + built_info = ( + ctx.attr.wheel[PyBuiltWheelInfo] if PyBuiltWheelInfo in ctx.attr.wheel else None + ) + wheel_input = built_info.directory if built_info != None else ctx.file.wheel out_wheel_dir = ctx.actions.declare_directory(ctx.attr.name + ".whldir") args = ctx.actions.args() @@ -44,7 +48,16 @@ def _py_wheel_transform_impl(ctx): progress_message = "Transforming wheel %{input} into %{output}", ) - return [DefaultInfo(files = depset([out_wheel_dir]))] + providers = [DefaultInfo(files = depset([out_wheel_dir]))] + if built_info != None: + providers.append( + PyBuiltWheelInfo( + directory = out_wheel_dir, + distribution = built_info.distribution, + version = built_info.version, + ), + ) + return providers py_wheel_transform = ruleb.Rule( implementation = _py_wheel_transform_impl, @@ -79,7 +92,11 @@ wrapper's `RUNFILES_*` and `PYTHONSAFEPATH`/`PYTHONPATH`/`PYTHONHOME` launcher v "wheel": lambda: attrb.Label( mandatory = True, allow_single_file = True, - doc = "The input `.whl` file or `.whldir` TreeArtifact directory.", + doc = """ +The input `.whl` file, `.whldir` TreeArtifact directory, or `py_sdist_wheel` +target (for action-built sdists in a pip hub, pass `@pypi//:whldir` rather +than `:whl`). +""", ), "_wheel_layout": lambda: attrb.Label( allow_single_file = True, diff --git a/python/private/pypi/wheel_layout.py b/python/private/pypi/wheel_layout.py index cbab8e93cb..ec882f6504 100644 --- a/python/private/pypi/wheel_layout.py +++ b/python/private/pypi/wheel_layout.py @@ -160,18 +160,30 @@ def _resolve_wheel_entry_dest( name: str, parts: list[str], expected_data_dir: str, + *, + wheel_dist_info_dir: str = "", + target_dist_info_dir: str = "", ) -> str | None: if parts[-1] in _BAZEL_REPO_FILES: return None - if parts[0] != expected_data_dir: - return f"site-packages/{name}" - if len(parts) <= 2: - return None - dest_prefix = _DATA_CATEGORIES.get(parts[1]) - if not dest_prefix: - raise ValueError(f"Unknown .data category {parts[1]!r} in wheel entry {name!r}") - rel_path = "/".join(parts[2:]) - return f"{dest_prefix}/{rel_path}" if rel_path else None + if parts[0] == expected_data_dir: + if len(parts) <= 2: + return None + dest_prefix = _DATA_CATEGORIES.get(parts[1]) + if not dest_prefix: + raise ValueError( + f"Unknown .data category {parts[1]!r} in wheel entry {name!r}" + ) + rel_path = "/".join(parts[2:]) + return f"{dest_prefix}/{rel_path}" if rel_path else None + if ( + wheel_dist_info_dir + and target_dist_info_dir + and target_dist_info_dir != wheel_dist_info_dir + and parts[0] == wheel_dist_info_dir + ): + return f"site-packages/{target_dist_info_dir}/{'/'.join(parts[1:])}" + return f"site-packages/{name}" def _map_wheel_entry_destination( @@ -179,6 +191,9 @@ def _map_wheel_entry_destination( parts: list[str], expected_data_dir: str, seen_destinations: dict[str, str], + *, + wheel_dist_info_dir: str = "", + target_dist_info_dir: str = "", ) -> str | None: """Map a wheel archive entry to its installed relative path under the TreeArtifact root. @@ -186,7 +201,13 @@ def _map_wheel_entry_destination( distinct wheel entries map to the same destination path (checked case-insensitively across platforms). """ - dest_rel = _resolve_wheel_entry_dest(name, parts, expected_data_dir) + dest_rel = _resolve_wheel_entry_dest( + name, + parts, + expected_data_dir, + wheel_dist_info_dir=wheel_dist_info_dir, + target_dist_info_dir=target_dist_info_dir, + ) if dest_rel is None: return None @@ -211,6 +232,8 @@ def plan_wheel_entries( entry_points_content: str | None, srcs_exclude_rx: list[re.Pattern[str]], data_exclude_rx: list[re.Pattern[str]], + *, + target_dist_info_dir: str = "", ) -> Iterator[tuple[zipfile.ZipInfo, str, bool]]: """Yield `(info, dest_rel_or_script_name, is_shebang_script)` for wheel entries.""" expected_data_dir = expected_data_dir_for_dist_info(dist_info_dir) @@ -228,6 +251,8 @@ def plan_wheel_entries( parts, expected_data_dir, seen_destinations, + wheel_dist_info_dir=dist_info_dir, + target_dist_info_dir=target_dist_info_dir, ) if dest_rel is None: continue diff --git a/python/private/pypi/wheel_record_rewriter.py b/python/private/pypi/wheel_record_rewriter.py index deaad65be9..cc579f166b 100644 --- a/python/private/pypi/wheel_record_rewriter.py +++ b/python/private/pypi/wheel_record_rewriter.py @@ -19,10 +19,20 @@ def rewrite_record_lines( target_os: str, data_dir_basename: str, rewritten_scripts: Set[str], + *, + wheel_dist_info_dir: str = "", + target_dist_info_dir: str = "", ) -> list[str]: - """Rewrite `.data//...` RECORD lines to installed paths.""" - data_prefix = data_dir_basename + "/" - quoted_data_prefix = '"' + data_prefix + """Rewrite `.data//...` and renamed `.dist-info/` RECORD lines.""" + data_prefix = (data_dir_basename + "/") if data_dir_basename else "" + quoted_data_prefix = ('"' + data_prefix) if data_prefix else "" + rename_dist = bool( + wheel_dist_info_dir + and target_dist_info_dir + and wheel_dist_info_dir != target_dist_info_dir + ) + dist_prefix = (wheel_dist_info_dir + "/") if rename_dist else "" + quoted_dist_prefix = ('"' + dist_prefix) if rename_dist else "" if target_os == "windows": data_repl = "../../" @@ -41,10 +51,19 @@ def rewrite_record_lines( for raw_line in lines: line = raw_line.rstrip("\r\n") - if line.startswith(quoted_data_prefix): + if rename_dist and line.startswith(quoted_dist_prefix): + out_lines.append( + f'"{target_dist_info_dir}/{line[len(quoted_dist_prefix) :]}\n' + ) + continue + if rename_dist and line.startswith(dist_prefix): + out_lines.append(f"{target_dist_info_dir}/{line[len(dist_prefix) :]}\n") + continue + + if data_prefix and line.startswith(quoted_data_prefix): quote = '"' rest = line[len(quoted_data_prefix) :] - elif line.startswith(data_prefix): + elif data_prefix and line.startswith(data_prefix): quote = "" rest = line[len(data_prefix) :] else: diff --git a/tests/pypi/py_wheel_library/BUILD.bazel b/tests/pypi/py_wheel_library/BUILD.bazel index d4c72c9f76..67a5935a64 100644 --- a/tests/pypi/py_wheel_library/BUILD.bazel +++ b/tests/pypi/py_wheel_library/BUILD.bazel @@ -243,7 +243,7 @@ py_sdist_wheel( ":classic_bdep", ":custom_build_helper", ":custom_shadow_dep", - ":demo_wheel_lib", + ":demo_wheel_lib_venv", ], config_settings_list = { "--global-option": [ @@ -303,6 +303,26 @@ whl_filegroup( whl = ":sdist_demo-0.5.0.whldir", ) +py_wheel_transform( + name = "transformed_sdist_demo_whl", + env = {"EXPECTED_SH_ENV": "from_transform"}, + transform = ":sh_transform", + wheel = ":sdist_demo-0.5.0.whldir", +) + +py_wheel_library( + name = "sdist_demo_wheel_lib", + site_paths = ["sdist_demo"], + wheel = ":transformed_sdist_demo_whl", +) + +py_wheel_library( + name = "sdist_demo_wheel_lib_venv", + experimental_venvs_site_packages = "//python/config_settings:venvs_site_packages", + site_paths = ["sdist_demo"], + wheel = ":sdist_demo-0.5.0.whldir", +) + genrule( name = "gen_cext_sdist", outs = ["sdist_cext-0.1.0.tar.gz"], @@ -342,6 +362,10 @@ filegroup( py_wheel_library( name = "sdist_cext_wheel_lib", + site_paths = [ + "cext_demo", + "sdist_cext", + ], target_compatible_with = select({ "@platforms//os:windows": ["@platforms//:incompatible"], "//conditions:default": [], @@ -403,6 +427,7 @@ py_test( }, deps = [ ":demo_wheel_lib", + ":sdist_demo_wheel_lib", ], ) @@ -425,6 +450,7 @@ py_reconfig_test( venvs_site_packages = "yes", deps = [ ":demo_wheel_lib_venv", + ":sdist_demo_wheel_lib_venv", ], ) @@ -445,6 +471,7 @@ py_reconfig_test( precompile_flag = "enabled", deps = [ ":demo_wheel_lib", + ":sdist_demo_wheel_lib", ], ) @@ -468,6 +495,7 @@ py_reconfig_test( venvs_site_packages = "yes", deps = [ ":demo_wheel_lib_venv", + ":sdist_demo_wheel_lib_venv", ], ) @@ -522,5 +550,6 @@ py_reconfig_test( venvs_site_packages = "yes", deps = [ ":demo_wheel_lib_reuse_omit", + ":sdist_demo_wheel_lib_venv", ], ) diff --git a/tests/pypi/py_wheel_library/py_wheel_library_bzl_tests.bzl b/tests/pypi/py_wheel_library/py_wheel_library_bzl_tests.bzl index 437c318363..65767d675b 100644 --- a/tests/pypi/py_wheel_library/py_wheel_library_bzl_tests.bzl +++ b/tests/pypi/py_wheel_library/py_wheel_library_bzl_tests.bzl @@ -68,11 +68,29 @@ def _test_pyi_files_exposed_when_stubs_present(name): "site-packages/foo/__init__.py", ], ) + rt_util.helper_target( + py_wheel_library, + name = name + "_sdist_site_paths", + wheel = name + "_whl", + distribution = "foo", + version = "1.0", + site_paths = ["foo"], + ) + rt_util.helper_target( + py_wheel_library, + name = name + "_sdist_site_paths_with_pyi", + wheel = name + "_whl", + distribution = "foo", + version = "1.0", + site_paths = ["foo", "foo/__init__.pyi"], + ) analysis_test( name = name, impl = _test_pyi_files_exposed_when_stubs_present_impl, targets = { "no_stubs": name + "_no_stubs", + "sdist_site_paths": name + "_sdist_site_paths", + "sdist_site_paths_with_pyi": name + "_sdist_site_paths_with_pyi", "with_py_typed": name + "_with_py_typed", "with_py_typed_omit": name + "_with_py_typed_omit", "with_pyi": name + "_with_pyi", @@ -105,6 +123,18 @@ def _test_pyi_files_exposed_when_stubs_present_impl(env, targets): factory = py_info_subject, ) no_stubs_info.direct_pyi_files().contains_exactly([]) + sdist_site_paths_info = env.expect.that_target(targets.sdist_site_paths).provider( + PyInfo, + factory = py_info_subject, + ) + sdist_site_paths_info.direct_pyi_files().contains_exactly([]) + sdist_site_paths_with_pyi_info = env.expect.that_target(targets.sdist_site_paths_with_pyi).provider( + PyInfo, + factory = py_info_subject, + ) + sdist_site_paths_with_pyi_info.direct_pyi_files().contains_exactly([ + "{package}/" + targets.sdist_site_paths_with_pyi.label.name, + ]) _tests.append(_test_pyi_files_exposed_when_stubs_present) @@ -153,6 +183,12 @@ def _test_precompile_flags_and_providers_impl(env, targets): default_info.transitive_sources().contains_exactly([ "{package}/" + targets.default.label.name, ]) + default_t.output_group("dist_info").contains_exactly([ + "{package}/" + targets.default.label.name + ".dist_info/entry_points.txt", + ]) + default_t.action_generating("{package}/" + targets.default.label.name).argv().contains_at_least([ + "--entry-points-output", + ]) enabled_t = env.expect.that_target(targets.enabled) enabled_info = enabled_t.provider(PyInfo, factory = py_info_subject) diff --git a/tests/pypi/py_wheel_library/py_wheel_library_test.py b/tests/pypi/py_wheel_library/py_wheel_library_test.py index f6c33be20a..8041a80ec0 100644 --- a/tests/pypi/py_wheel_library/py_wheel_library_test.py +++ b/tests/pypi/py_wheel_library/py_wheel_library_test.py @@ -73,6 +73,12 @@ def test_post_install_patch_and_transform(self): self.assertTrue(copied_exec.is_file()) self.assertTrue(os.access(copied_exec, os.X_OK)) + def test_sdist_wheel_and_pre_build_patch(self): + sys.dont_write_bytecode = True + sdist_demo = importlib.import_module("sdist_demo") + self.assertEqual(sdist_demo.GREETING, "patched_before_build") + self.assertEqual(importlib.metadata.version("sdist-demo"), "0.5.0") + if __name__ == "__main__": unittest.main() diff --git a/tests/pypi/py_wheel_library/sh_transform.sh b/tests/pypi/py_wheel_library/sh_transform.sh index d72469ae01..8813044d55 100755 --- a/tests/pypi/py_wheel_library/sh_transform.sh +++ b/tests/pypi/py_wheel_library/sh_transform.sh @@ -17,4 +17,8 @@ for var in RUNFILES_DIR RUNFILES_MANIFEST_FILE PYTHONSAFEPATH PYTHONPATH PYTHONH fi done +if [[ "$(basename "${WHEEL_FILE}")" != *-*-*-*-*.whl ]]; then + echo "ERROR: WHEEL_FILE basename is not a canonical PEP 427 wheel filename: $(basename "${WHEEL_FILE}")" >&2 + exit 1 +fi cp "${WHEEL_FILE}" "${WHEEL_OUTPUT_ROOT}/$(basename "${WHEEL_FILE}")" diff --git a/tests/pypi/py_wheel_library/wheel_layout_and_installer_test.py b/tests/pypi/py_wheel_library/wheel_layout_and_installer_test.py index 51f2ff97aa..74f43ac291 100644 --- a/tests/pypi/py_wheel_library/wheel_layout_and_installer_test.py +++ b/tests/pypi/py_wheel_library/wheel_layout_and_installer_test.py @@ -851,6 +851,80 @@ def test_wheel_files_extractor(self): [("site-packages/fgpkg/missing.txt", root / "extracted/m.txt")], ) + def test_site_paths_validation_and_dist_info_rename(self): + with tempfile.TemporaryDirectory() as tmp: + tmp_path = pathlib.Path(tmp) + whl = _write_zip( + tmp_path / "Google.Pkg-1.0-py3-none-any.whl", + { + "Google.Pkg-1.0.dist-info/METADATA": "Name: Google.Pkg\nVersion: 1.0\n", + "Google.Pkg-1.0.dist-info/WHEEL": "Wheel-Version: 1.0\nTag: py3-none-any\n", + "Google.Pkg-1.0.dist-info/RECORD": ( + "Google.Pkg-1.0.dist-info/METADATA,sha256=abc,10\n" + "google/protobuf/__init__.py,sha256=def,6\n" + ), + "google/protobuf/__init__.py": "X = 1\n", + "google/_upb/__init__.py": "Y = 2\n", + }, + ) + with self.assertRaisesRegex(ValueError, "uncovered"): + action_whl_installer.install_wheel( + wheel_path=whl, + dest_dir=tmp_path / "out_empty", + expected_site_paths=[], + ) + with self.assertRaisesRegex(ValueError, "google/_upb/__init__.py"): + action_whl_installer.install_wheel( + wheel_path=whl, + dest_dir=tmp_path / "out_uncovered", + expected_site_paths=["google/protobuf"], + ) + with self.assertRaisesRegex(ValueError, "_missing_helper.py"): + action_whl_installer.install_wheel( + wheel_path=whl, + dest_dir=tmp_path / "out_missing", + expected_site_paths=[ + "google/protobuf", + "google/_upb", + "_missing_helper.py", + ], + ) + out_ok = tmp_path / "out_ok" + ep_out_empty = tmp_path / "out_ok.dist_info/entry_points.txt" + action_whl_installer.install_wheel( + wheel_path=whl, + dest_dir=out_ok, + entry_points_output=ep_out_empty, + expected_site_paths=["google/protobuf", "google/_upb"], + dist_info_dir_override="google_pkg-1.0.dist-info", + ) + record = ( + out_ok / "site-packages/google_pkg-1.0.dist-info/RECORD" + ).read_text(encoding="utf-8") + self.assertIn("google_pkg-1.0.dist-info/METADATA,sha256=abc,10\n", record) + self.assertNotIn("Google.Pkg-1.0.dist-info/", record) + self.assertEqual(ep_out_empty.read_text(encoding="utf-8"), "") + + whl_ep = _write_zip( + tmp_path / "Ep.Pkg-1.0-py3-none-any.whl", + { + "Ep.Pkg-1.0.dist-info/METADATA": "Name: Ep.Pkg\nVersion: 1.0\n", + "Ep.Pkg-1.0.dist-info/entry_points.txt": "[console_scripts]\nep_cli = ep_pkg:main\n", + "ep_pkg/__init__.py": "def main(): pass\n", + }, + ) + ep_out = tmp_path / "out_ep.dist_info/entry_points.txt" + action_whl_installer.install_wheel( + wheel_path=whl_ep, + dest_dir=tmp_path / "out_ep", + entry_points_output=ep_out, + dist_info_dir_override="ep_pkg-1.0.dist-info", + ) + self.assertEqual( + ep_out.read_text(encoding="utf-8"), + "[console_scripts]\nep_cli = ep_pkg:main\n", + ) + if __name__ == "__main__": unittest.main() From 85898869c32db1bea9ff8ac78451fa763dd8d315 Mon Sep 17 00:00:00 2001 From: Jeremy Volkman Date: Mon, 26 Oct 2026 01:11:34 +0000 Subject: [PATCH 5/9] feat(pypi): build sdists in actions when experimental_action_install is enabled Wire py_sdist_wheel into pip_archive and whl_library_targets when experimental_action_install is enabled: - Add inspect_sdist.py for static metadata, dependency, entry point, and site_paths extraction from sdists at repository evaluation time without executing PEP 517 builds. - Update pip_archive, whl_library_targets, whl_library_srcs, and generate_whl_library_build_bazel to emit py_sdist_wheel + py_wheel_library targets for sdists in action mode via an sdist config dict. - Add sdist_build_deps, sdist_config_settings, and site_paths attributes to package_annotation and pip.whl_mods. - Add unit tests in inspect_sdist_test.py, whl_library_srcs_tests.bzl, and generate_whl_library_build_bazel_tests.bzl. --- python/private/pypi/BUILD.bazel | 28 +- python/private/pypi/attrs.bzl | 27 +- python/private/pypi/extension.bzl | 41 +- .../pypi/generate_whl_library_build_bazel.bzl | 193 +++++- python/private/pypi/hub_builder.bzl | 2 + python/private/pypi/inspect_sdist.py | 552 ++++++++++++++++++ python/private/pypi/labels.bzl | 1 + python/private/pypi/package_annotation.bzl | 20 +- python/private/pypi/patch_and_extract_whl.bzl | 147 +++-- python/private/pypi/pip_archive.bzl | 142 ++++- python/private/pypi/wheel_layout.py | 8 +- .../private/pypi/whl_library_deps_targets.bzl | 37 +- python/private/pypi/whl_library_srcs.bzl | 139 ++++- python/private/pypi/whl_library_targets.bzl | 93 ++- ...generate_whl_library_build_bazel_tests.bzl | 139 +++++ tests/pypi/py_wheel_library/BUILD.bazel | 10 + .../py_wheel_library/inspect_sdist_test.py | 197 +++++++ .../py_wheel_library_bzl_tests.bzl | 46 ++ .../whl_library_srcs_tests.bzl | 132 +++++ 19 files changed, 1847 insertions(+), 107 deletions(-) create mode 100644 python/private/pypi/inspect_sdist.py create mode 100644 tests/pypi/py_wheel_library/inspect_sdist_test.py diff --git a/python/private/pypi/BUILD.bazel b/python/private/pypi/BUILD.bazel index 972b020baa..7a48248791 100644 --- a/python/private/pypi/BUILD.bazel +++ b/python/private/pypi/BUILD.bazel @@ -27,6 +27,15 @@ exports_files( visibility = ["//visibility:public"], ) +exports_files( + srcs = [ + "inspect_sdist.py", + "inspect_whl.py", + "wheel_layout.py", + ], + visibility = ["//:__subpackages__"], +) + filegroup( name = "action_whl_installer_helpers", srcs = [ @@ -86,6 +95,7 @@ py_library( name = "wheel_installer_lib", srcs = [ "action_whl_installer.py", + "inspect_sdist.py", "inspect_whl.py", "wheel_files_extractor.py", "wheel_layout.py", @@ -254,7 +264,10 @@ bzl_library( bzl_library( name = "generate_whl_library_build_bazel", srcs = ["generate_whl_library_build_bazel.bzl"], - deps = ["//python/private:text_util"], + deps = [ + "//python/private:text_util", + "@bazel_skylib//lib:types", + ], ) bzl_library( @@ -589,8 +602,13 @@ bzl_library( name = "whl_library_targets", srcs = ["whl_library_targets.bzl"], deps = [ + ":env_marker_setting", + ":labels", + ":pep508_deps", + ":py_sdist_wheel", ":whl_library_deps_targets", ":whl_library_srcs", + "//python/private:normalize_name", ], ) @@ -621,14 +639,20 @@ bzl_library( deps = [ ":attrs", ":deps", + ":generate_whl_library_build_bazel", ":patch_and_extract_whl", + ":pep508_requirement", ":pypi_repo_utils", ":urllib", + ":version_from_filename", ":whl_archive", + ":whl_metadata", "//python/private:auth", "//python/private:envsubst", "//python/private:is_standalone_interpreter", + "//python/private:normalize_name", "//python/private:repo_utils", + "//python/private:version", ], ) @@ -786,8 +810,10 @@ bzl_library( srcs = ["whl_library_srcs.bzl"], deps = [ ":gen_wheel_record", + ":generate_whl_library_build_bazel", ":labels", ":namespace_pkgs", + ":py_sdist_wheel", ":py_wheel_extract_files", ":py_wheel_library", ":venv_entry_point", diff --git a/python/private/pypi/attrs.bzl b/python/private/pypi/attrs.bzl index 9fce3153e2..4a2a1ed980 100644 --- a/python/private/pypi/attrs.bzl +++ b/python/private/pypi/attrs.bzl @@ -80,7 +80,10 @@ In this mode: files. - The `:data` and `:extracted_whl_files` targets alias the installed wheel `TreeArtifact` directory rather than separate `filegroup` subsets, and - `:dist_info` exposes only `entry_points.txt` (when present in the wheel). + `:dist_info` exposes only `entry_points.txt` (written at fetch time for + downloaded wheels, or extracted via `OutputGroupInfo.dist_info` for + action-built sdists, which runs `PyWheelInstall` in the exec configuration as + well when `py_console_script_binary` is used). - With `--//python/config_settings:venvs_site_packages=yes`, single-file virtual environment links into wheel `TreeArtifact`s (such as top-level modules, shared libraries, namespace `__init__.py` files, and merged conflict paths) @@ -98,10 +101,24 @@ In this mode: - In `pip.whl_mods`, `filegroups`, `copy_files`, and `copy_executables` extract files from downloaded wheels via `py_wheel_extract_files`, and `additive_build_content` should use `wheel_glob(...)` (or - `load(":wheel_files.bzl", "wheel_glob")` from external `.bzl` macros), - `py_wheel_headers`, `py_wheel_transform`, `post_install_patches`, or - `py_wheel_extract_files` instead of `native.glob(...)` over extracted wheel - paths (`site-packages/`, `include/`, `data/`). + `load(":wheel_files.bzl", "wheel_glob")` from external `.bzl` macros; note + that `:wheel_files.bzl` is generated only when `experimental_action_install` + is enabled, whereas `wheel_glob(...)` inside `additive_build_content` is + auto-loaded in both modes), `py_wheel_headers`, `py_wheel_transform`, + `post_install_patches`, or `py_wheel_extract_files` instead of + `native.glob(...)` over extracted wheel paths (`site-packages/`, `include/`, + `data/`). Note that `wheel_glob(...)` returns `:_extracted/` labels in + action mode and `` in default mode; use `py_wheel_headers` or + `wheel_extract_prefix() + ""` rather than hardcoding `"_extracted/..."` + in `includes`. +- Source distributions (`sdist`) are inspected statically at repository fetch + time and built into a wheel via `py_sdist_wheel` during the build phase; + `:whl` resolves to the `-.sdist_build.whl` file output while + `:whldir` resolves to the `.whldir` directory artifact (which should be used + for `py_wheel_transform`), `pip.override(patches = ...)` patches apply to the + unpacked sdist before building (`pre_build_patches`), and sdists installing + top-level compiled extension modules directly under `site-packages/` require + `--//python/config_settings:venvs_site_packages=no`. ::: :::{versionadded} VERSION_NEXT_FEATURE diff --git a/python/private/pypi/extension.bzl b/python/private/pypi/extension.bzl index 0d788319da..5c2cdc4baa 100644 --- a/python/private/pypi/extension.bzl +++ b/python/private/pypi/extension.bzl @@ -47,6 +47,15 @@ def _whl_mods_impl(whl_mods_dict): # to create the different JSON files. Mock structs in unit tests # may omit newer optional fields such as `filegroups`. for whl_name, mods in whl_maps.items(): + optional_fields = {} + if hasattr(mods, "filegroups") and mods.filegroups: + optional_fields["filegroups"] = mods.filegroups + if hasattr(mods, "sdist_build_deps") and mods.sdist_build_deps: + optional_fields["sdist_build_deps"] = mods.sdist_build_deps + if hasattr(mods, "sdist_config_settings") and mods.sdist_config_settings: + optional_fields["sdist_config_settings"] = mods.sdist_config_settings + if hasattr(mods, "site_paths") and mods.site_paths: + optional_fields["site_paths"] = mods.site_paths whl_mods[whl_name] = json.encode(struct( additive_build_content = mods.build_content, copy_files = mods.copy_files, @@ -54,7 +63,7 @@ def _whl_mods_impl(whl_mods_dict): data = mods.data, data_exclude_glob = mods.data_exclude_glob, srcs_exclude_glob = mods.srcs_exclude_glob, - **({"filegroups": mods.filegroups} if hasattr(mods, "filegroups") and mods.filegroups else {}) + **optional_fields )) _whl_mods_repo( @@ -223,6 +232,9 @@ You cannot use both the additive_build_content and additive_build_content_file a data = whl_mod.data, data_exclude_glob = whl_mod.data_exclude_glob, filegroups = whl_mod.filegroups, + sdist_build_deps = [str(d) for d in whl_mod.sdist_build_deps], + sdist_config_settings = whl_mod.sdist_config_settings, + site_paths = whl_mod.site_paths, srcs_exclude_glob = whl_mod.srcs_exclude_glob, ) @@ -1100,6 +1112,33 @@ cannot have a child module that uses the same `hub_name`. """, mandatory = True, ), + "sdist_build_deps": attr.label_list( + doc = """ +(list, optional): Explicit build dependency labels for `py_sdist_wheel` when +building an sdist in an action. + +:::{versionadded} VERSION_NEXT_FEATURE +::: +""", + ), + "sdist_config_settings": attr.string_dict( + doc = """ +(dict, optional): PEP 517 `--config-settings` key/value pairs for +`py_sdist_wheel` when building an sdist in an action. + +:::{versionadded} VERSION_NEXT_FEATURE +::: +""", + ), + "site_paths": attr.string_list( + doc = """ +(list, optional): Override predicted `site-packages/` paths when building an +sdist in an action. + +:::{versionadded} VERSION_NEXT_FEATURE +::: +""", + ), "srcs_exclude_glob": attr.string_list( doc = """\ (list, optional): A list of labels to add as `srcs` to the generated diff --git a/python/private/pypi/generate_whl_library_build_bazel.bzl b/python/private/pypi/generate_whl_library_build_bazel.bzl index fa0cb0386f..a6918ae610 100644 --- a/python/private/pypi/generate_whl_library_build_bazel.bzl +++ b/python/private/pypi/generate_whl_library_build_bazel.bzl @@ -14,6 +14,7 @@ """Generate the BUILD.bazel contents for a repo defined by a whl_library.""" +load("@bazel_skylib//lib:types.bzl", "types") load("//python/private:text_util.bzl", "render") _RENDER = { @@ -29,6 +30,7 @@ _RENDER = { "include": str, "repo": lambda maybe_label: repr(str(maybe_label)), "requires_dist": render.list, + "sdist": render.dict, "shebang_scripts": render.list, "srcs_exclude": render.list, "tags": render.list, @@ -62,6 +64,151 @@ def _check_additive_build_content_for_glob(content): return True return False +_QUIET_SDIST_PIP_FLAGS_NO_VALUE = { + "--disable-pip-version-check": True, + "--isolated": True, + "--no-cache-dir": True, + "--no-color": True, + "--no-deps": True, + "--no-index": True, + "--pre": True, + "--prefer-binary": True, + "--quiet": True, + "--require-hashes": True, + "--use-pep517": True, + "--verbose": True, + "-q": True, + "-v": True, +} + +_QUIET_SDIST_PIP_FLAGS_WITH_VALUE = { + "--abi": True, + "--cache-dir": True, + "--cert": True, + "--client-cert": True, + "--exists-action": True, + "--extra-index-url": True, + "--find-links": True, + "--implementation": True, + "--index-url": True, + "--keyring-provider": True, + "--log": True, + "--no-binary": True, + "--only-binary": True, + "--platform": True, + "--progress-bar": True, + "--proxy": True, + "--python-version": True, + "--retries": True, + "--timeout": True, + "--trusted-host": True, + "-f": True, + "-i": True, +} + +def _add_config_setting(config_settings, key, value): + if key in config_settings: + existing = config_settings[key] + if types.is_list(existing): + existing.append(value) + else: + config_settings[key] = [existing, value] + else: + config_settings[key] = value + +def split_sdist_config_settings(sdist_dict): + """Split list-valued entries in `sdist_dict["config_settings"]` into `config_settings_list`. + + Args: + sdist_dict: {type}`dict` Mutable sdist keyword arguments dict updated in place. + """ + if "config_settings" not in sdist_dict: + return + scalar_cs = {} + list_cs = dict(sdist_dict.get("config_settings_list", {})) + for k, v in sdist_dict["config_settings"].items(): + if types.is_list(v): + list_cs[k] = v + else: + scalar_cs[k] = v + if scalar_cs: + sdist_dict["config_settings"] = scalar_cs + else: + sdist_dict.pop("config_settings") + if list_cs: + sdist_dict["config_settings_list"] = list_cs + +def parse_sdist_extra_pip_args(extra_pip_args, logger = None, name = ""): + """Parse `extra_pip_args` for an action-mode sdist build. + + Extracts `-C` / `--config-settings` into a `config_settings` dict (accumulating + repeated keys into lists), silently ignores standard index/network/fetch flags, + and warns via `logger.warn` on any other unrecognized args. + + Args: + extra_pip_args: {type}`list[str]` Extra pip arguments configured on the repo. + logger: Optional repository logger used to emit warnings. + name: {type}`str` Package or sdist filename for warning messages. + + Returns: + {type}`dict[str, str | list[str]]` Parsed PEP 517 config settings. + """ + config_settings = {} + ignored = [] + mode = None + + for raw_arg in extra_pip_args or []: + if mode == "config_setting": + k, has_eq, v = raw_arg.partition("=") + _add_config_setting(config_settings, k, v if has_eq else "") + mode = None + continue + if mode == "skip_value": + mode = None + continue + + if raw_arg in ("-C", "--config-settings", "--config-setting"): + mode = "config_setting" + continue + if raw_arg.startswith("--config-settings="): + kv = raw_arg[len("--config-settings="):] + k, has_eq, v = kv.partition("=") + _add_config_setting(config_settings, k, v if has_eq else "") + continue + if raw_arg.startswith("--config-setting="): + kv = raw_arg[len("--config-setting="):] + k, has_eq, v = kv.partition("=") + _add_config_setting(config_settings, k, v if has_eq else "") + continue + if raw_arg.startswith("-C") and len(raw_arg) > 2: + kv = raw_arg[2:] + k, has_eq, v = kv.partition("=") + if has_eq: + _add_config_setting(config_settings, k, v) + continue + + if raw_arg in _QUIET_SDIST_PIP_FLAGS_NO_VALUE: + continue + if raw_arg in _QUIET_SDIST_PIP_FLAGS_WITH_VALUE: + mode = "skip_value" + continue + flag_name, has_eq, _ = raw_arg.partition("=") + if has_eq and flag_name in _QUIET_SDIST_PIP_FLAGS_WITH_VALUE: + continue + if (raw_arg.startswith("-i") or raw_arg.startswith("-f")) and len(raw_arg) > 2 and not raw_arg.startswith("--"): + continue + + ignored.append(raw_arg) + + if ignored and logger: + logger.warn( + "In '{}', extra_pip_args {} are ignored in experimental_action_install sdist builds (use -C / --config-settings or sdist_config_settings instead).".format( + name, + ignored, + ), + ) + return config_settings + def generate_whl_library_build_bazel( *, metadata_version, @@ -101,14 +248,28 @@ def generate_whl_library_build_bazel( ] kwargs["tags"] = tags - if not requires_dist: + sdist = kwargs.get("sdist") + if sdist != None: + sdist = dict(sdist) + if annotation: + if hasattr(annotation, "sdist_build_deps") and annotation.sdist_build_deps: + sdist["build_deps"] = annotation.sdist_build_deps + if hasattr(annotation, "sdist_config_settings") and annotation.sdist_config_settings: + sdist["config_settings"] = dict(sdist.get("config_settings", {})) | dict(annotation.sdist_config_settings) + if hasattr(annotation, "site_paths") and annotation.site_paths: + sdist["site_paths"] = annotation.site_paths + split_sdist_config_settings(sdist) + kwargs["sdist"] = {k: sdist[k] for k in sorted(sdist)} + + if not requires_dist and not (sdist and sdist.get("build_requires")): # no deps, we can leave the extra loads out pass elif config_load: loads.append("""load("{}", "{}")""".format(config_load, "packages")) kwargs["include"] = "packages" - kwargs["requires_dist"] = requires_dist - else: + if requires_dist: + kwargs["requires_dist"] = requires_dist + elif requires_dist: kwargs["requires_dist"] = requires_dist loads.extend([ @@ -177,7 +338,14 @@ def generate_whl_library_build_bazel( return contents.rstrip() + "\n" def generate_wheel_files_bzl(extracted_files): - """Generate the contents of `wheel_files.bzl` for a wheel repository.""" + """Generate the contents of `wheel_files.bzl` for a wheel repository. + + Args: + extracted_files: {type}`list[str]` Sorted list of wheel-relative file paths. + + Returns: + {type}`str` Starlark source for `wheel_files.bzl`. + """ return """\ \"\"\"Generated wheel file list and wheel_glob wrapper.\"\"\" @@ -206,3 +374,20 @@ def wheel_glob( """.format( files = render.list(extracted_files), ) + +def generate_sdist_wheel_files_bzl(): + """Generate stub `wheel_files.bzl` for an action-built sdist repository. + + Returns: + {type}`str` Starlark source for `wheel_files.bzl` that fails with guidance on `wheel_glob()`. + """ + return """\ +FILES = [] + +def wheel_glob(*args, **kwargs): + fail( + "wheel_glob() cannot be used with an action-built sdist because wheel contents " + + "are not known at loading time under experimental_action_install. Use a " + + "pre-built wheel or py_wheel_headers / py_wheel_transform instead.", + ) +""" diff --git a/python/private/pypi/hub_builder.bzl b/python/private/pypi/hub_builder.bzl index 2ea61e08d5..b3fe8c65c7 100644 --- a/python/private/pypi/hub_builder.bzl +++ b/python/private/pypi/hub_builder.bzl @@ -609,6 +609,8 @@ def _create_whl_repos( whl_modifications = whl_modifications, ) for src in whl.srcs: + if not src.filename.endswith(".whl") and whl_library_args.get("experimental_action_install"): + _add_extra_aliases(self, {whl.name: ["whldir"]}) repo = _whl_repo( src = src, index_url = whl.index_url, diff --git a/python/private/pypi/inspect_sdist.py b/python/private/pypi/inspect_sdist.py new file mode 100644 index 0000000000..336ea1f7fb --- /dev/null +++ b/python/private/pypi/inspect_sdist.py @@ -0,0 +1,552 @@ +"""Inspect a Python source distribution (.tar.gz / .zip) without building it. + +Writes a JSON object to stdout containing `build_requires`, +`entry_points_content`, `namespace_package_files`, `provides_extra`, +`requires_dist`, and `site_paths` for BUILD generation. + +Usage: + python3 -I -B inspect_sdist.py --sdist path/to/pkg-1.0.tar.gz +""" + +from __future__ import annotations + +import argparse +import email.parser +import importlib +import json +import posixpath +import sys +import tarfile +import zipfile +from pathlib import Path +from typing import TypedDict + +_THIS_DIR = Path(__file__).parent +# Invoked directly via `rctx.execute([python, "inspect_sdist.py", ...])` without +# Bazel runfiles/package PYTHONPATH, so add the script's directory to import +# sibling `wheel_layout`. +if str(_THIS_DIR) not in sys.path: + sys.path.insert(0, str(_THIS_DIR)) + +from wheel_layout import is_pkgutil_namespace_init # noqa: E402 + +_PY_EXTENSIONS = frozenset({".py", ".pyi"}) +_EXCLUDED_TOP_DIRS = frozenset( + { + "benchmark", + "benchmarks", + "build", + "dist", + "doc", + "docs", + "example", + "examples", + "test", + "testing", + "tests", + } +) +_EXCLUDED_ROOT_MODULES = frozenset( + { + "conf.py", + "conftest.py", + "noxfile.py", + "setup.py", + "tasks.py", + } +) + + +def _read_archive_files(sdist_path: Path) -> tuple[list[str], dict[str, bytes]]: + """Read file list and key metadata/init files from an sdist archive.""" + raw_entries: list[str] = [] + raw_contents: dict[str, bytes] = {} + + def _should_read(name: str) -> bool: + base = posixpath.basename(name) + if base in ("PKG-INFO", "pyproject.toml", "__init__.py"): + return True + return ".egg-info/" in name and base in ( + "PKG-INFO", + "requires.txt", + "top_level.txt", + "entry_points.txt", + ) + + if zipfile.is_zipfile(sdist_path): + with zipfile.ZipFile(sdist_path) as zf: + for info in zf.infolist(): + if info.is_dir() or info.filename.endswith("/"): + continue + norm = posixpath.normpath(info.filename) + if norm.startswith(("/", "..")): + continue + raw_entries.append(norm) + if _should_read(norm): + raw_contents[norm] = zf.read(info) + else: + with tarfile.open(sdist_path, "r:*") as tf: + for member in tf.getmembers(): + if not member.isfile(): + continue + norm = posixpath.normpath(member.name) + if norm.startswith(("/", "..")): + continue + raw_entries.append(norm) + if _should_read(norm): + fobj = tf.extractfile(member) + if fobj is not None: + raw_contents[norm] = fobj.read() + + top_dirs = {p.split("/", 1)[0] for p in raw_entries if "/" in p} + root_files = [p for p in raw_entries if "/" not in p] + if len(top_dirs) == 1 and not root_files: + prefix = next(iter(top_dirs)) + "/" + entries = [p[len(prefix) :] for p in raw_entries if p.startswith(prefix)] + contents = { + k[len(prefix) :]: v for k, v in raw_contents.items() if k.startswith(prefix) + } + return sorted(entries), contents + + return sorted(raw_entries), raw_contents + + +def _parse_pkg_info(text: str) -> tuple[bool, list[str], list[str]]: + msg = email.parser.Parser().parsestr(text, headersonly=True) + ver_parts = (msg.get("Metadata-Version") or "").strip().split(".") + try: + mv = (int(ver_parts[0]), int(ver_parts[1]) if len(ver_parts) > 1 else 0) + except ValueError: + mv = (0, 0) + dynamic = {d.strip().lower() for d in (msg.get_all("Dynamic") or ())} + static = mv >= (2, 2) and not ({"requires-dist", "provides-extra"} & dynamic) + requires_dist = [ + r.strip() for r in (msg.get_all("Requires-Dist") or ()) if r.strip() + ] + provides_extra = [ + e.strip() for e in (msg.get_all("Provides-Extra") or ()) if e.strip() + ] + return static, requires_dist, provides_extra + + +def _combine_req_and_marker(req: str, extra: str, marker: str) -> str: + req = req.strip() + existing_marker = "" + if ";" in req: + req_part, _, existing_marker = req.partition(";") + req = req_part.strip() + existing_marker = existing_marker.strip() + + conditions: list[str] = [] + if existing_marker: + conditions.append( + f"({existing_marker})" if (extra or marker) else existing_marker + ) + if marker: + conditions.append(f"({marker})" if (existing_marker or extra) else marker) + if extra: + conditions.append(f'extra == "{extra}"') + + if conditions: + return f"{req} ; {' and '.join(conditions)}" + return req + + +def _parse_egg_info_requires_txt(text: str) -> tuple[list[str], list[str]]: + requires_dist: list[str] = [] + provides_extra: list[str] = [] + current_extra = "" + current_marker = "" + + for raw_line in text.splitlines(): + line = raw_line.strip() + if not line or line.startswith("#"): + continue + if line.startswith("[") and line.endswith("]"): + section = line[1:-1].strip() + if ":" in section: + extra_part, _, marker_part = section.partition(":") + current_extra = extra_part.strip() + current_marker = marker_part.strip() + else: + current_extra = section + current_marker = "" + if current_extra and current_extra not in provides_extra: + provides_extra.append(current_extra) + continue + + requires_dist.append( + _combine_req_and_marker(line, current_extra, current_marker) + ) + + return requires_dist, provides_extra + + +def _parse_toml(text: str) -> dict[str, object]: + if sys.version_info >= (3, 11): + import tomllib + + loads = tomllib.loads + else: + try: + tomli = importlib.import_module("tomli") + except ModuleNotFoundError as exc: + raise RuntimeError( + "Neither tomllib nor tomli is available to parse pyproject.toml" + ) from exc + loads = tomli.loads + try: + parsed = loads(text) + except Exception as exc: + raise ValueError(f"Failed to parse pyproject.toml: {exc}") from exc + return parsed if isinstance(parsed, dict) else {} + + +def _format_entry_points_txt( + console_scripts: dict[str, str], + gui_scripts: dict[str, str], +) -> str: + sections: list[str] = [] + if console_scripts: + lines = ["[console_scripts]"] + [ + f"{k} = {v}" for k, v in sorted(console_scripts.items()) + ] + sections.append("\n".join(lines)) + if gui_scripts: + lines = ["[gui_scripts]"] + [ + f"{k} = {v}" for k, v in sorted(gui_scripts.items()) + ] + sections.append("\n".join(lines)) + return "\n\n".join(sections) + ("\n" if sections else "") + + +def _discover_site_paths_and_namespaces( + entries: list[str], + contents: dict[str, bytes], + pyproject: dict[str, object], +) -> tuple[list[str], list[str]]: + """Determine installed top-level / leaf non-namespace site_paths and pkgutil namespace init files.""" + entry_set = set(entries) + + dir_files: dict[str, list[str]] = {} + dir_subdirs: dict[str, set[str]] = {} + dir_has_py: set[str] = set() + + for path in entries: + parts = path.split("/") + if any(p.endswith(".egg-info") for p in parts[:-1]): + continue + parent = posixpath.dirname(path) + base = posixpath.basename(path) + dir_files.setdefault(parent, []).append(base) + + _, ext = posixpath.splitext(base) + if ext.lower() in _PY_EXTENSIONS: + dir_has_py.add(parent) + cur = parent + while cur: + dir_has_py.add(cur) + cur = posixpath.dirname(cur) + + cur = parent + while cur: + up = posixpath.dirname(cur) + dir_subdirs.setdefault(up, set()).add(posixpath.basename(cur)) + cur = up + + source_root = "" + raw_tool = pyproject.get("tool") + tool = raw_tool if isinstance(raw_tool, dict) else {} + raw_maturin = tool.get("maturin") + maturin_cfg = raw_maturin if isinstance(raw_maturin, dict) else {} + maturin_py_src = maturin_cfg.get("python-source", "") + if ( + isinstance(maturin_py_src, str) + and maturin_py_src.strip("/") + and maturin_py_src.strip("/") in dir_has_py + ): + source_root = maturin_py_src.strip("/") + elif ( + "src" in dir_subdirs.get("", set()) + and "src/__init__.py" not in entry_set + and "src" in dir_has_py + ): + source_root = "src" + + def _archive_dir(site_rel: str) -> str: + if source_root and f"{source_root}/{site_rel}" in dir_has_py: + return f"{source_root}/{site_rel}" + if site_rel in dir_has_py: + return site_rel + suffix = f"/{site_rel}" + for d in sorted(dir_has_py): + top_seg = d.partition("/")[0].lower() + if d.endswith(suffix) and top_seg not in _EXCLUDED_TOP_DIRS: + return d + return f"{source_root}/{site_rel}" if source_root else site_rel + + def _module_exists_in_archive(mod_name: str) -> bool: + if source_root and f"{source_root}/{mod_name}.py" in entry_set: + return True + if f"{mod_name}.py" in entry_set: + return True + suffix = f"/{mod_name}.py" + return any( + p.endswith(suffix) + and p.partition("/")[0].lower() not in _EXCLUDED_TOP_DIRS + and f"{p.rpartition('/')[0]}/__init__.py" not in entry_set + for p in entries + ) + + namespace_package_files: set[str] = set() + + def _resolve_package_dir(site_rel: str, arch_rel: str) -> list[str]: + init_arch = f"{arch_rel}/__init__.py" if arch_rel else "__init__.py" + has_init = init_arch in entry_set + is_ns_init = False + if has_init: + init_text = contents.get(init_arch, b"").decode("utf-8", "replace") + if is_pkgutil_namespace_init(init_text): + is_ns_init = True + namespace_package_files.add(f"{site_rel}/__init__.py") + + is_namespace = (not has_init) or is_ns_init + direct_non_init_files = [ + f + for f in dir_files.get(arch_rel, []) + if f != "__init__.py" and not f.startswith(".") + ] + child_dirs = sorted( + d + for d in dir_subdirs.get(arch_rel, set()) + if d.isidentifier() and f"{arch_rel}/{d}" in dir_has_py + ) + + if is_namespace and child_dirs and not direct_non_init_files: + resolved: list[str] = [] + for child in child_dirs: + resolved.extend( + _resolve_package_dir(f"{site_rel}/{child}", f"{arch_rel}/{child}") + ) + return resolved + return [site_rel] + + candidate_top_pkgs: list[str] = [] + candidate_modules: list[str] = [] + has_ext_sources = any( + posixpath.splitext(p)[1].lower() in {".c", ".cc", ".cpp", ".cxx", ".pyx", ".rs"} + for p in entries + ) + + for path, raw in sorted(contents.items()): + if not path.endswith(".egg-info/top_level.txt"): + continue + for line in raw.decode("utf-8", "replace").splitlines(): + top = line.strip().strip("/") + if not top or top.lower() in _EXCLUDED_TOP_DIRS: + continue + arch_dir = _archive_dir(top) + if arch_dir in dir_has_py or f"{arch_dir}/__init__.py" in entry_set: + if top not in candidate_top_pkgs: + candidate_top_pkgs.append(top) + continue + if _module_exists_in_archive(top): + mod_file = f"{top}.py" + if mod_file not in candidate_modules: + candidate_modules.append(mod_file) + continue + matches_entry = has_ext_sources or any( + (f"/{top}/" in f"/{p}" or p.endswith(f"/{top}.py")) + and p.partition("/")[0].lower() not in _EXCLUDED_TOP_DIRS + for p in entries + ) + if matches_entry and top not in candidate_top_pkgs: + candidate_top_pkgs.append(top) + break + + if not candidate_top_pkgs and not candidate_modules: + roots_to_scan = [source_root, ""] if source_root else [""] + for scan_root in roots_to_scan: + for d in sorted(dir_subdirs.get(scan_root, set())): + if ( + not d.isidentifier() + or d.lower() in _EXCLUDED_TOP_DIRS + or d.endswith(".egg-info") + ): + continue + arch_dir = f"{scan_root}/{d}" if scan_root else d + if arch_dir in dir_has_py and d not in candidate_top_pkgs: + candidate_top_pkgs.append(d) + for f in sorted(dir_files.get(scan_root, [])): + if ( + f.endswith(".py") + and f not in _EXCLUDED_ROOT_MODULES + and not f.startswith("test_") + and not f.endswith("_test.py") + and f not in candidate_modules + ): + candidate_modules.append(f) + if candidate_top_pkgs or candidate_modules: + break + + site_paths: list[str] = [] + for top_pkg in candidate_top_pkgs: + arch_dir = _archive_dir(top_pkg) + if arch_dir in dir_has_py: + for sp in _resolve_package_dir(top_pkg, arch_dir): + if sp not in site_paths: + site_paths.append(sp) + elif top_pkg not in site_paths: + site_paths.append(top_pkg) + + for mod_file in candidate_modules: + if mod_file not in site_paths: + site_paths.append(mod_file) + + return sorted(site_paths), sorted(namespace_package_files) + + +class SdistInspection(TypedDict): + build_requires: list[str] + entry_points_content: str + namespace_package_files: list[str] + provides_extra: list[str] + requires_dist: list[str] + site_paths: list[str] + + +def inspect_sdist(sdist_path: Path) -> SdistInspection: + """Inspect an sdist archive and return dependencies, entry points, and site_paths.""" + entries, contents = _read_archive_files(sdist_path) + + pkg_info_text = "" + if "PKG-INFO" in contents: + pkg_info_text = contents["PKG-INFO"].decode("utf-8", "replace") + else: + for path, raw in sorted(contents.items()): + if path.endswith(".egg-info/PKG-INFO"): + pkg_info_text = raw.decode("utf-8", "replace") + break + + pkg_info_static = False + requires_dist: list[str] = [] + provides_extra: list[str] = [] + if pkg_info_text: + pkg_info_static, pkg_reqs, pkg_extras = _parse_pkg_info(pkg_info_text) + provides_extra.extend(pkg_extras) + if pkg_reqs or pkg_info_static: + requires_dist.extend(pkg_reqs) + + pyproject: dict[str, object] = {} + if "pyproject.toml" in contents: + pyproject = _parse_toml(contents["pyproject.toml"].decode("utf-8", "replace")) + raw_project = pyproject.get("project") + project_table = raw_project if isinstance(raw_project, dict) else {} + + if not requires_dist and not pkg_info_static: + for path, raw in sorted(contents.items()): + if path.endswith(".egg-info/requires.txt"): + egg_reqs, egg_extras = _parse_egg_info_requires_txt( + raw.decode("utf-8", "replace") + ) + requires_dist.extend(egg_reqs) + for ex in egg_extras: + if ex not in provides_extra: + provides_extra.append(ex) + break + + raw_dynamic = project_table.get("dynamic") + project_dynamic = ( + {d for d in raw_dynamic if isinstance(d, str)} + if isinstance(raw_dynamic, list) + else set() + ) + if not requires_dist and not pkg_info_static and project_table: + if "dependencies" in project_table and "dependencies" not in project_dynamic: + raw_deps = project_table.get("dependencies") + if isinstance(raw_deps, list): + for dep in raw_deps: + if isinstance(dep, str) and dep.strip(): + requires_dist.append(dep.strip()) + opt_deps = project_table.get("optional-dependencies") + if ( + isinstance(opt_deps, dict) + and "optional-dependencies" not in project_dynamic + ): + for extra, deps in opt_deps.items(): + if not isinstance(extra, str): + continue + if extra not in provides_extra: + provides_extra.append(extra) + if not isinstance(deps, list): + continue + for dep in deps: + if isinstance(dep, str) and dep.strip(): + requires_dist.append(_combine_req_and_marker(dep, extra, "")) + + entry_points_content = "" + for path, raw in sorted(contents.items()): + if path.endswith(".egg-info/entry_points.txt"): + entry_points_content = raw.decode("utf-8", "replace") + break + if not entry_points_content and project_table: + raw_scripts = project_table.get("scripts") + raw_gui_scripts = project_table.get("gui-scripts") + if isinstance(raw_scripts, dict) or isinstance(raw_gui_scripts, dict): + scripts = ( + { + k: v + for k, v in raw_scripts.items() + if isinstance(k, str) and isinstance(v, str) + } + if isinstance(raw_scripts, dict) + else {} + ) + gui_scripts = ( + { + k: v + for k, v in raw_gui_scripts.items() + if isinstance(k, str) and isinstance(v, str) + } + if isinstance(raw_gui_scripts, dict) + else {} + ) + entry_points_content = _format_entry_points_txt(scripts, gui_scripts) + + build_system = ( + pyproject.get("build-system", {}) if isinstance(pyproject, dict) else {} + ) + build_requires: list[str] = ["setuptools", "wheel"] + if isinstance(build_system, dict) and build_system: + raw_requires = build_system.get("requires") + if isinstance(raw_requires, list): + build_requires = [ + r.strip() for r in raw_requires if isinstance(r, str) and r.strip() + ] + + site_paths, namespace_package_files = _discover_site_paths_and_namespaces( + entries=entries, + contents=contents, + pyproject=pyproject, + ) + + return { + "build_requires": build_requires, + "entry_points_content": entry_points_content, + "namespace_package_files": namespace_package_files, + "provides_extra": provides_extra, + "requires_dist": requires_dist, + "site_paths": site_paths, + } + + +def main() -> None: + parser = argparse.ArgumentParser(description="Inspect an sdist archive.") + parser.add_argument("--sdist", type=Path, required=True) + args = parser.parse_args() + + json.dump(inspect_sdist(args.sdist), sys.stdout, sort_keys=True) + + +if __name__ == "__main__": + main() diff --git a/python/private/pypi/labels.bzl b/python/private/pypi/labels.bzl index 7881b422d0..58d26d84ee 100644 --- a/python/private/pypi/labels.bzl +++ b/python/private/pypi/labels.bzl @@ -18,6 +18,7 @@ EXTRACTED_WHEEL_FILES = "extracted_whl_files" WHEEL_FILE_PUBLIC_LABEL = "whl" WHEEL_FILE_IMPL_LABEL = "_whl" WHEEL_FILE = "whl_file" +WHEEL_DIR_PUBLIC_LABEL = "whldir" PY_LIBRARY_PUBLIC_LABEL = "pkg" PY_LIBRARY_IMPL_LABEL = "_pkg" PY_SRCS_LABEL = "srcs" diff --git a/python/private/pypi/package_annotation.bzl b/python/private/pypi/package_annotation.bzl index 191d035abb..eae306941b 100644 --- a/python/private/pypi/package_annotation.bzl +++ b/python/private/pypi/package_annotation.bzl @@ -21,13 +21,17 @@ def package_annotation( data = [], data_exclude_glob = [], filegroups = {}, + sdist_build_deps = [], + sdist_config_settings = {}, + site_paths = [], srcs_exclude_glob = []): """Annotations to apply to the BUILD file content from package generated from a `pip_repository` rule. [cf]: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/copy_file_doc.md :::{versionchanged} VERSION_NEXT_FEATURE - Added the `filegroups` parameter. + Added the `filegroups`, `sdist_build_deps`, `sdist_config_settings`, and + `site_paths` parameters. ::: Args: @@ -40,11 +44,23 @@ def package_annotation( data_exclude_glob (list, optional): A list of exclude glob patterns to add as `data` to the generated `py_library` target. filegroups (dict, optional): A mapping of filegroup target names to glob patterns (or include/exclude dicts). + sdist_build_deps (list, optional): Explicit build dependency labels for `py_sdist_wheel` when building an sdist in an action. + sdist_config_settings (dict, optional): PEP 517 `--config-settings` key/value pairs for `py_sdist_wheel`. + site_paths (list, optional): Override predicted `site-packages/` paths when building an sdist in an action. srcs_exclude_glob (list, optional): A list of labels to add as `srcs` to the generated `py_library` target. Returns: str: A json encoded string of the provided content. """ + optional_fields = {} + for k, val in [ + ("filegroups", filegroups), + ("sdist_build_deps", sdist_build_deps), + ("sdist_config_settings", sdist_config_settings), + ("site_paths", site_paths), + ]: + if val: + optional_fields[k] = val return json.encode(struct( additive_build_content = additive_build_content, copy_files = copy_files, @@ -52,5 +68,5 @@ def package_annotation( data = data, data_exclude_glob = data_exclude_glob, srcs_exclude_glob = srcs_exclude_glob, - **({"filegroups": filegroups} if filegroups else {}) + **optional_fields )) diff --git a/python/private/pypi/patch_and_extract_whl.bzl b/python/private/pypi/patch_and_extract_whl.bzl index dc5008264a..6985704a75 100644 --- a/python/private/pypi/patch_and_extract_whl.bzl +++ b/python/private/pypi/patch_and_extract_whl.bzl @@ -186,6 +186,91 @@ def _inspect_whl_for_action_install( extra_kwargs = extra_kwargs, ) +def write_whl_library_repo( + rctx, + *, + name, + metadata, + sdist_filename = None, + annotation = None, + data_exclude = [], + namespace_package_files = [], + entry_points = {}, + remove_build_files = False, + **extra_kwargs): + """Write `metadata.json`, `BUILD.bazel`, and repo boilerplate for a `whl_library`. + + Args: + rctx: The repository context. + name: {type}`str` Wheel filename or sdist build target name. + metadata: {type}`struct` Parsed package metadata (`name`, `version`, `requires_dist`, `provides_extra`). + sdist_filename: {type}`str | None` Optional sdist archive filename. + annotation: {type}`struct | None` Optional decoded package annotation struct. + data_exclude: {type}`list[str]` Data exclusion glob patterns. + namespace_package_files: {type}`list[str]` Namespace package `__init__.py` paths. + entry_points: {type}`dict` Parsed entry points dictionary. + remove_build_files: {type}`bool` Whether to delete nested `BUILD`/`BUILD.bazel` files first. + **extra_kwargs: Extra keyword arguments forwarded to `generate_whl_library_build_bazel`. + + Returns: + Repository metadata if `rctx.repo_metadata` is supported, otherwise `None`. + """ + rctx.file("metadata.json", json.encode_indent({ + "name": metadata.name, + "provides_extra": metadata.provides_extra, + "requires_dist": metadata.requires_dist, + "version": metadata.version, + })) + + build_file_contents = generate_whl_library_build_bazel( + name = name, + dep_template = rctx.attr.dep_template, + sdist_filename = sdist_filename, + config_load = rctx.attr.config_load, + metadata_name = metadata.name, + metadata_version = metadata.version, + requires_dist = metadata.requires_dist, + # TODO @aignas 2025-05-17: maybe have a build flag for this instead + enable_implicit_namespace_pkgs = rctx.attr.enable_implicit_namespace_pkgs, + # TODO @aignas 2025-04-14: load through the hub: + annotation = annotation, + data_exclude = data_exclude, + group_deps = rctx.attr.group_deps, + group_name = rctx.attr.group_name, + namespace_package_files = namespace_package_files, + extras = requirement(rctx.attr.requirement).extras, + entry_points = entry_points, + purl = _to_purl( + index = rctx.attr.index_url, + metadata = metadata, + filename = sdist_filename or name, + ), + **extra_kwargs + ) + + # Delete these in case the wheel had them. They generally don't cause + # a problem, but let's avoid the chance of that happening. + rctx.file("WORKSPACE") + rctx.file("WORKSPACE.bazel") + rctx.file("MODULE.bazel") + rctx.file("REPO.bazel", """\ +repo( + default_package_metadata = [ + "//:package_metadata", + ], +) +""") + + if remove_build_files: + # BUILD files interfere with globbing and Bazel package boundaries. + _remove_files(rctx, "BUILD", "BUILD.bazel") + rctx.file("BUILD.bazel", build_file_contents) + + if hasattr(rctx, "repo_metadata"): + return rctx.repo_metadata(reproducible = True) + + return None + def patch_and_extract_whl(rctx, *, whl_path, logger, sdist_filename = None, whl_file = None): """Extract the wheel, apply patches and generate BUILD.bazel files. @@ -237,63 +322,23 @@ def patch_and_extract_whl(rctx, *, whl_path, logger, sdist_filename = None, whl_ if whl_file: extra_kwargs["whl_file"] = str(whl_file) - rctx.file("metadata.json", json.encode_indent({ - "name": metadata.name, - "provides_extra": metadata.provides_extra, - "requires_dist": metadata.requires_dist, - "version": metadata.version, - })) + whl_basename = whl_path.basename - build_file_contents = generate_whl_library_build_bazel( - name = whl_path.basename, - dep_template = rctx.attr.dep_template, + # The generated wheel target can obtain the original archive independently. + # Do not retain the temporary download or delete a caller-owned wheel. + if whl_file and whl_path.dirname == rctx.path("."): + rctx.delete(whl_path) + + return write_whl_library_repo( + rctx, + name = whl_basename, + metadata = metadata, sdist_filename = sdist_filename, - config_load = rctx.attr.config_load, - metadata_name = metadata.name, - metadata_version = metadata.version, - requires_dist = metadata.requires_dist, - # TODO @aignas 2025-05-17: maybe have a build flag for this instead - enable_implicit_namespace_pkgs = rctx.attr.enable_implicit_namespace_pkgs, - # TODO @aignas 2025-04-14: load through the hub: annotation = annotation, data_exclude = data_exclude, - group_deps = rctx.attr.group_deps, - group_name = rctx.attr.group_name, namespace_package_files = namespace_package_files, - extras = requirement(rctx.attr.requirement).extras, entry_points = entry_points, - purl = _to_purl( - index = rctx.attr.index_url, - metadata = metadata, - filename = sdist_filename or whl_path.basename, - ), logger = logger, + remove_build_files = True, **extra_kwargs ) - - # The generated wheel target can obtain the original archive independently. - # Do not retain the temporary download or delete a caller-owned wheel. - if whl_file and whl_path.dirname == rctx.path("."): - rctx.delete(whl_path) - - # Delete these in case the wheel had them. They generally don't cause - # a problem, but let's avoid the chance of that happening. - rctx.file("WORKSPACE") - rctx.file("WORKSPACE.bazel") - rctx.file("MODULE.bazel") - rctx.file("REPO.bazel", """\ -repo( - default_package_metadata = [ - "//:package_metadata", - ], -) -""") - - # BUILD files interfere with globbing and Bazel package boundaries. - _remove_files(rctx, "BUILD", "BUILD.bazel") - rctx.file("BUILD.bazel", build_file_contents) - - if hasattr(rctx, "repo_metadata"): - return rctx.repo_metadata(reproducible = True) - - return None diff --git a/python/private/pypi/pip_archive.bzl b/python/private/pypi/pip_archive.bzl index 79a805b32c..9b74d6543c 100644 --- a/python/private/pypi/pip_archive.bzl +++ b/python/private/pypi/pip_archive.bzl @@ -3,13 +3,23 @@ load("//python/private:auth.bzl", "get_auth") load("//python/private:envsubst.bzl", "envsubst") load("//python/private:is_standalone_interpreter.bzl", "is_standalone_interpreter") +load("//python/private:normalize_name.bzl", "normalize_name") load("//python/private:repo_utils.bzl", "REPO_DEBUG_ENV_VAR", "repo_utils") -load(":attrs.bzl", "ATTRS", "use_isolated") +load("//python/private:version.bzl", "version") +load(":attrs.bzl", "ATTRS", "use_action_install", "use_isolated") load(":deps.bzl", "all_repo_names", "record_files") -load(":patch_and_extract_whl.bzl", "patch_and_extract_whl") +load( + ":generate_whl_library_build_bazel.bzl", + "generate_sdist_wheel_files_bzl", + "parse_sdist_extra_pip_args", +) +load(":patch_and_extract_whl.bzl", "patch_and_extract_whl", "write_whl_library_repo") +load(":pep508_requirement.bzl", "requirement") load(":pypi_repo_utils.bzl", "pypi_repo_utils") load(":urllib.bzl", "urllib") +load(":version_from_filename.bzl", "version_from_filename") load(":whl_archive.bzl", "whl_archive_attrs") +load(":whl_metadata.bzl", "parse_entry_points") _CPPFLAGS = "CPPFLAGS" _COMMAND_LINE_TOOLS_PATH_SLUG = "commandlinetools" @@ -242,6 +252,122 @@ def _create_repository_execution_environment(rctx, python_interpreter, logger = env[_CPPFLAGS] = " ".join(cppflags) return env +def inspect_sdist_and_generate_build( + rctx, + *, + sdist_filename, + python_interpreter, + logger): + """Inspect an sdist archive at fetch time and write `BUILD.bazel` and `wheel_files.bzl`. + + Args: + rctx: The repository context. + sdist_filename: {type}`str` Filename of the downloaded sdist archive. + python_interpreter: {type}`path` Resolved Python interpreter path. + logger: Repository logger instance. + + Returns: + Repository metadata from `write_whl_library_repo`. + """ + annotation = None if not rctx.attr.annotation else struct(**json.decode(rctx.read(rctx.attr.annotation))) + inspect_env = { + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONHOME": _get_python_home(rctx, python_interpreter, logger), + "PYTHONPATH": pypi_repo_utils.construct_pythonpath( + rctx, + entries = rctx.attr._python_path_entries, + ), + } + inspection = json.decode(pypi_repo_utils.execute_checked_stdout( + rctx, + python = python_interpreter, + srcs = [ + rctx.attr._inspect_sdist, + rctx.attr._wheel_layout, + ], + op = "InspectSdist({})".format(sdist_filename), + arguments = [ + str(rctx.path(rctx.attr._inspect_sdist)), + "--sdist", + str(rctx.path(sdist_filename)), + ], + environment = inspect_env, + logger = logger, + )) + + req = requirement(rctx.attr.requirement) + pkg_name = req.name + pkg_version = req.version or version_from_filename(sdist_filename) + if not pkg_name or not pkg_version: + fail("Failed to determine package name and version for sdist '{}'".format(sdist_filename)) + + metadata = struct( + name = pkg_name, + version = pkg_version, + requires_dist = inspection.get("requires_dist", []), + provides_extra = inspection.get("provides_extra", []), + ) + + sdist = { + "distribution": pkg_name, + "site_paths": inspection.get("site_paths", []), + "version": pkg_version, + } + if inspection.get("build_requires"): + sdist["build_requires"] = inspection["build_requires"] + if rctx.attr.environment: + sdist["environment"] = dict(rctx.attr.environment) + if rctx.attr.add_libdir_to_library_search_path: + sdist["add_libdir_to_library_search_path"] = True + if rctx.attr.extra_pip_args: + resolved_extra_pip_args = [ + envsubst(pip_arg, rctx.attr.envsubst, rctx.getenv) + for pip_arg in rctx.attr.extra_pip_args + ] + pip_config_settings = parse_sdist_extra_pip_args( + resolved_extra_pip_args, + logger = logger, + name = sdist_filename, + ) + if pip_config_settings: + sdist["config_settings"] = pip_config_settings + + if rctx.attr.whl_patches: + pre_build_patches = [] + pre_build_patch_strips = [] + for patch_file, json_args in rctx.attr.whl_patches.items(): + patch_dst = struct(**json.decode(json_args)) + if sdist_filename in patch_dst.whls: + pre_build_patches.append(str(patch_file)) + pre_build_patch_strips.append(patch_dst.patch_strip) + if pre_build_patches: + sdist["pre_build_patches"] = pre_build_patches + sdist["pre_build_patch_strips"] = pre_build_patch_strips + else: + logger.warn( + "None of the whl_patches entries matched sdist filename '{}'".format(sdist_filename), + ) + + whl_target_name = "{}-{}.sdist_build.whl".format( + normalize_name(metadata.name), + version.normalize(metadata.version), + ) + rctx.file("wheel_files.bzl", generate_sdist_wheel_files_bzl()) + + return write_whl_library_repo( + rctx, + name = whl_target_name, + metadata = metadata, + sdist_filename = sdist_filename, + annotation = annotation, + data_exclude = rctx.attr.pip_data_exclude, + namespace_package_files = inspection.get("namespace_package_files", []), + entry_points = parse_entry_points(inspection.get("entry_points_content", "")), + logger = logger, + action_install = True, + sdist = sdist, + ) + def _pip_archive_impl(rctx): logger = repo_utils.logger(rctx) @@ -296,6 +422,15 @@ def _pip_archive_impl(rctx): python_interpreter = rctx.attr.python_interpreter, python_interpreter_target = rctx.attr.python_interpreter_target, ) + if sdist_filename and use_action_install(rctx, rctx.attr): + inspect_sdist_and_generate_build( + rctx, + sdist_filename = sdist_filename, + python_interpreter = python_interpreter, + logger = logger, + ) + return + args = [ "-m", "python.private.pypi.whl_installer.wheel_installer", @@ -360,6 +495,9 @@ pip_archive_attrs = { pip_archive = repository_rule( attrs = pip_archive_attrs | { + "_inspect_sdist": attr.label( + default = Label("//python/private/pypi:inspect_sdist.py"), + ), "_python_path_entries": attr.label_list( # Get the root directory of these rules and keep them as a default attribute # in order to avoid unnecessary repository fetching restarts. diff --git a/python/private/pypi/wheel_layout.py b/python/private/pypi/wheel_layout.py index ec882f6504..ce3cfd9063 100644 --- a/python/private/pypi/wheel_layout.py +++ b/python/private/pypi/wheel_layout.py @@ -67,9 +67,13 @@ def is_excluded(path: str, compiled_globs: list[re.Pattern[str]]) -> bool: def is_pkgutil_namespace_init(content: str) -> bool: - """Whether an `__init__.py` declares a pkgutil namespace package.""" + """Whether an `__init__.py` declares a pkgutil or pkg_resources namespace package.""" + if "__path__ =" in content and "pkgutil" in content and "extend_path(" in content: + return True return ( - "__path__ =" in content and "pkgutil" in content and "extend_path(" in content + "pkg_resources" in content + and "def declare_namespace" not in content + and bool(re.search(r"\bdeclare_namespace\(\s*__name__\s*\)", content)) ) diff --git a/python/private/pypi/whl_library_deps_targets.bzl b/python/private/pypi/whl_library_deps_targets.bzl index e549f52a47..bfd66afb7e 100644 --- a/python/private/pypi/whl_library_deps_targets.bzl +++ b/python/private/pypi/whl_library_deps_targets.bzl @@ -142,7 +142,7 @@ def whl_library_deps_targets( include = include, ) - _config_settings( + config_settings( dependencies_with_markers = package_deps.deps_select, rules = rules, visibility = ["//visibility:private"], @@ -151,10 +151,13 @@ def whl_library_deps_targets( if hasattr(native, "filegroup"): # We include the whl file as srcs so that `$(location :whl)` expands to the whl file. # The transitive dependencies are available via the `data` attribute. + # Note: For action-built sdists (`experimental_action_install`), `:whl`'s contents are + # the built wheel; the filename (`-.sdist_build.whl`) is not a valid wheel + # filename — use `:whldir` for the real one. native.filegroup( name = whl_file_label, srcs = [repo_label(WHEEL_FILE)], - data = _deps( + data = select_deps( deps = [], package_deps = package_deps, tmpl = dep_template.format(name = "{}", target = WHEEL_FILE_PUBLIC_LABEL), @@ -167,7 +170,7 @@ def whl_library_deps_targets( name = py_library_label, # We include as srcs to ensure that the (locations :pkg) works as expected. srcs = [repo_label(PY_SRCS_LABEL)], - deps = _deps( + deps = select_deps( # We include as deps, so that `PyInfo` and friends (e.g. `pyi_srcs`) get # propagated. Just passing the target as `srcs` is not enough to propagate # `pyi_srcs`, see `tests/base_rules/py_library`. @@ -197,28 +200,44 @@ def _parse_requires_dist( extras = extras, ) -def _config_settings(dependencies_with_markers, rules, **kwargs): +def config_settings( + dependencies_with_markers, + rules = struct(env_marker_setting = env_marker_setting), + setting_prefix = "include_", + visibility = ["//visibility:private"]): """Generate config settings for the targets. Args: dependencies_with_markers: {type}`dict[str, str]` The markers to evaluate by each dep. rules: used for testing - **kwargs: Extra kwargs to pass to the rule. + setting_prefix: {type}`str` Target name prefix for the generated setting. + visibility: {type}`list[str]` Target visibility. """ for dep, expression in dependencies_with_markers.items(): rules.env_marker_setting( - name = "include_{}".format(dep), + name = "{}{}".format(setting_prefix, dep), expression = expression, - **kwargs + visibility = visibility, ) -def _deps(deps, package_deps, tmpl): +def select_deps(deps, package_deps, tmpl, setting_prefix = "include_"): + """Append unconditional and marker-selected dependencies to `deps`. + + Args: + deps: {type}`list[str]` Initial dependency list. + package_deps: {type}`struct` Parsed dependency struct (`deps` and `deps_select`). + tmpl: {type}`str` Format string template for dependency labels. + setting_prefix: {type}`str` Prefix for marker config_setting target names. + + Returns: + {type}`list[str] | select` Combined dependencies list/select expression. + """ deps = [] + deps + [tmpl.format(d) for d in sorted(package_deps.deps)] for dep in package_deps.deps_select: deps = deps + select({ - ":is_include_{}_true".format(dep): [tmpl.format(dep)], + ":is_{}{}_true".format(setting_prefix, dep): [tmpl.format(dep)], "//conditions:default": [], }) diff --git a/python/private/pypi/whl_library_srcs.bzl b/python/private/pypi/whl_library_srcs.bzl index 063ef02352..cea660ef25 100644 --- a/python/private/pypi/whl_library_srcs.bzl +++ b/python/private/pypi/whl_library_srcs.bzl @@ -4,6 +4,7 @@ load("@bazel_skylib//lib:types.bzl", "types") load("@bazel_skylib//rules:copy_file.bzl", "copy_file") load("//python:py_library.bzl", "py_library") load(":gen_wheel_record.bzl", "gen_wheel_record") +load(":generate_whl_library_build_bazel.bzl", "split_sdist_config_settings") load( ":labels.bzl", "DATA_LABEL", @@ -11,9 +12,11 @@ load( "DIST_INFO_LABEL", "EXTRACTED_WHEEL_FILES", "PY_SRCS_LABEL", + "WHEEL_DIR_PUBLIC_LABEL", "WHEEL_FILE", ) load(":namespace_pkgs.bzl", _create_inits = "create_inits") +load(":py_sdist_wheel.bzl", "py_sdist_wheel") load(":py_wheel_extract_files.bzl", "py_wheel_extract_files", "wheel_glob") load(":py_wheel_library.bzl", "py_wheel_library") load(":venv_entry_point.bzl", "venv_entry_point") @@ -82,10 +85,35 @@ def _is_wheel_internal_path(src, extracted_files, shebang_scripts): def _validate_action_install_args( name, *, + sdist, filegroups, + copy_files, + copy_executables, extracted_files, shebang_scripts, _fail): + if sdist != None: + if filegroups != None: + _fail( + ( + "In '{}', custom glob-based 'filegroups' ({}) are not supported for action-built sdists " + + "under experimental_action_install (use py_wheel_extract_files or wheel_glob on downloaded wheels)." + ).format(name, ", ".join(sorted(filegroups.keys()))), + ) + return False + internal_copy_srcs = [ + src + for src in list(copy_files.keys()) + list(copy_executables.keys()) + if _is_wheel_internal_path(src, extracted_files, shebang_scripts) + ] + if internal_copy_srcs: + _fail( + ( + "In '{}', wheel-internal 'copy_files'/'copy_executables' ({}) are not supported for action-built sdists " + + "under experimental_action_install (use py_wheel_extract_files or wheel_glob on downloaded wheels)." + ).format(name, ", ".join(sorted(internal_copy_srcs))), + ) + return False if filegroups != None and not extracted_files and not shebang_scripts: _fail( ( @@ -201,11 +229,13 @@ def whl_library_srcs( extracted_files = [], has_entry_points_txt = False, shebang_scripts = [], + sdist = None, visibility = ["//visibility:public"], _fail = fail, rules = struct( copy_file = copy_file, py_library = py_library, + py_sdist_wheel = py_sdist_wheel, py_wheel_extract_files = py_wheel_extract_files, py_wheel_library = py_wheel_library, venv_entry_point = venv_entry_point, @@ -243,6 +273,7 @@ def whl_library_srcs( extracted_files: {type}`list[str]` Relative paths under the installed wheel directory. has_entry_points_txt: {type}`bool` Whether a fetch-time `entry_points.txt` file exists in the package. shebang_scripts: {type}`list[str]` Top-level script names in `.data/scripts/` with `#!python` shebangs. + sdist: {type}`dict | None` Keyword arguments for `py_sdist_wheel` (plus `site_paths`) when building an sdist in an action. native: {type}`native` The native struct for overriding in tests. _fail: {type}`callable` The fail function for overriding in tests. rules: {type}`struct` A struct with references to rules for creating targets. @@ -252,7 +283,10 @@ def whl_library_srcs( if action_install and not _validate_action_install_args( name, + sdist = sdist, filegroups = filegroups, + copy_files = copy_files, + copy_executables = copy_executables, extracted_files = extracted_files, shebang_scripts = shebang_scripts, _fail = _fail, @@ -278,7 +312,7 @@ def whl_library_srcs( if bin_s not in all_wheel_files: all_wheel_files.append(bin_s) - wheel_install_target = "_wheel_install" + wheel_install_target = "_wheel_install" if sdist == None else PY_SRCS_LABEL extract_state = {} _add_action_install_copies( @@ -296,12 +330,35 @@ def whl_library_srcs( _fail = _fail, ) + if sdist != None: + sdist_kwargs = dict(sdist) + site_paths = sdist_kwargs.pop("site_paths", []) + split_sdist_config_settings(sdist_kwargs) + rules.py_sdist_wheel( + name = name, + sdist = sdist_filename, + visibility = visibility, + **sdist_kwargs + ) + else: + site_paths = [] + if hasattr(native, "filegroup"): + # Note: For action-built sdists (`sdist != None`), `:whl_file` / `:whl` + # points to `-.sdist_build.whl`: contents are the built wheel; + # the filename is not a valid wheel filename — use `:whldir` for the real one. native.filegroup( name = WHEEL_FILE, srcs = [whl_file or name], visibility = visibility, ) + if sdist != None: + native.filegroup( + name = WHEEL_DIR_PUBLIC_LABEL, + srcs = [name], + output_group = "whldir", + visibility = visibility, + ) _add_action_install_custom_filegroups( filegroups = filegroups, @@ -316,16 +373,30 @@ def whl_library_srcs( ) if hasattr(native, "filegroup"): - for fg_name, fg_srcs in [ - (EXTRACTED_WHEEL_FILES, [PY_SRCS_LABEL]), - (DIST_INFO_LABEL, ["entry_points.txt"] if has_entry_points_txt else []), - (DATA_LABEL, [PY_SRCS_LABEL] + bins_for_data_label), - ]: - if filegroups != None and fg_name in filegroups: - continue + if filegroups == None or EXTRACTED_WHEEL_FILES not in filegroups: + native.filegroup( + name = EXTRACTED_WHEEL_FILES, + srcs = [PY_SRCS_LABEL], + visibility = visibility, + ) + if filegroups == None or DIST_INFO_LABEL not in filegroups: + if sdist != None: + native.filegroup( + name = DIST_INFO_LABEL, + srcs = [":" + PY_SRCS_LABEL], + output_group = "dist_info", + visibility = visibility, + ) + else: + native.filegroup( + name = DIST_INFO_LABEL, + srcs = ["entry_points.txt"] if has_entry_points_txt else [], + visibility = visibility, + ) + if filegroups == None or DATA_LABEL not in filegroups: native.filegroup( - name = fg_name, - srcs = fg_srcs, + name = DATA_LABEL, + srcs = [PY_SRCS_LABEL] + bins_for_data_label, visibility = visibility, ) @@ -340,25 +411,35 @@ def whl_library_srcs( tags = tags, experimental_venvs_site_packages = _VENV_SITE_PACKAGES_FLAG, ) - - # NOTE: `_wheel_install` is an internal implementation detail exposed with - # `visibility` solely so `:wheel_files.bzl` (`wheel_glob`) can reference it - # when loaded from external packages. Do not depend on `:_wheel_install` - # directly; depend on `:srcs` (or `:pkg`) instead. - rules.py_wheel_library( - name = wheel_install_target, - wheel = whl_file or name, - data = [], - visibility = visibility, - **common_wheel_kwargs - ) - rules.py_wheel_library( - name = PY_SRCS_LABEL, - wheel = ":" + wheel_install_target, - data = data, - visibility = visibility, - **common_wheel_kwargs - ) + if site_paths: + common_wheel_kwargs["site_paths"] = site_paths + if sdist == None: + # NOTE: `_wheel_install` is an internal implementation detail exposed with + # `visibility` solely so `:wheel_files.bzl` (`wheel_glob`) can reference it + # when loaded from external packages. Do not depend on `:_wheel_install` + # directly; depend on `:srcs` (or `:pkg`) instead. + rules.py_wheel_library( + name = wheel_install_target, + wheel = whl_file or name, + data = [], + visibility = visibility, + **common_wheel_kwargs + ) + rules.py_wheel_library( + name = PY_SRCS_LABEL, + wheel = ":" + wheel_install_target, + data = data, + visibility = visibility, + **common_wheel_kwargs + ) + else: + rules.py_wheel_library( + name = PY_SRCS_LABEL, + wheel = name, + data = data, + visibility = visibility, + **common_wheel_kwargs + ) return existing_bin_names = {ep["name"].lower(): None for ep in entry_points.values()} diff --git a/python/private/pypi/whl_library_targets.bzl b/python/private/pypi/whl_library_targets.bzl index d365b4ca1d..c90acb8cb2 100644 --- a/python/private/pypi/whl_library_targets.bzl +++ b/python/private/pypi/whl_library_targets.bzl @@ -14,12 +14,89 @@ """Macro to generate all of the targets present in a {obj}`whl_library`.""" -load(":whl_library_deps_targets.bzl", _whl_library_deps_targets = "whl_library_deps_targets") +load("//python/private:normalize_name.bzl", "normalize_name") +load(":labels.bzl", "PY_LIBRARY_PUBLIC_LABEL") +load(":pep508_deps.bzl", _pep508_deps = "deps") +load(":py_sdist_wheel.bzl", "BOOTSTRAP_BUILD_PACKAGES") +load( + ":whl_library_deps_targets.bzl", + "config_settings", + "select_deps", + _whl_library_deps_targets = "whl_library_deps_targets", +) load(":whl_library_srcs.bzl", _whl_library_srcs = "whl_library_srcs") whl_library_deps_targets = _whl_library_deps_targets whl_library_srcs = _whl_library_srcs +def _resolve_sdist_build_deps( + *, + name, + sdist, + metadata_name, + dep_template, + group_deps, + include, + kwargs): + sdist = dict(sdist) + build_requires = sdist.pop("build_requires", []) + build_deps = list(sdist.get("build_deps", [])) + if not (build_requires and dep_template): + if build_deps: + sdist["build_deps"] = build_deps + return sdist + + user_dep_names = [] + for d in build_deps: + _, _, pkg_and_target = d.partition("//") + pkg_part, _, target_part = pkg_and_target.partition(":") + if pkg_part: + user_dep_names.append(normalize_name(pkg_part.rpartition("/")[2])) + if target_part: + user_dep_names.append(normalize_name(target_part)) + excludes = group_deps + BOOTSTRAP_BUILD_PACKAGES.keys() + user_dep_names + + if include and not build_deps: + all_build_reqs = _pep508_deps( + name = metadata_name, + requires_dist = build_requires, + excludes = excludes, + ) + include_set = {normalize_name(n): True for n in include} + missing = [r for r in all_build_reqs.deps if r not in include_set] + if missing: + fail( + "In '{}', sdist build requires {} which are not present in the pip hub ".format( + name, + ", ".join(missing), + ) + + "packages or bootstrap dependencies ({}). Add them to your requirements ".format( + ", ".join(sorted(BOOTSTRAP_BUILD_PACKAGES.keys())), + ) + + "lockfile or specify 'sdist_build_deps' via pip.whl_mods / package_annotation.", + ) + + build_pkg_deps = _pep508_deps( + name = metadata_name, + requires_dist = build_requires, + excludes = excludes, + include = include, + ) + config_settings( + dependencies_with_markers = build_pkg_deps.deps_select, + setting_prefix = "include_sdist_build_", + **({"rules": kwargs["rules"]} if "rules" in kwargs else {}) + ) + build_deps = select_deps( + deps = build_deps, + package_deps = build_pkg_deps, + tmpl = dep_template.format(name = "{}", target = PY_LIBRARY_PUBLIC_LABEL), + setting_prefix = "include_sdist_build_", + ) + if build_deps: + sdist["build_deps"] = build_deps + return sdist + def whl_library_targets( *, name, @@ -45,6 +122,7 @@ def whl_library_targets( extracted_files = [], has_entry_points_txt = False, shebang_scripts = [], + sdist = None, visibility = ["//visibility:public"], **kwargs): """The macro to create whl targets from the METADATA. @@ -77,9 +155,21 @@ def whl_library_targets( extracted_files: {type}`list[str]` Relative paths under the installed wheel directory. has_entry_points_txt: {type}`bool` Whether a fetch-time `entry_points.txt` file exists in the package. shebang_scripts: {type}`list[str]` Top-level script names in `.data/scripts/` with `#!python` shebangs. + sdist: {type}`dict | None` Keyword arguments for `py_sdist_wheel` (plus `build_requires` and `site_paths`) when building an sdist in an action. visibility: {type}`list[str]` The visibility of the targets. **kwargs: Extra args passed to the {obj}`whl_library_deps_targets` and {obj}`whl_library_srcs`. """ + if sdist != None: + sdist = _resolve_sdist_build_deps( + name = name, + sdist = sdist, + metadata_name = metadata_name, + dep_template = dep_template, + group_deps = group_deps, + include = include, + kwargs = kwargs, + ) + whl_library_srcs( name = name, whl_file = whl_file, @@ -98,6 +188,7 @@ def whl_library_targets( extracted_files = extracted_files, has_entry_points_txt = has_entry_points_txt, shebang_scripts = shebang_scripts, + sdist = sdist, **kwargs ) diff --git a/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl b/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl index 07c0b8d5f4..18b21dc105 100644 --- a/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl +++ b/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl @@ -17,8 +17,10 @@ load("@rules_testing//lib:test_suite.bzl", "test_suite") load( "//python/private/pypi:generate_whl_library_build_bazel.bzl", + "generate_sdist_wheel_files_bzl", "generate_wheel_files_bzl", "generate_whl_library_build_bazel", + "parse_sdist_extra_pip_args", ) # buildifier: disable=bzl-visibility _tests = [] @@ -452,6 +454,143 @@ def _test_action_install_glob_warning(env): _tests.append(_test_action_install_glob_warning) +def _test_action_sdist(env): + pip_warnings = [] + parsed_cs = parse_sdist_extra_pip_args( + [ + "--index-url", + "https://pypi.org/simple", + "-i", + "https://mirror.example.com", + "--extra-index-url=https://extra.example.com", + "--trusted-host", + "mirror.example.com", + "--find-links=.", + "-f", + "wheels", + "--no-index", + "--isolated", + "--cert=/etc/ssl/cert.pem", + "--client-cert", + "/etc/ssl/client.pem", + "--proxy", + "http://proxy:8080", + "--retries=3", + "--timeout", + "30", + "--cache-dir=/tmp/cache", + "--no-cache-dir", + "--prefer-binary", + "--only-binary=:none:", + "--no-binary", + ":all:", + "--pre", + "--require-hashes", + "--quiet", + "-q", + "--no-deps", + "--use-pep517", + "--platform=manylinux2014_x86_64", + "-C", + "cmake.define.FOO=from_pip_args", + "-Ckeep_from_pip=1", + "--config-settings", + "setup-args=-Dbar=2", + "--config-settings=build-dir=build", + "-C--global-option=--quiet", + "-C--global-option=--force", + "-Cmalformed_no_equals", + "--global-option=--cpp_implementation", + ], + logger = struct(warn = pip_warnings.append), + name = "foo-1.0.tar.gz", + ) + env.expect.that_dict(parsed_cs).contains_exactly({ + "--global-option": ["--quiet", "--force"], + "build-dir": "build", + "cmake.define.FOO": "from_pip_args", + "keep_from_pip": "1", + "setup-args": "-Dbar=2", + }) + env.expect.that_int(len(pip_warnings)).equals(1) + env.expect.that_str(pip_warnings[0]).contains("-Cmalformed_no_equals") + env.expect.that_str(pip_warnings[0]).contains("--global-option=--cpp_implementation") + env.expect.that_str(pip_warnings[0]).contains("ignored in experimental_action_install sdist builds") + + sdist_wheel_files_bzl = generate_sdist_wheel_files_bzl() + env.expect.that_str(sdist_wheel_files_bzl).contains("FILES = []") + env.expect.that_str(sdist_wheel_files_bzl).contains("cannot be used with an action-built sdist") + + want = """\ +load("@package_metadata//rules:package_metadata.bzl", "package_metadata") +load("@pypi//:config.bzl", "packages") +load("@rules_python//python/private/pypi:whl_library_targets.bzl", "whl_library_targets") + +package(default_visibility = ["//visibility:public"]) + +whl_library_targets( + action_install = True, + copy_executables = {}, + copy_files = {}, + data = [], + data_exclude = [], + dep_template = "@pypi//{name}:{target}", + include = packages, + metadata_name = "foo", + name = "foo-1.0.sdist_build.whl", + sdist = { + "add_libdir_to_library_search_path": True, + "build_requires": ["setuptools>=61", "wheel"], + "config_settings": {"cmake.define.FOO": "from_whl_mods", "keep_from_pip": "1"}, + "config_settings_list": {"--global-option": ["--quiet", "--force"]}, + "environment": {"FOO_ENV": "1"}, + "pre_build_patch_strips": [1], + "pre_build_patches": ["//patches:fix.patch"], + "site_paths": ["foo"], + }, + sdist_filename = "foo-1.0.tar.gz", + srcs_exclude = [], + tags = [ + "pypi_name=foo", + "pypi_version=1.0", + ], +) +""" + actual = generate_whl_library_build_bazel( + metadata_version = "1.0", + metadata_name = "foo", + dep_template = "@pypi//{name}:{target}", + name = "foo-1.0.sdist_build.whl", + sdist_filename = "foo-1.0.tar.gz", + config_load = "@pypi//:config.bzl", + action_install = True, + annotation = struct( + copy_files = {}, + copy_executables = {}, + data = [], + data_exclude_glob = [], + sdist_config_settings = {"cmake.define.FOO": "from_whl_mods"}, + srcs_exclude_glob = [], + additive_build_content = None, + ), + sdist = { + "add_libdir_to_library_search_path": True, + "build_requires": ["setuptools>=61", "wheel"], + "config_settings": { + "--global-option": ["--quiet", "--force"], + "cmake.define.FOO": "from_pip_args", + "keep_from_pip": "1", + }, + "environment": {"FOO_ENV": "1"}, + "pre_build_patch_strips": [1], + "pre_build_patches": ["//patches:fix.patch"], + "site_paths": ["foo"], + }, + ) + env.expect.that_str(actual.replace("@@", "@")).equals(want) + +_tests.append(_test_action_sdist) + def generate_whl_library_build_bazel_test_suite(name): """Create the test suite. diff --git a/tests/pypi/py_wheel_library/BUILD.bazel b/tests/pypi/py_wheel_library/BUILD.bazel index 67a5935a64..163812a121 100644 --- a/tests/pypi/py_wheel_library/BUILD.bazel +++ b/tests/pypi/py_wheel_library/BUILD.bazel @@ -553,3 +553,13 @@ py_reconfig_test( ":sdist_demo_wheel_lib_venv", ], ) + +py_test( + name = "inspect_sdist_test", + srcs = ["inspect_sdist_test.py"], + data = [":gen_demo_sdist"], + deps = [ + "//python/private/pypi:wheel_installer_lib", + "//python/runfiles", + ], +) diff --git a/tests/pypi/py_wheel_library/inspect_sdist_test.py b/tests/pypi/py_wheel_library/inspect_sdist_test.py new file mode 100644 index 0000000000..d848b46410 --- /dev/null +++ b/tests/pypi/py_wheel_library/inspect_sdist_test.py @@ -0,0 +1,197 @@ +"""Unit tests for inspect_sdist.""" + +from __future__ import annotations + +import io +import pathlib +import tarfile +import tempfile +import unittest + +import inspect_sdist + +from python.runfiles import runfiles + + +def _make_sdist_tar(path: pathlib.Path, files: dict[str, str]) -> pathlib.Path: + with tarfile.open(path, "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.mode = 0o644 + tf.addfile(info, io.BytesIO(data)) + return path + + +class InspectSdistTest(unittest.TestCase): + def test_inspect_generated_sdist(self): + rf = runfiles.Create() + assert rf is not None + sdist_rloc = rf.Rlocation( + "rules_python/tests/pypi/py_wheel_library/sdist_demo-main.tar.gz" + ) + assert sdist_rloc is not None + info = inspect_sdist.inspect_sdist(pathlib.Path(sdist_rloc)) + self.assertEqual(info["site_paths"], ["sdist_demo"]) + + def test_inspect_pep420_namespace_and_pyproject(self): + with tempfile.TemporaryDirectory() as tmp: + sdist = _make_sdist_tar( + pathlib.Path(tmp) / "acme_sub-2.0.0.tar.gz", + { + "acme_sub-2.0.0/pyproject.toml": ( + "[build-system]\n" + 'requires = ["setuptools>=61", "wheel"]\n' + 'build-backend = "setuptools.build_meta"\n' + "[project]\n" + 'name = "acme-sub"\n' + 'version = "2.0.0"\n' + 'dependencies = ["requests>=2.0"]\n' + "[project.optional-dependencies]\n" + 'dev = ["pytest"]\n' + "[project.scripts]\n" + 'acme-cli = "acme.sub.cli:main"\n' + ), + "acme_sub-2.0.0/src/acme/sub/__init__.py": "X = 1\n", + "acme_sub-2.0.0/src/acme/sub/cli.py": "def main(): pass\n", + }, + ) + info = inspect_sdist.inspect_sdist(sdist) + self.assertEqual(info["build_requires"], ["setuptools>=61", "wheel"]) + self.assertIn("requests>=2.0", info["requires_dist"]) + self.assertIn('pytest ; extra == "dev"', info["requires_dist"]) + self.assertEqual(info["provides_extra"], ["dev"]) + self.assertEqual(info["site_paths"], ["acme/sub"]) + self.assertEqual(info["namespace_package_files"], []) + self.assertIn("acme-cli = acme.sub.cli:main", info["entry_points_content"]) + + def test_inspect_pkgutil_namespace_and_egg_info(self): + with tempfile.TemporaryDirectory() as tmp: + sdist = _make_sdist_tar( + pathlib.Path(tmp) / "ns_pkg-1.0.tar.gz", + { + "ns_pkg-1.0/ns_pkg.egg-info/requires.txt": ( + "six\n\n[test]\nmock\n" + ), + "ns_pkg-1.0/ns_pkg.egg-info/top_level.txt": "ns\nzope\ntools\nstale_ghost\n", + "ns_pkg-1.0/ns/__init__.py": ( + "__path__ = __import__('pkgutil').extend_path(__path__, __name__)\n" + ), + "ns_pkg-1.0/ns/leaf/__init__.py": "VAL = 42\n", + "ns_pkg-1.0/zope/__init__.py": ( + "__import__('pkg_resources').declare_namespace(__name__)\n" + ), + "ns_pkg-1.0/zope/interface/__init__.py": "IFACE = 1\n", + "ns_pkg-1.0/tools/__init__.py": "T = 1\n", + }, + ) + info = inspect_sdist.inspect_sdist(sdist) + self.assertIn("six", info["requires_dist"]) + self.assertIn('mock ; extra == "test"', info["requires_dist"]) + self.assertEqual(info["site_paths"], ["ns/leaf", "tools", "zope/interface"]) + self.assertEqual( + info["namespace_package_files"], ["ns/__init__.py", "zope/__init__.py"] + ) + + def test_inspect_src_module_and_maturin_python_source(self): + with tempfile.TemporaryDirectory() as tmp: + flit_sdist = _make_sdist_tar( + pathlib.Path(tmp) / "typing_extensions-4.8.0.tar.gz", + { + "typing_extensions-4.8.0/pyproject.toml": ( + "[build-system]\n" + 'requires = ["flit_core >=3.4,<4"]\n' + 'build-backend = "flit_core.buildapi"\n' + ), + "typing_extensions-4.8.0/src/typing_extensions.py": "X = 1\n", + }, + ) + self.assertEqual( + inspect_sdist.inspect_sdist(flit_sdist)["site_paths"], + ["typing_extensions.py"], + ) + + maturin_sdist = _make_sdist_tar( + pathlib.Path(tmp) / "pydantic_core-2.10.0.tar.gz", + { + "pydantic_core-2.10.0/pyproject.toml": ( + "[build-system]\n" + 'requires = ["maturin>=1.0,<2.0"]\n' + 'build-backend = "maturin"\n' + "[tool.maturin]\n" + 'python-source = "python"\n' + ), + "pydantic_core-2.10.0/src/lib.rs": "fn main() {}\n", + "pydantic_core-2.10.0/python/pydantic_core/__init__.py": "X = 1\n", + }, + ) + self.assertEqual( + inspect_sdist.inspect_sdist(maturin_sdist)["site_paths"], + ["pydantic_core"], + ) + + def test_pkg_info_pep643_dynamic_and_invalid_toml(self): + with tempfile.TemporaryDirectory() as tmp: + dyn_sdist = _make_sdist_tar( + pathlib.Path(tmp) / "dyn_pkg-1.0.tar.gz", + { + "dyn_pkg-1.0/PKG-INFO": ( + "Metadata-Version: 2.2\n" + "Name: dyn-pkg\n" + "Version: 1.0\n" + "Dynamic: Requires-Dist\n" + ), + "dyn_pkg-1.0/dyn_pkg.egg-info/requires.txt": "urllib3>=1.26\n", + "dyn_pkg-1.0/dyn_pkg/__init__.py": "X = 1\n", + }, + ) + self.assertEqual( + inspect_sdist.inspect_sdist(dyn_sdist)["requires_dist"], + ["urllib3>=1.26"], + ) + + bad_toml_sdist = _make_sdist_tar( + pathlib.Path(tmp) / "bad_toml-1.0.tar.gz", + { + "bad_toml-1.0/pyproject.toml": "[project\nname = 'broken'\n", + "bad_toml-1.0/bad_toml/__init__.py": "X = 1\n", + }, + ) + with self.assertRaisesRegex(ValueError, "Failed to parse pyproject.toml"): + inspect_sdist.inspect_sdist(bad_toml_sdist) + + # Positive pkg_resources.declare_namespace(__name__) vs negative def declare_namespace + # plus stale 'dist' in top_level.txt and package_dir remapping. + ns_and_remapped = _make_sdist_tar( + pathlib.Path(tmp) / "combo_sdist-1.0.tar.gz", + { + "combo_sdist-1.0/combo.egg-info/top_level.txt": ( + "dist\nfoo\nns_root\npkg_resources\nremapped_pkg\n" + ), + "combo_sdist-1.0/foo_impl/__init__.py": "from .foo import *\n", + "combo_sdist-1.0/foo_impl/foo.py": "F = 1\n", + "combo_sdist-1.0/ns_root/__init__.py": ( + "__import__('pkg_resources').declare_namespace(__name__)\n" + ), + "combo_sdist-1.0/ns_root/child_a/__init__.py": "A = 1\n", + "combo_sdist-1.0/pkg_resources/__init__.py": ( + "def declare_namespace(packageName):\n pass\n" + ), + "combo_sdist-1.0/pkg_resources/_vendor/__init__.py": "V = 1\n", + "combo_sdist-1.0/lib/remapped_pkg/__init__.py": "R = 1\n", + }, + ) + combo_res = inspect_sdist.inspect_sdist(ns_and_remapped) + self.assertEqual( + combo_res["site_paths"], + ["foo", "ns_root/child_a", "pkg_resources", "remapped_pkg"], + ) + self.assertEqual( + combo_res["namespace_package_files"], + ["ns_root/__init__.py"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/pypi/py_wheel_library/py_wheel_library_bzl_tests.bzl b/tests/pypi/py_wheel_library/py_wheel_library_bzl_tests.bzl index 65767d675b..b143980905 100644 --- a/tests/pypi/py_wheel_library/py_wheel_library_bzl_tests.bzl +++ b/tests/pypi/py_wheel_library/py_wheel_library_bzl_tests.bzl @@ -7,7 +7,9 @@ load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", rt_util = "util") load("//python:py_info.bzl", "PyInfo") load("//python/private:common_labels.bzl", "labels") # buildifier: disable=bzl-visibility +load("//python/private/pypi:py_wheel_extract_files.bzl", "wheel_glob") # buildifier: disable=bzl-visibility load("//python/private/pypi:py_wheel_library.bzl", "py_wheel_library") # buildifier: disable=bzl-visibility +load("//python/private/pypi:whl_library_srcs.bzl", "whl_library_srcs") # buildifier: disable=bzl-visibility load("//tests/support:py_info_subject.bzl", "py_info_subject") load( "//tests/support:support.bzl", @@ -318,6 +320,50 @@ def _test_missing_exec_tools_toolchain_fails_impl(env, target): _tests.append(_test_missing_exec_tools_toolchain_fails) def py_wheel_library_bzl_test_suite(name): + """Create the analysis test suite for `py_wheel_library`. + + Args: + name: The name of the test suite. + """ + + # Real (non-mocked) whl_library_srcs + wheel_glob verification on an + # action-built sdist with empty site_paths using real native.existing_rule. + whl_library_srcs( + name = name + ".empty_site_paths-0.5.0.sdist_build.whl", + action_install = True, + sdist_filename = ":gen_demo_sdist", + sdist = { + "build_deps": [ + ":classic_bdep", + ":custom_build_helper", + ":custom_shadow_dep", + ":demo_wheel_lib", + ], + "distribution": "sdist-demo", + "pre_build_patch_strips": [1], + "pre_build_patches": ["pre_build.patch"], + "site_paths": [], + "tags": ["manual"], + "version": "0.5.0", + }, + tags = ["manual"], + native = struct( + existing_rule = native.existing_rule, + filegroup = lambda **kwargs: native.filegroup(tags = ["manual"], **kwargs), + ), + ) + sdist_glob_errors = [] + wheel_glob(["**"], _fail = sdist_glob_errors.append) + if ( + len(sdist_glob_errors) != 1 or + "cannot be used with an action-built sdist" not in sdist_glob_errors[0] + ): + fail( + "Expected wheel_glob() to fail on real action-built sdist with empty site_paths, got: {}".format( + sdist_glob_errors, + ), + ) + test_suite( name = name, tests = _tests, diff --git a/tests/pypi/whl_library_srcs/whl_library_srcs_tests.bzl b/tests/pypi/whl_library_srcs/whl_library_srcs_tests.bzl index 1c4706de7f..a6163d6308 100644 --- a/tests/pypi/whl_library_srcs/whl_library_srcs_tests.bzl +++ b/tests/pypi/whl_library_srcs/whl_library_srcs_tests.bzl @@ -22,6 +22,7 @@ load( "wheel_glob", ) # buildifier: disable=bzl-visibility load("//python/private/pypi:whl_library_srcs.bzl", "whl_library_srcs") # buildifier: disable=bzl-visibility +load("//python/private/pypi:whl_library_targets.bzl", "whl_library_targets") # buildifier: disable=bzl-visibility load("//tests/support/mocks:mocks.bzl", "mocks") _tests = [] @@ -728,6 +729,137 @@ def _test_wheel_glob_dedup_and_sdist_failure(env): _tests.append(_test_wheel_glob_dedup_and_sdist_failure) +def _test_action_sdist(env): + py_sdist_wheel_calls = [] + py_wheel_library_calls = [] + env_marker_setting_calls = [] + filegroup_calls = [] + + whl_library_targets( + name = "foo-1.0.sdist_build.whl", + action_install = True, + sdist_filename = "foo-1.0.tar.gz", + metadata_name = "foo", + dep_template = "@pypi//{name}:{target}", + include = ["foo", "hatchling", "cython", "tomli", "setuptools_scm"], + sdist = { + "add_libdir_to_library_search_path": True, + "build_deps": [ + "@@+pip+pypi//setuptools_scm:pkg", + "@@//third_party/flit_core:flit_core", + "@@//:custom_builder_bundle", + ], + "build_requires": [ + "setuptools>=61", + "setuptools-scm>=8", + "flit-core>=3.8", + "some-custom-backend>=1.0", + "hatchling>=1.18", + "tomli>=1.0; python_version < '3.11'", + "cython; python_version >= '3.8'", + "cffi; implementation_name == 'pypy'", + "nonexistent; extra == 'dev'", + ], + "config_settings": {"--build-option": "--pure"}, + "environment": {"FOO_ENV": "1"}, + "pre_build_patch_strips": [1], + "pre_build_patches": ["//patches:pre.patch"], + "site_paths": ["foo"], + }, + tags = ["pypi_name=foo", "pypi_version=1.0"], + native = struct( + alias = lambda **_: None, + filegroup = lambda **kwargs: filegroup_calls.append(kwargs), + glob = lambda *args, **kwargs: env.fail("glob should not be called in action mode"), + ), + rules = struct( + env_marker_setting = lambda **kwargs: env_marker_setting_calls.append(kwargs), + py_sdist_wheel = lambda **kwargs: py_sdist_wheel_calls.append(kwargs), + py_wheel_library = lambda **kwargs: py_wheel_library_calls.append(kwargs), + ), + ) + + env.expect.that_int(len(py_sdist_wheel_calls)).equals(1) + sdist_call = py_sdist_wheel_calls[0] + env.expect.that_str(sdist_call["name"]).equals("foo-1.0.sdist_build.whl") + env.expect.that_str(sdist_call["sdist"]).equals("foo-1.0.tar.gz") + env.expect.that_dict(sdist_call).contains_at_least({ + "add_libdir_to_library_search_path": True, + "build_deps": [ + "@@+pip+pypi//setuptools_scm:pkg", + "@@//third_party/flit_core:flit_core", + "@@//:custom_builder_bundle", + "@pypi//hatchling:pkg", + ] + select({ + ":is_include_sdist_build_cython_true": ["@pypi//cython:pkg"], + "//conditions:default": [], + }), + "config_settings": {"--build-option": "--pure"}, + "environment": {"FOO_ENV": "1"}, + "pre_build_patch_strips": [1], + "pre_build_patches": ["//patches:pre.patch"], + }) + env.expect.that_collection(env_marker_setting_calls).contains_exactly([ + { + "expression": 'python_version >= "3.8"', + "name": "include_sdist_build_cython", + "visibility": ["//visibility:private"], + }, + ]) + env.expect.that_collection(filegroup_calls).contains_at_least([ + { + "name": "whl_file", + "srcs": ["foo-1.0.sdist_build.whl"], + "visibility": ["//visibility:public"], + }, + { + "name": "whldir", + "output_group": "whldir", + "srcs": ["foo-1.0.sdist_build.whl"], + "visibility": ["//visibility:public"], + }, + { + "name": "dist_info", + "output_group": "dist_info", + "srcs": [":srcs"], + "visibility": ["//visibility:public"], + }, + ]) + + env.expect.that_int(len(py_wheel_library_calls)).equals(1) + whl_call = py_wheel_library_calls[0] + env.expect.that_str(whl_call["name"]).equals("srcs") + env.expect.that_str(whl_call["wheel"]).equals("foo-1.0.sdist_build.whl") + env.expect.that_collection(whl_call["site_paths"]).contains_exactly(["foo"]) + + # Verify sdist fails with guidance naming py_wheel_extract_files on custom filegroups + # or wheel-internal copy_files. + sdist_fg_errors = [] + whl_library_srcs( + name = "foo-1.0.sdist_build.whl", + action_install = True, + sdist_filename = "foo-1.0.tar.gz", + sdist = {"site_paths": ["foo"]}, + filegroups = {"custom_fg": ["site-packages/**"]}, + _fail = sdist_fg_errors.append, + ) + env.expect.that_int(len(sdist_fg_errors)).equals(1) + env.expect.that_str(sdist_fg_errors[0]).contains("py_wheel_extract_files") + + sdist_copy_errors = [] + whl_library_srcs( + name = "foo-1.0.sdist_build.whl", + action_install = True, + sdist_filename = "foo-1.0.tar.gz", + sdist = {"site_paths": ["foo"]}, + copy_files = {"site-packages/foo/cfg.txt": "copied_cfg.txt"}, + _fail = sdist_copy_errors.append, + ) + env.expect.that_int(len(sdist_copy_errors)).equals(1) + env.expect.that_str(sdist_copy_errors[0]).contains("py_wheel_extract_files") + +_tests.append(_test_action_sdist) + def whl_library_srcs_test_suite(name): """create the test suite. From 403a20459f5dabfc083e335c115f3a942480fe65 Mon Sep 17 00:00:00 2001 From: Richard Sartor Date: Tue, 17 Nov 2026 05:57:24 +0000 Subject: [PATCH 6/9] Use hermetic-llvm for cross-compiling toolchains. --- python/private/pypi/py_sdist_wheel.bzl | 98 ++++++++++- python/private/pypi/sdist_wheel_builder.py | 191 ++++++++++++++++++++- 2 files changed, 281 insertions(+), 8 deletions(-) diff --git a/python/private/pypi/py_sdist_wheel.bzl b/python/private/pypi/py_sdist_wheel.bzl index c999d804d3..e3352ada26 100644 --- a/python/private/pypi/py_sdist_wheel.bzl +++ b/python/private/pypi/py_sdist_wheel.bzl @@ -1,5 +1,8 @@ """Rule for building a Python wheel (.whl) from an sdist archive in a Bazel build action.""" +load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES") +load("@rules_cc//cc:find_cc_toolchain.bzl", "find_cc_toolchain") +load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("//python/private:attr_builders.bzl", "attrb") load("//python/private:attributes.bzl", "REQUIRED_EXEC_GROUP_BUILDERS") load("//python/private:builders.bzl", "builders") @@ -13,6 +16,8 @@ load( "//python/private:toolchain_types.bzl", "EXEC_TOOLS_TOOLCHAIN_TYPE", "TARGET_TOOLCHAIN_TYPE", + "CC_TOOLCHAIN_TYPE", + "PY_CC_TOOLCHAIN_TYPE", ) load("//python/private:version.bzl", "version") load(":py_installed_wheel_info.bzl", "PyInstalledWheelInfo") @@ -157,6 +162,9 @@ Note that git-formatted patches with `a/` and `b/` path prefixes require strip ` cfg = "exec", default = _BOOTSTRAP_DEPS, ), + "_cc_toolchain": lambda: attrb.Label( + default = Label("@rules_cc//cc:current_cc_toolchain"), + ), "_platform_constraints": lambda: attrb.LabelKeyedStringDict( default = _PLATFORM_CONSTRAINTS, ), @@ -277,6 +285,10 @@ def _py_sdist_wheel_impl(ctx): target_runtime = target_tc.py3_runtime if target_tc else None _validate_sdist_toolchains(exec_runtime, target_runtime) + cc_toolchain = find_cc_toolchain(ctx, mandatory = False) + py_cc_tc_info = ctx.toolchains[PY_CC_TOOLCHAIN_TYPE] + py_cc_toolchain = py_cc_tc_info.py_cc_toolchain if py_cc_tc_info else None + if not ctx.attr.distribution or not ctx.attr.version: parsed_dist, parsed_ver = _parse_sdist_filename(ctx.file.sdist.basename) else: @@ -352,6 +364,87 @@ def _py_sdist_wheel_impl(ctx): for patch_file, strip_val in zip(patches, strips): args.add("--patch", "{}:{}".format(patch_file.path, strip_val)) + transitive_inputs = [build_deps.files, bootstrap_deps.files] + + if cc_toolchain: + transitive_inputs.append(cc_toolchain.all_files) + feature_config = cc_common.configure_features( + ctx = ctx, + cc_toolchain = cc_toolchain, + requested_features = ctx.features, + unsupported_features = ctx.disabled_features, + ) + cc_bin = cc_common.get_tool_for_action( + feature_configuration = feature_config, + action_name = ACTION_NAMES.c_compile, + ) + cxx_bin = cc_common.get_tool_for_action( + feature_configuration = feature_config, + action_name = ACTION_NAMES.cpp_compile, + ) + compile_vars = cc_common.create_compile_variables( + cc_toolchain = cc_toolchain, + feature_configuration = feature_config, + use_pic = True, + ) + c_flags = cc_common.get_memory_inefficient_command_line( + feature_configuration = feature_config, + action_name = ACTION_NAMES.c_compile, + variables = compile_vars, + ) + cxx_flags = cc_common.get_memory_inefficient_command_line( + feature_configuration = feature_config, + action_name = ACTION_NAMES.cpp_compile, + variables = compile_vars, + ) + link_vars = cc_common.create_link_variables( + cc_toolchain = cc_toolchain, + feature_configuration = feature_config, + is_using_linker = True, + is_linking_dynamic_library = True, + ) + ld_flags = cc_common.get_memory_inefficient_command_line( + feature_configuration = feature_config, + action_name = ACTION_NAMES.cpp_link_dynamic_library, + variables = link_vars, + ) + static_rt_libs = cc_toolchain.static_runtime_lib( + feature_configuration = feature_config, + ) + transitive_inputs.append(static_rt_libs) + if cc_bin: + args.add("--cc", cc_bin) + if cxx_bin: + args.add("--cxx", cxx_bin) + if cc_toolchain.ar_executable: + args.add("--ar", cc_toolchain.ar_executable) + if cc_toolchain.sysroot: + args.add("--sysroot", cc_toolchain.sysroot) + args.add_all(c_flags, format_each = "--cflag=%s") + args.add_all(cxx_flags, format_each = "--cxxflag=%s") + args.add_all(ld_flags, format_each = "--ldflag=%s") + args.add_all(static_rt_libs, format_each = "--ldflag=%s") + + # Target Python runtime files (includes target lib/python3.13/_sysconfigdata_*.py) + if target_runtime and target_runtime.interpreter: + transitive_inputs.append(target_runtime.files) + # interpreter is /bin/python3, so dirname of dirname is + args.add("--target-python-bin", target_runtime.interpreter.path) + + # Target Python C headers (include/python3.13/Python.h, pyconfig.h) & SOABI + if py_cc_toolchain: + headers_cc_info = py_cc_toolchain.headers.providers_map["CcInfo"] + transitive_inputs.append(headers_cc_info.compilation_context.headers) + args.add_all( + headers_cc_info.compilation_context.includes, + uniquify = True, + format_each = "--target-python-include=%s", + ) + if py_cc_toolchain.soabi: + args.add("--target-soabi", py_cc_toolchain.soabi) + if py_cc_toolchain.platform_tag: + args.add("--target-platform-tag", py_cc_toolchain.platform_tag) + helper_files = ( ctx.files._sdist_wheel_builder_helpers if PyInterpreterProgramInfo in ctx.attr.builder else [] ) @@ -363,7 +456,7 @@ def _py_sdist_wheel_impl(ctx): ) inputs = depset( direct = [ctx.file.sdist] + patches + helper_files, - transitive = [build_deps.files, bootstrap_deps.files], + transitive = transitive_inputs, ) actions_run( @@ -415,10 +508,13 @@ and only supports building wheels compatible with the host platform. ::: """, exec_groups = dict(REQUIRED_EXEC_GROUP_BUILDERS), + fragments = ["cpp"], attrs = PY_SDIST_WHEEL_ATTRS, provides = [PyBuiltWheelInfo], toolchains = [ ruleb.ToolchainType(TARGET_TOOLCHAIN_TYPE, mandatory = False), ruleb.ToolchainType(EXEC_TOOLS_TOOLCHAIN_TYPE, mandatory = True), + ruleb.ToolchainType(CC_TOOLCHAIN_TYPE, mandatory = False), + ruleb.ToolchainType(PY_CC_TOOLCHAIN_TYPE, mandatory = False), ], ).build() diff --git a/python/private/pypi/sdist_wheel_builder.py b/python/private/pypi/sdist_wheel_builder.py index 197cb9f912..796ff7a9f2 100644 --- a/python/private/pypi/sdist_wheel_builder.py +++ b/python/private/pypi/sdist_wheel_builder.py @@ -17,6 +17,7 @@ import importlib.metadata import os import platform +import shlex import shutil import subprocess import sys @@ -329,17 +330,35 @@ def main() -> None: parser.add_argument("--target-os", default="") parser.add_argument("--target-cpu", default="") parser.add_argument("--target-python-version", default="") + parser.add_argument("--cc", default="") + parser.add_argument("--cxx", default="") + parser.add_argument("--ar", default="") + parser.add_argument("--cflag", action="append", dest="cflags", default=[]) + parser.add_argument("--cxxflag", action="append", dest="cxxflags", default=[]) + parser.add_argument("--ldflag", action="append", dest="ldflags", default=[]) + parser.add_argument("--sysroot", default="") + parser.add_argument("--target-python-bin", default="") + parser.add_argument( + "--target-python-include", + action="append", + dest="target_python_includes", + default=[], + ) + parser.add_argument("--target-soabi", default="") + parser.add_argument("--target-platform-tag", 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 - ): + is_cross = bool( + (args.target_os and args.target_os != host_os) or + (args.target_cpu and args.target_cpu != host_cpu) + ) + if is_cross and not args.cc: 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." + "but no cross-compiler (--cc) was provided." ) 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: @@ -407,6 +426,12 @@ def main() -> None: strip=int(raw_strip), ) + def _resolve_tool(prefix: Path, raw: str) -> str: + if not raw or os.path.isabs(raw): + return raw + candidate = (prefix / raw).absolute() + return str(candidate) if candidate.exists() else raw + env = dict(orig_env) env["PYTHONHASHSEED"] = "0" env["PYTHONNOUSERSITE"] = "1" @@ -430,8 +455,86 @@ def main() -> None: else rust_remap_flag ) - include_dir = sysconfig.get_path("include") or "" + cc_bin = _resolve_tool(prefix, args.cc) + cxx_bin = _resolve_tool(prefix, args.cxx) + ar_bin = _resolve_tool(prefix, args.ar) + if cc_bin: + env["CC"] = cc_bin + env["LDSHARED"] = f"{cc_bin} -shared" + if cxx_bin: + env["CXX"] = cxx_bin + env["LDCXXSHARED"] = f"{cxx_bin} -shared" + if ar_bin: + env["AR"] = ar_bin + if args.sysroot: + sysroot_abs = _resolve_tool(prefix, args.sysroot) + for var in ("CFLAGS", "CXXFLAGS", "LDFLAGS"): + env[var] = ( + f"{env[var]} --sysroot={sysroot_abs}" + if env.get(var) else f"--sysroot={sysroot_abs}" + ) + + # Because pip wheel runs with cwd=sdist_root (`scratch_dir/src/...`) + # rather than the Bazel execroot, any execroot-relative paths + # (`external/...`) in those flags need to be turned into absolute + # paths (`prefix / ...`). + + def _absolutize_flag(prefix: Path, flag: str) -> str: + if flag.startswith("-Wl,"): + parts = flag[4:].split(",") + new_parts = [] + for p in parts: + if p.startswith("-L") and len(p) > 2 and not os.path.isabs(p[2:]) and (prefix / p[2:]).exists(): + new_parts.append("-L" + str((prefix / p[2:]).absolute())) + elif p and not p.startswith("-") and not os.path.isabs(p) and (prefix / p).exists(): + new_parts.append(str((prefix / p).absolute())) + else: + new_parts.append(p) + return "-Wl," + ",".join(new_parts) + for opt in ("--sysroot=", "-resource-dir=", "-isystem", "-I", "-L", "-B"): + if flag.startswith(opt) and len(flag) > len(opt): + rel = flag[len(opt):] + if not os.path.isabs(rel) and (prefix / rel).exists(): + return opt + str((prefix / rel).absolute()) + return flag + if flag.startswith("-") and "=" in flag: + key, _, rel = flag.partition("=") + if "/" in rel and not os.path.isabs(rel) and (prefix / rel).exists(): + return f"{key}={str((prefix / rel).absolute())}" + if flag and not flag.startswith("-") and not os.path.isabs(flag) and (prefix / flag).exists(): + return str((prefix / flag).absolute()) + return flag + + link_resource_dirs = [f for f in args.ldflags if f.startswith("-resource-dir=")] + redacted_prefixes = ("-D__DATE__=", "-D__TIMESTAMP__=", "-D__TIME__=") + + def _sanitize_compile_flags(flags: list[str]) -> list[str]: + out = [f for f in flags if not f.startswith(redacted_prefixes)] + if not link_resource_dirs: + return out + return [ + link_resource_dirs[-1] if f.startswith("-resource-dir=") else f + for f in out + ] + + for var, raw_flags in ( + ("CFLAGS", _sanitize_compile_flags(args.cflags)), + ("CXXFLAGS", _sanitize_compile_flags(args.cxxflags)), + ("LDFLAGS", [f for f in args.ldflags if f != "-shared"]), + ): + if raw_flags: + resolved = " ".join(shlex.quote(_absolutize_flag(prefix, f)) for f in raw_flags) + env[var] = f"{env[var]} {resolved}" if env.get(var) else resolved + cppflags: list[str] = [env["CPPFLAGS"]] if env.get("CPPFLAGS") else [] + if args.target_python_includes: + for inc in args.target_python_includes: + inc_abs = str((prefix / inc).absolute()) + cppflags.append(f"-I{inc_abs}") + else: + include_dir = sysconfig.get_path("include") or "" + if include_dir and os.path.isdir(include_dir): + cppflags.append(f"-isystem {include_dir}") sysroot_flag = _get_macos_sysroot_cflag() if ( sysroot_flag @@ -439,8 +542,6 @@ def main() -> None: 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) @@ -464,6 +565,82 @@ def main() -> None: pip_config_args = [f"--config-settings={cs}" for cs in args.config_settings] + if is_cross: + if args.target_os == "linux" and args.target_cpu: + env["_PYTHON_HOST_PLATFORM"] = f"linux-{args.target_cpu}" + if args.target_soabi: + ext = ".pyd" if args.target_os == "windows" else ".so" + env["SETUPTOOLS_EXT_SUFFIX"] = f".{args.target_soabi}{ext}" + if args.target_python_bin and args.target_python_version: + target_py_root = (prefix / args.target_python_bin).absolute().parent.parent + target_stdlib = target_py_root / "lib" / f"python{args.target_python_version}" + sysconfig_files = sorted(target_stdlib.glob("_sysconfigdata_*.py")) + if sysconfig_files: + sc_src = sysconfig_files[0] + sc_dir = scratch_dir / "sysconfig" + sc_dir.mkdir(parents=True, exist_ok=True) + sc_text = sc_src.read_text(encoding="utf-8") + if args.target_python_includes: + inc_dirs = [ + str((prefix / inc).absolute()) + for inc in args.target_python_includes + if (prefix / inc / "Python.h").is_file() + ] + inc_abs = ( + inc_dirs[0] + if inc_dirs + else str((prefix / args.target_python_includes[-1]).absolute()) + ) + sc_text += ( + f"\nbuild_time_vars['INCLUDEPY'] = {inc_abs!r}\n" + f"build_time_vars['CONFINCLUDEPY'] = {inc_abs!r}\n" + ) + (sc_dir / sc_src.name).write_text(sc_text, encoding="utf-8") + env["_PYTHON_SYSCONFIGDATA_NAME"] = sc_src.stem + resolved_python_paths.insert(0, str(sc_dir)) + env["PYTHONPATH"] = os.pathsep.join(resolved_python_paths) + + pyproject_file = sdist_root / "pyproject.toml" + if (is_cross and + pyproject_file.is_file() and + "mesonpy" in pyproject_file.read_text(errors="ignore")): + cpu_family = {"x86_32": "x86"}.get(args.target_cpu, args.target_cpu) + cross_ini = scratch_dir / "meson-cross.ini" + cross_lines = [ + "[binaries]", + f"c = {cc_bin!r}", + ] + if cxx_bin: + cross_lines.append(f"cpp = {cxx_bin!r}") + if ar_bin: + cross_lines.append(f"ar = {ar_bin!r}") + cross_lines += [ + "", + "[host_machine]", + f"system = {args.target_os!r}", + f"cpu_family = {cpu_family!r}", + f"cpu = {args.target_cpu!r}", + "endian = 'little'", + ] + longdouble_formats = { + ("linux", "aarch64"): "IEEE_QUAD_LE", + ("linux", "x86_64"): "INTEL_EXTENDED_16_BYTES_LE", + ("linux", "x86_32"): "INTEL_EXTENDED_12_BYTES_LE", + ("macos", "aarch64"): "IEEE_DOUBLE_LE", + ("macos", "x86_64"): "INTEL_EXTENDED_16_BYTES_LE", + ("windows", "aarch64"): "IEEE_DOUBLE_LE", + ("windows", "x86_64"): "IEEE_DOUBLE_LE", + } + ld_fmt = longdouble_formats.get((args.target_os, args.target_cpu)) + if ld_fmt: + cross_lines += [ + "", + "[properties]", + f"longdouble_format = {ld_fmt!r}", + ] + cross_ini.write_text("\n".join(cross_lines) + "\n", encoding="utf-8") + pip_config_args.append(f"--config-settings=setup-args=--cross-file={cross_ini}") + cmd = [ build_python, "-m", From 825be2ecd56a75f41419a375d7b5742994582475 Mon Sep 17 00:00:00 2001 From: Richard Sartor Date: Thu, 19 Nov 2026 21:25:27 +0000 Subject: [PATCH 7/9] Add adjustments for hermetic_cc_toolchain. --- python/private/pypi/sdist_wheel_builder.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/python/private/pypi/sdist_wheel_builder.py b/python/private/pypi/sdist_wheel_builder.py index 796ff7a9f2..47745b4ccb 100644 --- a/python/private/pypi/sdist_wheel_builder.py +++ b/python/private/pypi/sdist_wheel_builder.py @@ -613,7 +613,23 @@ def _sanitize_compile_flags(flags: list[str]) -> list[str]: if cxx_bin: cross_lines.append(f"cpp = {cxx_bin!r}") if ar_bin: - cross_lines.append(f"ar = {ar_bin!r}") + meson_ar = ar_bin + if "zig" in ar_bin or "zig" in cc_bin: + # zig-specific adjustment: zig's ar doesn't support thin + # archives. + ar_wrapper = scratch_bin_dir / "ar-no-thin" + ar_wrapper.write_text( + f"#!/usr/bin/env python3\n" + f"import os, sys\n" + f"args = sys.argv[1:]\n" + f"if args and not args[0].startswith('-'):\n" + f" args[0] = args[0].replace('T', '')\n" + f"os.execv({ar_bin!r}, [{ar_bin!r}, *args])\n", + encoding="utf-8", + ) + os.chmod(ar_wrapper, 0o755) + meson_ar = str(ar_wrapper) + cross_lines.append(f"ar = {meson_ar!r}") cross_lines += [ "", "[host_machine]", From f461aff1501700290095a8615280ec41c01cc46b Mon Sep 17 00:00:00 2001 From: Richard Sartor Date: Fri, 20 Nov 2026 23:33:52 +0000 Subject: [PATCH 8/9] Fix hermeticity bug. --- python/private/pypi/sdist_wheel_builder.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/python/private/pypi/sdist_wheel_builder.py b/python/private/pypi/sdist_wheel_builder.py index 47745b4ccb..cb098f824c 100644 --- a/python/private/pypi/sdist_wheel_builder.py +++ b/python/private/pypi/sdist_wheel_builder.py @@ -601,9 +601,17 @@ def _sanitize_compile_flags(flags: list[str]) -> list[str]: env["PYTHONPATH"] = os.pathsep.join(resolved_python_paths) pyproject_file = sdist_root / "pyproject.toml" - if (is_cross and - pyproject_file.is_file() and - "mesonpy" in pyproject_file.read_text(errors="ignore")): + is_meson = ( + pyproject_file.is_file() + and "mesonpy" in pyproject_file.read_text(errors="ignore") + ) + if is_meson: + # Prevent Meson from querying host pkg-config (e.g. + # /usr/lib/.../python-3.13.pc -> -I/usr/include/python3.13) + # instead of Bazel's hermetic Python headers via sysconfig. + env.setdefault("PKG_CONFIG_LIBDIR", "") + + if is_cross and is_meson: cpu_family = {"x86_32": "x86"}.get(args.target_cpu, args.target_cpu) cross_ini = scratch_dir / "meson-cross.ini" cross_lines = [ From 432de03344dac34a34dd7ee477b57d42f005f192 Mon Sep 17 00:00:00 2001 From: Richard Sartor Date: Tue, 24 Nov 2026 05:05:25 +0000 Subject: [PATCH 9/9] Add test cases for sdist, both regular and cross-compiling. --- .bazelignore | 4 + examples/sdist_cross_compile/.bazelrc | 16 ++ examples/sdist_cross_compile/.gitignore | 8 + examples/sdist_cross_compile/BUILD.bazel | 97 +++++++++++ examples/sdist_cross_compile/MODULE.bazel | 66 ++++++++ .../sdist_cross_compile/cross_compile_test.py | 72 ++++++++ .../sdist_cross_compile/make_meson_sdist.py | 160 ++++++++++++++++++ .../sdist_cross_compile/native_sdist_test.py | 32 ++++ examples/sdist_cross_compile/requirements.txt | 20 +++ examples/sdist_cross_compile/transitions.bzl | 43 +++++ 10 files changed, 518 insertions(+) create mode 100644 examples/sdist_cross_compile/.bazelrc create mode 100644 examples/sdist_cross_compile/.gitignore create mode 100644 examples/sdist_cross_compile/BUILD.bazel create mode 100644 examples/sdist_cross_compile/MODULE.bazel create mode 100644 examples/sdist_cross_compile/cross_compile_test.py create mode 100644 examples/sdist_cross_compile/make_meson_sdist.py create mode 100644 examples/sdist_cross_compile/native_sdist_test.py create mode 100644 examples/sdist_cross_compile/requirements.txt create mode 100644 examples/sdist_cross_compile/transitions.bzl diff --git a/.bazelignore b/.bazelignore index 8a3cbf9068..4b3d51bb90 100644 --- a/.bazelignore +++ b/.bazelignore @@ -24,6 +24,10 @@ examples/pip_parse/bazel-pip_parse examples/pip_parse_vendored/bazel-pip_parse_vendored examples/pip_repository_annotations/bazel-pip_repository_annotations examples/py_proto_library/bazel-py_proto_library +examples/sdist_cross_compile/bazel-bin +examples/sdist_cross_compile/bazel-out +examples/sdist_cross_compile/bazel-sdist_cross_compile +examples/sdist_cross_compile/bazel-testlogs gazelle/bazel-gazelle gazelle/examples/bzlmod_build_file_generation/bazel-bin gazelle/examples/bzlmod_build_file_generation/bazel-bzlmod_build_file_generation diff --git a/examples/sdist_cross_compile/.bazelrc b/examples/sdist_cross_compile/.bazelrc new file mode 100644 index 0000000000..a912d7ec73 --- /dev/null +++ b/examples/sdist_cross_compile/.bazelrc @@ -0,0 +1,16 @@ +common --enable_bzlmod +common --enable_platform_specific_config +common --incompatible_python_disallow_native_rules + +test --test_output=errors + +# BuildBuddy's managed cloud pool only has Linux executors; disable remote +# execution on macOS and Windows while keeping BES and Remote Cache. +common:macos --remote_executor= +common:macos --extra_execution_platforms= +common:windows --remote_executor= +common:windows --extra_execution_platforms= + +import %workspace%/../../buildbuddy.bazelrc +try-import %workspace%/../../user.bazelrc +try-import %workspace%/user.bazelrc diff --git a/examples/sdist_cross_compile/.gitignore b/examples/sdist_cross_compile/.gitignore new file mode 100644 index 0000000000..c7233ab306 --- /dev/null +++ b/examples/sdist_cross_compile/.gitignore @@ -0,0 +1,8 @@ +user.bazelrc +bazel-remote-grpc.log +bazel-execution-log.binpb.zst +/bazel-* +/bazel-bin +/bazel-genfiles +/bazel-out +/bazel-testlogs diff --git a/examples/sdist_cross_compile/BUILD.bazel b/examples/sdist_cross_compile/BUILD.bazel new file mode 100644 index 0000000000..c0054a1626 --- /dev/null +++ b/examples/sdist_cross_compile/BUILD.bazel @@ -0,0 +1,97 @@ +load("@rules_python//python:py_binary.bzl", "py_binary") +load("@rules_python//python:py_test.bzl", "py_test") +load("@rules_python//python/private/pypi:py_sdist_wheel.bzl", "py_sdist_wheel") # buildifier: disable=bzl-visibility +load("@rules_python//python/private/pypi:py_wheel_library.bzl", "py_wheel_library") # buildifier: disable=bzl-visibility +load(":transitions.bzl", "cross_platform_files") + +platform( + name = "linux_aarch64", + constraint_values = [ + "@platforms//os:linux", + "@platforms//cpu:aarch64", + "@llvm//constraints/libc:gnu.2.17", + ], +) + +# Self-contained tiny meson-python C/C++ sdist generated at build time (no +# checked-in binary archives) to exercise meson-python + meson + ninja + +# meson-cross.ini cross-compilation quickly. +py_binary( + name = "make_meson_sdist", + srcs = ["make_meson_sdist.py"], +) + +genrule( + name = "gen_tiny_meson_sdist", + outs = ["tiny_meson-0.1.0.tar.gz"], + cmd = "$(execpath :make_meson_sdist) $@", + tools = [":make_meson_sdist"], +) + +py_sdist_wheel( + name = "tiny_meson.whldir", + build_deps = [ + "@sdist_deps//meson_python:pkg", + "@sdist_deps//ninja:pkg", + ], + sdist = ":gen_tiny_meson_sdist", +) + +py_wheel_library( + name = "tiny_meson_wheel_lib", + site_paths = ["tiny_meson"], + wheel = ":tiny_meson.whldir", +) + +# Simple setuptools C-extension sdist from PyPI. +cross_platform_files( + name = "markupsafe_aarch64", + target_platform = ":linux_aarch64", + deps = ["@sdist_deps//markupsafe"], +) + +# Pure-Python sdist from PyPI (with a setuptools-scm build-time dependency). +cross_platform_files( + name = "tabulate_aarch64", + target_platform = ":linux_aarch64", + deps = ["@sdist_deps//tabulate"], +) + +# In-repo meson-python C/C++17 sdist built directly via py_sdist_wheel. +cross_platform_files( + name = "tiny_meson_aarch64", + target_platform = ":linux_aarch64", + deps = [":tiny_meson_wheel_lib"], +) + +# Exercises pip.parse + pip.whl_mods(sdist_build_deps = ...) with a real PyPI +# meson-python + pybind11 C++17 sdist. +cross_platform_files( + name = "contourpy_aarch64", + target_platform = ":linux_aarch64", + deps = ["@sdist_deps//contourpy"], +) + +py_test( + name = "native_sdist_test", + size = "small", + srcs = ["native_sdist_test.py"], + deps = [ + ":tiny_meson_wheel_lib", + "@sdist_deps//contourpy", + "@sdist_deps//markupsafe", + "@sdist_deps//tabulate", + ], +) + +py_test( + name = "cross_compile_test", + size = "small", + srcs = ["cross_compile_test.py"], + data = [ + ":contourpy_aarch64", + ":markupsafe_aarch64", + ":tabulate_aarch64", + ":tiny_meson_aarch64", + ], +) diff --git a/examples/sdist_cross_compile/MODULE.bazel b/examples/sdist_cross_compile/MODULE.bazel new file mode 100644 index 0000000000..de102504a5 --- /dev/null +++ b/examples/sdist_cross_compile/MODULE.bazel @@ -0,0 +1,66 @@ +module( + name = "example_sdist_cross_compile", + version = "0.0.0", +) + +bazel_dep(name = "platforms", version = "1.1.0") +bazel_dep(name = "rules_cc", version = "0.2.25") +bazel_dep(name = "rules_python", version = "0.0.0") +local_path_override( + module_name = "rules_python", + path = "../..", +) + +# Hermetic LLVM C/C++ cross-compilation toolchain (linux_x86_64 -> linux_aarch64). +bazel_dep(name = "llvm", version = "0.8.27") +register_toolchains("@llvm//toolchain:all") + +# BuildBuddy RBE platform and Ubuntu 24.04 GCC toolchain (used with --config=buildbuddy_*). +bazel_dep(name = "toolchains_buildbuddy", version = "0.0.4", dev_dependency = True) +buildbuddy = use_extension( + "@toolchains_buildbuddy//:extensions.bzl", + "buildbuddy", + dev_dependency = True, +) +buildbuddy.platform(buildbuddy_container_image = "UBUNTU24_04_IMAGE") + +rules_python_config = use_extension( + "@rules_python//python/extensions:config.bzl", + "config", +) +rules_python_config.explicit_init_py(default = True) + +python = use_extension("@rules_python//python/extensions:python.bzl", "python") +python.defaults( + python_version = "3.13", +) +python.toolchain( + python_version = "3.13", +) + +pip = use_extension("@rules_python//python/extensions:pip.bzl", "pip") +# Exercise pip.parse + pip.whl_mods(sdist_build_deps = ...) end-to-end with +# contourpy, a lightweight PyPI C++17 sdist built via meson-python + pybind11. +pip.whl_mods( + hub_name = "sdist_whl_mods", + sdist_build_deps = [ + "@sdist_deps//meson_python:pkg", + "@sdist_deps//ninja:pkg", + "@sdist_deps//pybind11:pkg", + ], + whl_name = "contourpy", +) +pip.parse( + experimental_action_install = True, + hub_name = "sdist_deps", + python_version = "3.13", + requirements_lock = "//:requirements.txt", + target_platforms = [ + "linux_x86_64", + "linux_aarch64", + ], + whl_modifications = { + "@sdist_whl_mods//:contourpy.json": "contourpy", + }, +) +use_repo(pip, "sdist_deps", "sdist_whl_mods") diff --git a/examples/sdist_cross_compile/cross_compile_test.py b/examples/sdist_cross_compile/cross_compile_test.py new file mode 100644 index 0000000000..b8e9bd794f --- /dev/null +++ b/examples/sdist_cross_compile/cross_compile_test.py @@ -0,0 +1,72 @@ +import os +import pathlib +import struct +import unittest + +ELF_MAGIC = b"\x7fELF" +ELFCLASS64 = 2 +ELFDATA2LSB = 1 +EM_AARCH64 = 183 + + +def _find_runfiles_root() -> pathlib.Path: + runfiles_dir = os.environ.get("TEST_SRCDIR") or os.environ.get("RUNFILES_DIR") + if not runfiles_dir: + raise AssertionError("Neither TEST_SRCDIR nor RUNFILES_DIR is set") + return pathlib.Path(runfiles_dir) + + +def _read_elf_header(path: pathlib.Path) -> tuple[bytes, int, int, int]: + with path.open("rb") as f: + header = f.read(20) + magic = header[0:4] + ei_class = header[4] + ei_data = header[5] + # e_machine is at offset 18 (uint16, little-endian for ELFDATA2LSB). + (e_machine,) = struct.unpack(" None: + root = _find_runfiles_root() + matches = list(root.rglob(pattern)) + self.assertTrue( + matches, + f"Expected aarch64 extension matching {pattern!r} under {root}", + ) + so_path = matches[0] + magic, ei_class, ei_data, e_machine = _read_elf_header(so_path) + self.assertEqual(magic, ELF_MAGIC, f"{so_path} is not an ELF binary") + self.assertEqual(ei_class, ELFCLASS64, f"{so_path} is not 64-bit ELF") + self.assertEqual(ei_data, ELFDATA2LSB, f"{so_path} is not little-endian ELF") + self.assertEqual( + e_machine, + EM_AARCH64, + f"{so_path} has e_machine={e_machine}, expected EM_AARCH64 ({EM_AARCH64})", + ) + + def test_markupsafe_aarch64_elf(self): + self._assert_aarch64_so("_speedups.cpython-*-aarch64-linux-gnu.so") + + def test_tiny_meson_c_aarch64_elf(self): + self._assert_aarch64_so("_tiny_c.cpython-*-aarch64-linux-gnu.so") + + def test_tiny_meson_cpp_aarch64_elf(self): + self._assert_aarch64_so("_tiny_cpp.cpython-*-aarch64-linux-gnu.so") + + def test_contourpy_aarch64_elf(self): + # Exercises pip.parse + pip.whl_mods with a PyPI meson-python C++ sdist. + self._assert_aarch64_so("_contourpy.cpython-*-aarch64-linux-gnu.so") + + def test_tabulate_aarch64_present(self): + root = _find_runfiles_root() + matches = list(root.rglob("tabulate/__init__.py")) + self.assertTrue( + matches, + f"Expected tabulate/__init__.py in cross-compiled outputs under {root}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/examples/sdist_cross_compile/make_meson_sdist.py b/examples/sdist_cross_compile/make_meson_sdist.py new file mode 100644 index 0000000000..fbeaffcdac --- /dev/null +++ b/examples/sdist_cross_compile/make_meson_sdist.py @@ -0,0 +1,160 @@ +"""Generates a deterministic tiny meson-python C/C++ sdist tar.gz for testing.""" + +from __future__ import annotations + +import argparse +import io +import pathlib +import tarfile + +_PYPROJECT_TOML = """\ +[build-system] +build-backend = "mesonpy" +requires = ["meson-python"] + +[project] +name = "tiny-meson" +version = "0.1.0" +requires-python = ">=3.9" +""" + +_MESON_BUILD = """\ +project( + 'tiny-meson', + 'c', + 'cpp', + version: '0.1.0', + default_options: ['cpp_std=c++17'], +) + +py = import('python').find_installation(pure: false) + +py.install_sources( + 'tiny_meson/__init__.py', + subdir: 'tiny_meson', +) + +py.extension_module( + '_tiny_c', + 'tiny_meson/_tiny_c.c', + subdir: 'tiny_meson', + install: true, +) + +py.extension_module( + '_tiny_cpp', + 'tiny_meson/_tiny_cpp.cpp', + subdir: 'tiny_meson', + install: true, +) +""" + +_INIT_PY = """\ +from tiny_meson._tiny_c import add_ints +from tiny_meson._tiny_cpp import mul_ints + +__all__ = ["add_ints", "mul_ints"] +""" + +_TINY_C = """\ +#define PY_SSIZE_T_CLEAN +#include + +static PyObject *tiny_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 TinyCMethods[] = { + {"add_ints", tiny_add_ints, METH_VARARGS, "Add two integers in C."}, + {NULL, NULL, 0, NULL}, +}; + +static struct PyModuleDef tiny_c_module = { + PyModuleDef_HEAD_INIT, + "_tiny_c", + NULL, + -1, + TinyCMethods, +}; + +PyMODINIT_FUNC PyInit__tiny_c(void) { + return PyModule_Create(&tiny_c_module); +} +""" + +_TINY_CPP = """\ +#define PY_SSIZE_T_CLEAN +#include +#include + +namespace { + +long multiply_pair(long a, long b) { + std::vector vals = {a, b}; + return vals[0] * vals[1]; +} + +PyObject *tiny_mul_ints(PyObject *self, PyObject *args) { + long a = 0, b = 0; + if (!PyArg_ParseTuple(args, "ll", &a, &b)) { + return nullptr; + } + return PyLong_FromLong(multiply_pair(a, b)); +} + +PyMethodDef TinyCppMethods[] = { + {"mul_ints", tiny_mul_ints, METH_VARARGS, "Multiply two integers in C++."}, + {nullptr, nullptr, 0, nullptr}, +}; + +PyModuleDef tiny_cpp_module = { + PyModuleDef_HEAD_INIT, + "_tiny_cpp", + nullptr, + -1, + TinyCppMethods, +}; + +} // namespace + +PyMODINIT_FUNC PyInit__tiny_cpp(void) { + return PyModule_Create(&tiny_cpp_module); +} +""" + + +def write_sdist_tar(out: pathlib.Path, files: dict[str, str]) -> None: + 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)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("out", type=pathlib.Path) + args = parser.parse_args() + + write_sdist_tar( + args.out, + { + "tiny_meson-0.1.0/pyproject.toml": _PYPROJECT_TOML, + "tiny_meson-0.1.0/meson.build": _MESON_BUILD, + "tiny_meson-0.1.0/tiny_meson/__init__.py": _INIT_PY, + "tiny_meson-0.1.0/tiny_meson/_tiny_c.c": _TINY_C, + "tiny_meson-0.1.0/tiny_meson/_tiny_cpp.cpp": _TINY_CPP, + }, + ) + + +if __name__ == "__main__": + main() diff --git a/examples/sdist_cross_compile/native_sdist_test.py b/examples/sdist_cross_compile/native_sdist_test.py new file mode 100644 index 0000000000..1e7b4b420b --- /dev/null +++ b/examples/sdist_cross_compile/native_sdist_test.py @@ -0,0 +1,32 @@ +import unittest + +import contourpy +import markupsafe +import tabulate +import tiny_meson + + +class NativeSdistTest(unittest.TestCase): + def test_markupsafe_c_extension(self): + # Verify the compiled C speedup extension was built and loaded. + self.assertTrue(hasattr(markupsafe, "_speedups")) + self.assertEqual(str(markupsafe.escape("hi")), "<b>hi</b>") + + def test_tabulate(self): + table = tabulate.tabulate([["a", 1], ["b", 2]], headers=["k", "v"]) + self.assertIn("a", table) + self.assertIn("2", table) + + def test_tiny_meson_c_and_cpp_extensions(self): + self.assertEqual(tiny_meson.add_ints(2, 3), 5) + self.assertEqual(tiny_meson.mul_ints(4, 5), 20) + + def test_contourpy_meson_cpp_extension(self): + # Exercises pip.parse + pip.whl_mods with a PyPI meson-python C++ sdist. + cg = contourpy.contour_generator(z=[[0.0, 1.0], [1.0, 0.0]]) + lines = cg.lines(0.5) + self.assertTrue(lines) + + +if __name__ == "__main__": + unittest.main() diff --git a/examples/sdist_cross_compile/requirements.txt b/examples/sdist_cross_compile/requirements.txt new file mode 100644 index 0000000000..8167204d49 --- /dev/null +++ b/examples/sdist_cross_compile/requirements.txt @@ -0,0 +1,20 @@ +# Build-time dependency required by tabulate-0.9.0's pyproject.toml [build-system].requires +setuptools-scm==7.0.3 --hash=sha256:7934c856b042199eb44e1523b46abb881726b7d61b3c9b41a756e4ffb4adf73b + +# C-extension sdist specified via version + sdist-only sha256 +markupsafe==3.0.4 --hash=sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6 + +# Pure-Python sdist specified via direct URL +tabulate @ https://files.pythonhosted.org/packages/source/t/tabulate/tabulate-0.9.0.tar.gz --hash=sha256:0095b12bf5966de529c0feb1fa08671671b3368eec77d7ef7ab114be2c068b3c + +# Build-time dependencies for meson-python sdists +meson-python==0.22.1 +meson==1.10.2 +pyproject-metadata==0.11.0 +ninja==1.13.0 + +# Lightweight PyPI C++17 meson-python sdist (exercises pip.parse + pip.whl_mods) +contourpy==1.4.0 --hash=sha256:20156f5a1ac4f8ce02656e39a61e82164a3d359796dc8026f75b062783d500e1 +# Build-time and runtime dependencies for contourpy (installed as prebuilt wheels) +pybind11==3.1.0 +numpy==2.5.5 diff --git a/examples/sdist_cross_compile/transitions.bzl b/examples/sdist_cross_compile/transitions.bzl new file mode 100644 index 0000000000..ae803879b8 --- /dev/null +++ b/examples/sdist_cross_compile/transitions.bzl @@ -0,0 +1,43 @@ +"""Rule to build dependencies under a target platform transition.""" + +def _platform_transition_impl(_settings, attr): + return {"//command_line_option:platforms": str(attr.target_platform)} + +_platform_transition = transition( + implementation = _platform_transition_impl, + inputs = [], + outputs = ["//command_line_option:platforms"], +) + +def _cross_platform_files_impl(ctx): + files = depset( + transitive = [ + dep[DefaultInfo].files + for dep in ctx.attr.deps + ] + [ + dep[DefaultInfo].default_runfiles.files + for dep in ctx.attr.deps + ], + ) + return [ + DefaultInfo( + files = files, + runfiles = ctx.runfiles(transitive_files = files), + ), + ] + +cross_platform_files = rule( + implementation = _cross_platform_files_impl, + attrs = { + "deps": attr.label_list( + cfg = _platform_transition, + mandatory = True, + ), + "target_platform": attr.label( + mandatory = True, + ), + "_allowlist_function_transition": attr.label( + default = "@bazel_tools//tools/allowlists/function_transition_allowlist", + ), + }, +)