diff --git a/MODULE.bazel b/MODULE.bazel index 4b69b54aed..c2fad3725f 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -333,6 +333,7 @@ use_repo( "pkgutil_nspkg2", "rules_python_runtime_env_tc_info", "somepkg_with_build_files", + "whl_library_extras_consumer", "whl_library_extras_direct_dep", "whl_with_build_files", "whl_with_data1", diff --git a/docs/pypi/circular-dependencies.md b/docs/pypi/circular-dependencies.md index 62613f489e..2d510316e7 100644 --- a/docs/pypi/circular-dependencies.md +++ b/docs/pypi/circular-dependencies.md @@ -65,6 +65,32 @@ be a part of the `airflow` cycle. For instance: ) ``` +Each extra of a package has its own target, so a cycle that goes through an +extra back to the package without extras, e.g. `foo[bar]` depending on `baz` +which depends on `foo`, is not a cycle in Bazel and does not need a group. If +the cycle includes the extra itself, e.g. `baz` depends on `foo[bar]`, then +only the extra needs to be a member of the group: + +```starlark + ... + experimental_requirement_cycles = { + "foo": [ + "foo[bar]", + "baz", + ] + } +) +``` + +Only the targets of the members, `@pypi//foo:[bar]` and `@pypi//baz`, are +then part of the group and the other targets of `foo`, e.g. `@pypi//foo:[]`, +can be used without the group. The `whl` targets do not use the extras, so +only the packages without extras are part of the group for the `whl` targets. + +:::{versionadded} VERSION_NEXT_FEATURE +Support for the extras as members of the groups. +::: + Alternatively, one could resolve the cycle by removing one leg of it. For example, while `apache-airflow-providers-sqlite` is "baked into" the Airflow diff --git a/docs/pypi/use.md b/docs/pypi/use.md index 9d0c54c4ab..58953879bb 100644 --- a/docs/pypi/use.md +++ b/docs/pypi/use.md @@ -57,11 +57,101 @@ which can help you create a `py_binary` target for a particular console script e [whl_ep]: https://packaging.python.org/specifications/entry-points/ +{#extras} ## 'Extras' dependencies -Any "extras" specified in the requirements lock file will be automatically added -as transitive dependencies of the package. In the example above, you'd just put -`requirement("useful_dep")` or `@pypi//useful_dep`. +Any "extras" specified in the requirements lock file or the `uv.lock` file will +be automatically added as transitive dependencies of the package. In the +example above, you'd just put `requirement("useful_dep")` or +`@pypi//useful_dep`. + +If you need only some of the extras, the hub repo also has a target for the +package without any extras and a target for each extra used in the lock file. +For example, if the lock file has `google-api-core[async_rest,grpc]`, then the +hub has: + +``` +@pypi//google_api_core # The package with the requested extras +@pypi//google_api_core:[] # The package without any extras +@pypi//google_api_core:[async_rest] # The package with the async_rest extra +@pypi//google_api_core:[grpc] # The package with the grpc extra +``` + +Extra names are normalized in the same way as the package names, so +`async-rest` becomes `async_rest`. + +The `requirement` helper supports the same syntax: + +```starlark +load("@pypi//:requirements.bzl", "requirement") + +py_library( + name = "my_lib", + deps = [ + requirement("google-api-core[grpc]"), + ], +) +``` + +There are no targets for combinations of extras, because each `[extra]` target +already includes the package. The `requirement` helper accepts at most one +extra. To request more than one extra, depend on the target of each extra: + +```starlark +py_library( + name = "my_lib", + deps = [ + ":other_lib", + "@pypi//google_api_core:[async_rest]", + "@pypi//google_api_core:[grpc]", + "@pypi//numpy", + ], +) +``` + +If the lock file requests different extras for a package on different +platforms, for example `foo[bar]` on Linux and `foo[baz]` on macOS, then +`@pypi//foo` includes only the extras requested for the target platform and +`@pypi//foo:[bar]` on macOS is the same as `@pypi//foo:[]`. + +The dependencies of the packages use the extras written in the wheel +`METADATA`, so if `foo` depends on `bar[socks]`, then `@pypi//foo` depends on +`@pypi//bar:[socks]`. If the extra is not in the lock file, then building +`@pypi//foo` fails with a message asking you to add `bar[socks]` to the +requirements or the lock file. For example, when compiling the requirements +with `uv pip compile`, pass `--no-strip-extras` to keep the extras in the +output. + +If the lock file requests an extra that the package does not provide, e.g. +`foo[nope]`, then `@pypi//foo:[nope]` is the same as `@pypi//foo:[]`, because +an unknown extra does not have any dependencies. A warning is printed when the +package is loaded, e.g. `WARNING: foo 1.0 does not provide the extra 'nope'`, +which is how `pip` handles the unknown extras. The extras that a package +provides are the `Provides-Extra` fields of the wheel `METADATA` and the extras +that are used in the markers of its requirements, e.g. `extra == "socks"`, +because the old metadata versions do not have the `Provides-Extra` fields. + +In bzlmod the extras are not passed to the repositories of the wheels, so +changing the extras in the lock file does not refetch them. + +When the `requirements.bzl` file is vendored, there is no hub repo and the +labels returned by the `requirement` helper point to the repositories of the +wheels. Their `pkg` targets include the extras from the lock file and they +have the `[]` target and the `[extra]` targets for the extras used in the lock +file and for all of the extras that the package provides. The dependencies +between the packages use the `pkg` targets and ignore the extras from the wheel +`METADATA` like before, so the extras need to be in the lock file. + +The `whl` targets, e.g. `@pypi//foo:whl`, do not use the extras and include +only the wheels of the package and its dependencies without extras. + +The packages in a dependency group can also have only some of their extras in +the group, see the [circular dependencies](./circular-dependencies) docs. + +:::{versionadded} VERSION_NEXT_FEATURE +The `[]` and `[extra]` targets, the support for extras in the `requirement` +helper and the `requirements` helper were added. +::: ## Consuming Wheel Dists Directly diff --git a/examples/pip_parse_vendored/requirements.bzl b/examples/pip_parse_vendored/requirements.bzl index 95c4b985f9..cbbaac0aca 100644 --- a/examples/pip_parse_vendored/requirements.bzl +++ b/examples/pip_parse_vendored/requirements.bzl @@ -5,6 +5,7 @@ load("@rules_python//python:pip.bzl", "pip_utils") load("@rules_python//python/pip_install:pip_repository.bzl", "whl_config_repo", "whl_library") +load("@rules_python//python/private/pypi:labels.bzl", "requirement_label") # buildifier: disable=bzl-visibility all_requirements = [ "@my_project_pip_deps_vendored_certifi//:pkg", @@ -79,7 +80,16 @@ _config = { _annotations = {} def requirement(name): - return "@my_project_pip_deps_vendored_{}//:{}".format(pip_utils.normalize_name(name), "pkg") + """Return the label for the package. + + Args: + name: The name of the package with at most one extra, e.g. `foo`, + `foo[]` or `foo[bar]`. + + Returns: + The label of the package. + """ + return requirement_label("@my_project_pip_deps_vendored_{}//:{}", name) def whl_requirement(name): return "@my_project_pip_deps_vendored_{}//:{}".format(pip_utils.normalize_name(name), "whl") @@ -107,8 +117,10 @@ def install_deps(**whl_library_kwargs): # Set up the requirement groups all_requirement_groups = {} + # The members are the packages, e.g. `foo`, or the extras of the packages, + # e.g. `foo[bar]`. requirement_group_mapping = { - requirement: group_name + requirement.partition("[")[0]: group_name for group_name, group_requirements in all_requirement_groups.items() for requirement in group_requirements } diff --git a/news/2786.added.md b/news/2786.added.md new file mode 100644 index 0000000000..dd87c4c4a0 --- /dev/null +++ b/news/2786.added.md @@ -0,0 +1,15 @@ +(pypi) The hub repositories now have a `[]` target for each package without +any extras and an `[extra]` target for each extra used in the lock file, e.g. +`@pypi//google_api_core:[grpc]`, in both bzlmod and `WORKSPACE`. The unified +`@pypi` hub of bzlmod has the same targets. The `requirement` macro accepts a +single extra, e.g. `requirement("google-api-core[grpc]")`. The +whl repositories also have the `[]` target and an `[extra]` target for every +extra that the package provides or the lock file requests, so they can be used +with a vendored `requirements.bzl`. In bzlmod the requested extras are no +longer passed to the whl repositories, so changing them does not refetch the +repositories. The members of +`experimental_requirement_cycles` can now be the extras of the packages, e.g. +`foo[bar]`. See +[the docs](https://rules-python.readthedocs.io/en/latest/pypi/use.html#extras) +([#2786](https://github.com/bazel-contrib/rules_python/issues/2786), +[#4168](https://github.com/bazel-contrib/rules_python/issues/4168)). diff --git a/news/2786.changed.md b/news/2786.changed.md new file mode 100644 index 0000000000..29a0897f0b --- /dev/null +++ b/news/2786.changed.md @@ -0,0 +1,17 @@ +(pypi) The dependencies between the PyPI packages now use the extras from the +wheel `METADATA`, e.g. if `foo` requires `bar[socks]`, then `@pypi//foo` +depends on `@pypi//bar:[socks]` instead of `@pypi//bar`. Previously such extras +were ignored. If the lock file of a hub does not request the extra, the build +fails with a message asking to add it, e.g. by compiling the requirements with +`--no-strip-extras`. This does not apply when there is no hub, e.g. with a +vendored `requirements.bzl`, where the dependencies use the `pkg` targets, +which include the extras from the lock file, as before. The `whl` targets no longer include the wheels of the +dependencies of the extras. A member of `experimental_requirement_cycles` +without extras, e.g. `foo`, is now only the package without extras, so the +cycles that go through `foo[bar]` need `foo[bar]` as a member. The same +distribution that is requested with different extras on different platforms +now uses a single whl repository. The `@pypi//foo` targets still include the +extras requested in the lock file. An extra that the package does not provide +is still ignored, but a warning is now printed like `pip` does, e.g. +`WARNING: foo 1.0 does not provide the extra 'nope'` +([#2786](https://github.com/bazel-contrib/rules_python/issues/2786)). diff --git a/python/private/internal_dev_deps.bzl b/python/private/internal_dev_deps.bzl index 5bbee232f9..7ca740aa6a 100644 --- a/python/private/internal_dev_deps.bzl +++ b/python/private/internal_dev_deps.bzl @@ -39,7 +39,6 @@ def _internal_dev_deps_impl(mctx): whl_library( name = "somepkg_with_build_files", whl_file = "@whl_with_build_files//:somepkg-1.0-any-none-any.whl", - requirement = "somepkg", ) # Setup for //tests/implicit_namespace_packages @@ -51,7 +50,6 @@ def _internal_dev_deps_impl(mctx): whl_library( name = "implicit_namespace_ns_sub1", whl_file = "@implicit_namespace_ns_sub1_whl//:ns_sub1-1.0-any-none-any.whl", - requirement = "ns-sub1", enable_implicit_namespace_pkgs = False, ) @@ -63,7 +61,6 @@ def _internal_dev_deps_impl(mctx): whl_library( name = "implicit_namespace_ns_sub2", whl_file = "@implicit_namespace_ns_sub2_whl//:ns_sub2-1.0-any-none-any.whl", - requirement = "ns-sub2", enable_implicit_namespace_pkgs = False, ) @@ -75,7 +72,6 @@ def _internal_dev_deps_impl(mctx): whl_library( name = "pkgutil_nspkg1", whl_file = "@pkgutil_nspkg1_whl//:pkgutil_nspkg1-1.0-any-none-any.whl", - requirement = "pkgutil_nspkg1", enable_implicit_namespace_pkgs = False, ) @@ -87,7 +83,6 @@ def _internal_dev_deps_impl(mctx): whl_library( name = "pkgutil_nspkg2", whl_file = "@pkgutil_nspkg2_whl//:pkgutil_nspkg2-1.0-any-none-any.whl", - requirement = "pkgutil_nspkg2", enable_implicit_namespace_pkgs = False, ) @@ -99,7 +94,6 @@ def _internal_dev_deps_impl(mctx): whl_library( name = "whl_with_data1", whl_file = "@whl_with_data1_whl//:whl_with_data1-1.0-any-none-any.whl", - requirement = "whl-with-data1", ) whl_from_dir_repo( @@ -110,23 +104,42 @@ def _internal_dev_deps_impl(mctx): whl_library( 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_from_dir( name = "whl_library_extras_direct_dep", root = "//tests/pypi/whl_library/testdata/pkg:BUILD.bazel", output = "pkg-1.0-any-none-any.whl", + # The `pkg` target includes the requested extras and the package does + # not provide the `unknown` extra. + requirement = "pkg[optional,unknown]", + # 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_from_dir( + name = "whl_library_extras_pkg", + root = "//tests/pypi/whl_library/testdata/pkg:BUILD.bazel", + output = "pkg-1.0-any-none-any.whl", + # Without a hub the dependencies use the `pkg` target, which includes + # the extras of the requirement. requirement = "pkg[optional]", # 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_from_dir( + name = "whl_library_extras_consumer", + root = "//tests/pypi/whl_library/testdata/consumer:BUILD.bazel", + output = "consumer-1.0-any-none-any.whl", + # 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_from_dir( name = "whl_library_extras_optional_dep", root = "//tests/pypi/whl_library/testdata/optional_dep:BUILD.bazel", output = "optional_dep-1.0-any-none-any.whl", - 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", ) @@ -140,7 +153,6 @@ def _internal_dev_deps_impl(mctx): whl_library( name = "patch_whl_pkg", whl_file = "@patch_whl_pkg_whl//:pkg-1.0-any-none-any.whl", - requirement = "pkg", whl_patches = { "//tests/pypi/patch_whl/testdata/patches:modify_pkg.patch": json.encode({ "patch_strip": 0, diff --git a/python/private/pypi/BUILD.bazel b/python/private/pypi/BUILD.bazel index e867cd9163..0d660f0d4d 100644 --- a/python/private/pypi/BUILD.bazel +++ b/python/private/pypi/BUILD.bazel @@ -141,6 +141,7 @@ bzl_library( ":hub_builder", ":hub_exposure", ":hub_repository", + ":labels", ":parse_whl_name", ":pep508_env", ":pip_repository_attrs", @@ -193,9 +194,11 @@ bzl_library( deps = [ ":attrs", ":hash", + ":labels", ":parse_requirements", ":pep508_env", ":pep508_evaluate", + ":pep508_requirement", ":python_tag", ":requirements_files_by_platform", ":whl_config_setting", @@ -284,6 +287,7 @@ bzl_library( name = "pep508_deps", srcs = ["pep508_deps.bzl"], deps = [ + ":labels", ":pep508_env", ":pep508_evaluate", ":pep508_requirement", @@ -336,8 +340,10 @@ bzl_library( deps = [ ":default_platforms", ":hash", + ":labels", ":parse_requirements", ":pep508_env", + ":pep508_requirement", ":pip_repository_attrs", ":pypi_repo_utils", ":render_pkg_aliases", @@ -363,6 +369,7 @@ bzl_library( deps = [ ":labels", ":whl_library_deps_targets", + "//python:py_library", "//python/private:common_labels", "//python/private:text_util", "@bazel_skylib//lib:selects", @@ -389,6 +396,7 @@ bzl_library( srcs = ["render_pkg_aliases.bzl"], deps = [ ":generate_group_library_build_bazel", + ":labels", "//python/private:normalize_name", "//python/private:text_util", ], @@ -617,6 +625,7 @@ bzl_library( deps = [ ":env_marker_setting", ":labels", + ":missing_package", ":pep508_deps", "//python:py_library", "//python/private:normalize_name", @@ -637,6 +646,12 @@ bzl_library( ], ) +bzl_library( + name = "labels", + srcs = ["labels.bzl"], + deps = ["//python/private:normalize_name"], +) + bzl_library( name = "dependency_groups", srcs = ["dependency_groups.bzl"], @@ -681,11 +696,6 @@ bzl_library( srcs = ["hash.bzl"], ) -bzl_library( - name = "labels", - srcs = ["labels.bzl"], -) - bzl_library( name = "package_annotation", srcs = ["package_annotation.bzl"], diff --git a/python/private/pypi/extension.bzl b/python/private/pypi/extension.bzl index 753e34e541..1d921f539d 100644 --- a/python/private/pypi/extension.bzl +++ b/python/private/pypi/extension.bzl @@ -26,6 +26,7 @@ load(":default_platforms.bzl", "default_platforms") load(":hub_builder.bzl", "hub_builder") load(":hub_exposure.bzl", "hub_exposure") load(":hub_repository.bzl", "hub_repository", "whl_config_settings_to_json") +load(":labels.bzl", "extra_label") load(":parse_whl_name.bzl", "parse_whl_name") load(":pep508_env.bzl", "env") load(":pip_repository_attrs.bzl", "ATTRS") @@ -421,9 +422,18 @@ You cannot use both the additive_build_content and additive_build_content_file a }, ) -def _create_unified_hub_repo(mods): +def unified_hub_args(mods): + """Return the args of the unified hub repository. + + Args: + mods: {type}`struct` the value returned by {obj}`parse_modules`. + + Returns: + {type}`dict | None` the args for {obj}`unified_hub_repo` or `None` if + a concrete hub uses the name of the unified hub. + """ if "pypi" in mods.hub_whl_map: - return + return None hubs = sorted(mods.hub_whl_map.keys()) if mods.default_hub and mods.default_hub not in hubs: @@ -445,8 +455,16 @@ def _create_unified_hub_repo(mods): if hub_name not in packages[norm_pkg]: packages[norm_pkg].append(hub_name) + # The `[]` targets only exist in the hubs that request + # the extra. + extras = { + extra_label(extra): None + for settings in mods.hub_whl_map[hub_name].get(pkg_name, {}).values() + for setting in settings + for extra in setting.extras or [] + } extra = mods.extra_aliases.get(hub_name, {}).get(norm_pkg, []) - for alias_name in extra: + for alias_name in sorted(extras) + extra: qual_alias = "%s:%s" % (norm_pkg, alias_name) if qual_alias not in extra_aliases: extra_aliases[qual_alias] = [] @@ -462,7 +480,7 @@ def _create_unified_hub_repo(mods): if qual_alias not in extra_aliases: extra_aliases[qual_alias] = [] - unified_hub_repo( + return dict( name = "pypi", default_hub = mods.default_hub or (hubs[0] if hubs else ""), extra_aliases = extra_aliases, @@ -471,6 +489,11 @@ def _create_unified_hub_repo(mods): requirements_bzl = mods.unified_hub_requirements_bzl, ) +def _create_unified_hub_repo(mods): + args = unified_hub_args(mods) + if args != None: + unified_hub_repo(**args) + def _pip_impl(module_ctx): """Implementation of a class tag that creates the pip hub and corresponding pip spoke whl repositories. diff --git a/python/private/pypi/generate_group_library_build_bazel.bzl b/python/private/pypi/generate_group_library_build_bazel.bzl index 571cfd6b3f..92cf8f9870 100644 --- a/python/private/pypi/generate_group_library_build_bazel.bzl +++ b/python/private/pypi/generate_group_library_build_bazel.bzl @@ -22,6 +22,8 @@ load( "PY_LIBRARY_PUBLIC_LABEL", "WHEEL_FILE_IMPL_LABEL", "WHEEL_FILE_PUBLIC_LABEL", + "extra_label", + "group_member", ) _PRELUDE = """\ @@ -60,32 +62,36 @@ def _generate_group_libraries(repo_prefix, group_name, group_members): repo_prefix: str; the pip_parse repo prefix. group_name: str; the name which the user provided for the dep group. group_members: list[str]; the names of the _packages_ (not repositories) - which make up the group. + which make up the group, optionally with a single extra, e.g. `foo[bar]`. """ - group_members = sorted(group_members) + # The whl targets do not use the extras, so only the packages without + # extras are members for the whl targets. + group_members = sorted([group_member(d) for d in group_members]) + whl_members = [d for d in group_members if "[" not in d] + packages = sorted({_package(d): None for d in group_members}) if repo_prefix: lib_dependencies = [ - "@%s%s//:%s" % (repo_prefix, normalize_name(d), PY_LIBRARY_IMPL_LABEL) + "@%s%s//:%s" % (repo_prefix, _package(d), _lib_impl_label(d)) for d in group_members ] whl_file_deps = [ "@%s%s//:%s" % (repo_prefix, normalize_name(d), WHEEL_FILE_IMPL_LABEL) - for d in group_members + for d in whl_members ] visibility = [ "@%s%s//:__pkg__" % (repo_prefix, normalize_name(d)) - for d in group_members + for d in packages ] else: lib_dependencies = [ - "//%s:%s" % (normalize_name(d), PY_LIBRARY_IMPL_LABEL) + "//%s:%s" % (_package(d), _lib_impl_label(d)) for d in group_members ] whl_file_deps = [ "//%s:%s" % (normalize_name(d), WHEEL_FILE_IMPL_LABEL) - for d in group_members + for d in whl_members ] visibility = ["//:__subpackages__"] @@ -98,6 +104,13 @@ def _generate_group_libraries(repo_prefix, group_name, group_members): visibility = render.indent(render.list(visibility)).lstrip(), ) +def _package(member): + return member.partition("[")[0] + +def _lib_impl_label(member): + _, _, extra = member.partition("[") + return "_" + extra_label(extra.rstrip("]")) if extra else PY_LIBRARY_IMPL_LABEL + def generate_group_library_build_bazel( repo_prefix, groups): diff --git a/python/private/pypi/generate_whl_library_build_bazel.bzl b/python/private/pypi/generate_whl_library_build_bazel.bzl index bec45bb08f..3b3f64cc81 100644 --- a/python/private/pypi/generate_whl_library_build_bazel.bzl +++ b/python/private/pypi/generate_whl_library_build_bazel.bzl @@ -25,6 +25,7 @@ _RENDER = { "extras": render.list, "group_deps": render.list, "include": str, + "provides_extra": render.list, "repo": lambda maybe_label: repr(str(maybe_label)), "requires_dist": render.list, "srcs_exclude": render.list, @@ -59,6 +60,7 @@ def generate_whl_library_build_bazel( config_load, purl = None, requires_dist = [], + extras = [], **kwargs): """Generate a BUILD file for an unzipped Wheel @@ -68,6 +70,7 @@ def generate_whl_library_build_bazel( config_load: {type}`str` The location from where to load the config. purl: The purl. requires_dist: {type}`list[str]` The list of dependencies from the METADATA file. + extras: {type}`list[str]` The list of requested extras. **kwargs: Extra args serialized to be passed to the {obj}`whl_library_targets`. @@ -89,15 +92,15 @@ def generate_whl_library_build_bazel( "pypi_version={}".format(metadata_version), ] kwargs["tags"] = tags + if extras: + kwargs["extras"] = extras - if not requires_dist: - # no deps, we can leave the extra loads out - pass - elif config_load: + if config_load: + # The config is also needed without any deps, because it has the + # extras that are requested from this package. loads.append("""load("{}", "{}")""".format(config_load, "packages")) kwargs["include"] = "packages" - kwargs["requires_dist"] = requires_dist - else: + if requires_dist: kwargs["requires_dist"] = requires_dist loads.extend([ diff --git a/python/private/pypi/hub_builder.bzl b/python/private/pypi/hub_builder.bzl index df0c48794e..05def3daf4 100644 --- a/python/private/pypi/hub_builder.bzl +++ b/python/private/pypi/hub_builder.bzl @@ -9,9 +9,11 @@ load("//python/private:version.bzl", "version") load("//python/private:version_label.bzl", "version_label") load(":attrs.bzl", "use_isolated") load(":hash.bzl", "hash") +load(":labels.bzl", "group_member") load(":parse_requirements.bzl", "parse_requirements") load(":pep508_env.bzl", "env") load(":pep508_evaluate.bzl", "evaluate") +load(":pep508_requirement.bzl", "requirement", "strip_extras") load(":python_tag.bzl", "python_tag") load(":requirements_files_by_platform.bzl", "requirements_files_by_platform") load(":whl_config_setting.bzl", "whl_config_setting") @@ -257,8 +259,10 @@ def _add_group_map(self, group_map): # cycles for different abis/oses? For now we will need the users to # assume the same groups across all versions/platforms until we start # using an alternative cycle resolution strategy. + # The members are the packages, e.g. `foo`, or the extras of the packages, + # e.g. `foo[bar]`. group_map = { - name: [normalize_name(whl_name) for whl_name in whls] + name: [group_member(whl_name) for whl_name in whls] for name, whls in group_map.items() } self._group_map.clear() @@ -266,7 +270,7 @@ def _add_group_map(self, group_map): self._group_map.update(group_map) self._group_name_by_whl.update({ - whl_name: group_name + whl_name.partition("[")[0]: group_name for group_name, group_whls in self._group_map.items() for whl_name in group_whls }) @@ -610,7 +614,8 @@ def _create_whl_repos( whl = whl, whl_modifications = whl_modifications, ) - for src in whl.srcs: + srcs = _merge_extras(whl.srcs) + for src in srcs: repo = _whl_repo( src = src, index_url = whl.index_url, @@ -620,16 +625,96 @@ def _create_whl_repos( use_downloader = src.url and _use_downloader(self, python_version, whl.name), auth_patterns = self._config.auth_patterns or pip_attr.auth_patterns, python_version = _major_minor_version(python_version), - is_multiple_versions = whl.is_multiple_versions, + # Different extras for the same distribution are not different versions. + is_multiple_versions = whl.is_multiple_versions and len({ + s.requirement_line: None + for s in srcs + }) > 1, interpreter = interpreter, enable_pipstar_extract = enable_pipstar_extract, ) - _add_whl_library( - self, - python_version = python_version, - whl = whl, - repo = repo, - ) + for config_setting in repo.config_settings if repo else []: + _add_whl_library( + self, + python_version = python_version, + whl = whl, + repo = struct( + repo_name = repo.repo_name, + args = repo.args, + config_setting = config_setting, + ), + ) + +def _merge_extras(srcs): + """Merge the sources that differ only in the requested extras. + + The whl repositories create targets for all of the extras that a package + provides, so the extras are not passed to them and the same distribution + requested with different extras on different platforms uses a single whl + repository. The extras of each platform are recorded so that the hub can + expose only the requested extras for each platform. + + Args: + srcs: {type}`list[struct]` the sources returned by `parse_requirements`. + + Returns: + The list of sources without the extras in the requirement line and + with an extra `extras_by_platform` attribute. + """ + merged = {} + for src in srcs: + line = strip_extras(src.requirement_line) + entry = merged.setdefault( + (src.filename, src.url, line, tuple(src.extra_pip_args)), + struct( + src = src, + line = line, + extras_by_platform = {}, + target_platforms = [], + ), + ) + extras = sorted(requirement(src.requirement_line).extras) + for p in src.target_platforms: + if p not in entry.target_platforms: + entry.target_platforms.append(p) + entry.extras_by_platform[p] = extras + + return [ + struct( + distribution = entry.src.distribution, + extra_pip_args = entry.src.extra_pip_args, + requirement_line = entry.line, + target_platforms = entry.target_platforms, + extras_by_platform = entry.extras_by_platform, + filename = entry.src.filename, + digest = entry.src.digest, + url = entry.src.url, + yanked = entry.src.yanked, + ) + for entry in merged.values() + ] + +def _config_settings(*, src, version, target_platforms): + """Return the config settings for each set of extras requested by the platforms.""" + plats_by_extras = {} + for p in src.target_platforms: + plats_by_extras.setdefault(tuple(src.extras_by_platform.get(p, [])), []).append(p) + + if len(plats_by_extras) == 1: + return [whl_config_setting( + version = version, + target_platforms = target_platforms or None, + extras = plats_by_extras.keys()[0], + )] + + return [ + whl_config_setting( + version = version, + target_platforms = plats, + extras = extras, + ) + for extras, plats in plats_by_extras.items() + ] def _common_args(self, module_ctx, *, pip_attr): # Construct args separately so that the lock file can be smaller and does not include unused @@ -699,8 +784,11 @@ def _whl_repo( interpreter, enable_pipstar_extract = False): args = dict(whl_library_args) - args["requirement"] = src.requirement_line is_whl = src.filename.endswith(".whl") + if not (src.url and is_whl): + # The requirement line is only needed for `pip` to download or build + # the wheel. + args["requirement"] = src.requirement_line if src.extra_pip_args and not is_whl: # pip is not used to download wheels and the python @@ -729,9 +817,10 @@ def _whl_repo( *target_platforms ), args = args, - config_setting = whl_config_setting( + config_settings = _config_settings( + src = src, version = python_version, - target_platforms = target_platforms or None, + target_platforms = target_platforms, ), ) @@ -762,7 +851,8 @@ def _whl_repo( return struct( repo_name = whl_repo_name(src.filename, src.digest, *target_platforms), args = args, - config_setting = whl_config_setting( + config_settings = _config_settings( + src = src, version = python_version, target_platforms = src.target_platforms, ), diff --git a/python/private/pypi/hub_repository.bzl b/python/private/pypi/hub_repository.bzl index c401168873..27fa5fdece 100644 --- a/python/private/pypi/hub_repository.bzl +++ b/python/private/pypi/hub_repository.bzl @@ -15,7 +15,7 @@ "" load("//python/private:text_util.bzl", "render") -load(":render_pkg_aliases.bzl", "render_multiplatform_pkg_aliases") +load(":render_pkg_aliases.bzl", "available_extras", "render_multiplatform_pkg_aliases") load(":whl_config_setting.bzl", "whl_config_setting") _BUILD_FILE_CONTENTS = """\ @@ -32,11 +32,12 @@ def _impl(rctx): else: bzl_packages = rctx.attr.packages or rctx.attr.whl_map.keys() exposed_packages = None + whl_map = { + key: _whl_config_settings_from_json(values) + for key, values in rctx.attr.whl_map.items() + } aliases = render_multiplatform_pkg_aliases( - aliases = { - key: _whl_config_settings_from_json(values) - for key, values in rctx.attr.whl_map.items() - }, + aliases = whl_map, exposed_packages = exposed_packages, extra_hub_aliases = rctx.attr.extra_hub_aliases, requirement_cycles = rctx.attr.groups, @@ -56,7 +57,9 @@ def _impl(rctx): "config.bzl", rctx.attr._config_template, substitutions = { - "%%PACKAGES%%": render.dict(rctx.attr.whl_map, value_repr = lambda x: "None"), + # The available extras of each package for the spoke repositories + # to check if the extras of their dependencies are available. + "%%PACKAGES%%": render.dict(available_extras(whl_map), value_repr = render.list), }, ) rctx.template("requirements.bzl", rctx.attr._requirements_bzl_template, substitutions = { @@ -164,6 +167,8 @@ def whl_config_settings_to_json(repo_mapping): def _whl_config_setting_dict(a): ret = {} + if a.extras: + ret["extras"] = a.extras if a.target_platforms: ret["target_platforms"] = a.target_platforms if a.version: diff --git a/python/private/pypi/labels.bzl b/python/private/pypi/labels.bzl index c77167b593..f15c7fb38b 100644 --- a/python/private/pypi/labels.bzl +++ b/python/private/pypi/labels.bzl @@ -14,6 +14,8 @@ """Constants used by parts of pip_repository for naming libraries and wheels.""" +load("//python/private:normalize_name.bzl", "normalize_name") + EXTRACTED_WHEEL_FILES = "extracted_whl_files" WHEEL_FILE_PUBLIC_LABEL = "whl" WHEEL_FILE_IMPL_LABEL = "_whl" @@ -24,3 +26,65 @@ PY_SRCS_LABEL = "srcs" DATA_LABEL = "data" DIST_INFO_LABEL = "dist_info" NODEPS_LABEL = "no_deps" + +def extra_label(extra): + """Return the label name for the target that includes an extra. + + Args: + extra: {type}`str` the normalized name of the extra, an empty string + means the base package without any extras. + + Returns: + The target name, e.g. `[extra]`. + """ + return "[{}]".format(extra) + +def _labels(tmpl, requirement): + name, bracket, extras = requirement.partition("[") + name = normalize_name(name.strip()) + if not bracket: + return [tmpl.format(name, PY_LIBRARY_PUBLIC_LABEL)] + + extras, _, _ = extras.partition("]") + extras = sorted([ + normalize_name(extra.strip()) + for extra in extras.split(",") + if extra.strip() + ]) + return [tmpl.format(name, extra_label(extra)) for extra in extras or [""]] + +def requirement_label(tmpl, requirement, *, fail = fail): + """Return the label for a requirement in a hub repository. + + Args: + tmpl: {type}`str` the label template with two `{}` placeholders for + the package name and the target name. + requirement: {type}`str` the name of the package with at most one + extra, e.g. `foo`, `foo[]` or `foo[bar]`. + fail: the function to call on errors, used in tests. + + Returns: + {type}`str` the label of the `pkg` target if no extras are given, the + label of the `[]` target if empty extras are given, or the label of + the `[extra]` target if one extra is given. + """ + labels = _labels(tmpl, requirement) + if len(labels) > 1: + fail("Only a single extra is supported by 'requirement', got '{}'. Depend on the target of each extra instead.".format(requirement)) + + return labels[0] + +def group_member(spec): + """Normalize a member of a dependency group. + + Args: + spec: {type}`str` the package name, e.g. `Foo`, or the package name + with a single extra, e.g. `Foo[Bar]`. + + Returns: + The normalized member, e.g. `foo` or `foo[bar]`. + """ + name, _, extra = spec.partition("[") + name = normalize_name(name.strip()) + extra = normalize_name(extra.partition("]")[0].strip()) if extra else "" + return "{}[{}]".format(name, extra) if extra else name diff --git a/python/private/pypi/missing_package.bzl b/python/private/pypi/missing_package.bzl index 46823e813b..e5647d5786 100644 --- a/python/private/pypi/missing_package.bzl +++ b/python/private/pypi/missing_package.bzl @@ -1,25 +1,16 @@ -"""Rule for generating an execution-phase action failure when a PyPI package is missing.""" +"""Rules for generating an execution-phase action failure when a PyPI package or its extra is missing.""" load("//python/private:py_info.bzl", "PyInfo") load("//python/private:reexports.bzl", "BuiltinPyInfo") -def _missing_package_error_impl(ctx): +def _error(ctx, message): out = ctx.actions.declare_file(ctx.label.name + ".error") - if ctx.attr.hub_name: - hub_clause = ' when building under PyPI hub "{hub}". Try adding it to the requirements of this hub (e.g. requirements_lock or requirements_by_platform in pip.parse)'.format( - hub = ctx.attr.hub_name, - ) - else: - hub_clause = ' because no default PyPI hub was configured. Try designating a default hub via pip.default(default_hub = "...") or select a hub using --@rules_python//python/config_settings:venv' - # Register an action that fails when Bazel attempts to stage/build this file ctx.actions.run_shell( outputs = [out], - command = "echo 'ERROR: PyPI package \"{pkg}\" is not available{hub_clause}.' >&2 && exit 1".format( - pkg = ctx.attr.package_name, - hub_clause = hub_clause, - ), + command = "echo \"$1\" >&2 && exit 1", + arguments = ["ERROR: " + message], ) maybe_builtin = [BuiltinPyInfo(transitive_sources = depset([out]))] if BuiltinPyInfo != None else [] @@ -34,6 +25,19 @@ def _missing_package_error_impl(ctx): ), ] + maybe_builtin +def _missing_package_error_impl(ctx): + if ctx.attr.hub_name: + hub_clause = ' when building under PyPI hub "{hub}". Try adding it to the requirements of this hub (e.g. requirements_lock or requirements_by_platform in pip.parse)'.format( + hub = ctx.attr.hub_name, + ) + else: + hub_clause = ' because no default PyPI hub was configured. Try designating a default hub via pip.default(default_hub = "...") or select a hub using --@rules_python//python/config_settings:venv' + + return _error(ctx, 'PyPI package "{pkg}" is not available{hub_clause}.'.format( + pkg = ctx.attr.package_name, + hub_clause = hub_clause, + )) + missing_package_error = rule( implementation = _missing_package_error_impl, attrs = { @@ -41,3 +45,25 @@ missing_package_error = rule( "package_name": attr.string(mandatory = True), }, ) + +def _missing_extra_error_impl(ctx): + return _error(ctx, ( + 'The PyPI package "{pkg}" requires "{dep}[{extra}]", but the extra "{extra}" of ' + + '"{dep}" is not available in the hub. Add "{dep}[{extra}]" to the requirements or ' + + "the lock file of the hub, e.g. by compiling the requirements with the extras kept " + + "(`--no-strip-extras`) or by adding the extra to the project dependencies." + ).format( + pkg = ctx.attr.required_by, + dep = ctx.attr.package_name, + extra = ctx.attr.extra, + )) + +missing_extra_error = rule( + implementation = _missing_extra_error_impl, + doc = "A target that fails the build with a helpful message when an extra of a PyPI package is missing.", + attrs = { + "extra": attr.string(mandatory = True), + "package_name": attr.string(mandatory = True), + "required_by": attr.string(mandatory = True), + }, +) diff --git a/python/private/pypi/patch_and_extract_whl.bzl b/python/private/pypi/patch_and_extract_whl.bzl index 37c90e3221..bf58ab1872 100644 --- a/python/private/pypi/patch_and_extract_whl.bzl +++ b/python/private/pypi/patch_and_extract_whl.bzl @@ -135,6 +135,7 @@ def patch_and_extract_whl(rctx, *, whl_path, logger, sdist_filename = None, whl_ group_deps = rctx.attr.group_deps, group_name = rctx.attr.group_name, namespace_package_files = namespace_package_files, + provides_extra = metadata.provides_extra, extras = requirement(rctx.attr.requirement).extras, entry_points = entry_points, purl = _to_purl( diff --git a/python/private/pypi/pep508_deps.bzl b/python/private/pypi/pep508_deps.bzl index e36ceadbd5..8aa74194fa 100644 --- a/python/private/pypi/pep508_deps.bzl +++ b/python/private/pypi/pep508_deps.bzl @@ -16,6 +16,7 @@ """ load("//python/private:normalize_name.bzl", "normalize_name") +load(":labels.bzl", "group_member") load(":pep508_env.bzl", "create_env") load(":pep508_evaluate.bzl", "evaluate") load(":pep508_requirement.bzl", "requirement") @@ -26,23 +27,32 @@ def deps( requires_dist, extras = [], excludes = [], - include = []): + include = [], + keep_extras = False): """Parse the RequiresDist from wheel METADATA Args: name: {type}`str` the name of the wheel. requires_dist: {type}`list[str]` the list of RequiresDist lines from the METADATA file. - excludes: {type}`list[str]` what packages should we exclude. + excludes: {type}`list[str]` what dependencies should we exclude, e.g. + `foo` or `foo[bar]`, in the same format as the returned values. include: {type}`list[str]` what packages should we exclude. If it is not specified, then we will include all deps from `requires_dist`. extras: {type}`list[str]` the requested extras to generate targets for. + keep_extras: {type}`bool` keep the extras of the dependencies, if + `True`, the dependencies with extras are returned as `foo[bar]`. Returns: A struct with attributes: * deps: {type}`list[str]` dependencies to include unconditionally. * deps_select: {type}`dict[str, list[str]]` dependencies to include on particular subset of target platforms. + + The dependencies are normalized names, e.g. `foo`, or normalized names + with a single extra, e.g. `foo[bar]`, if the dependency is requested + with extras and `keep_extras` is set. A dependency with multiple + extras, e.g. `foo[bar,baz]`, is returned as `foo[bar]` and `foo[baz]`. """ if not requires_dist: return struct( @@ -59,26 +69,27 @@ def deps( name = normalize_name(name) want_extras = _resolve_extras(name, reqs, extras) include = [normalize_name(n) for n in include] + excludes = {group_member(x): None for x in excludes} - # drop self edges - excludes = [name] + [normalize_name(x) for x in excludes] - - reqs_by_name = {} + reqs_by_dep = {} for req in reqs: - if req.name_ in excludes: + # drop self edges + if req.name_ == name: continue if include and req.name_ not in include: continue - reqs_by_name.setdefault(req.name, []).append(req) + for dep in ["{}[{}]".format(req.name_, e) for e in req.extras if keep_extras] or [req.name_]: + if dep not in excludes: + reqs_by_dep.setdefault(dep, []).append(req) - for name, reqs in reqs_by_name.items(): + for dep, reqs in reqs_by_dep.items(): _add_reqs( deps, deps_select, - normalize_name(name), + dep, reqs, extras = want_extras, ) @@ -92,8 +103,6 @@ def deps( ) def _add(deps, deps_select, dep, markers = None): - dep = normalize_name(dep) - if not markers: deps[dep] = True elif len(markers) == 1: @@ -128,7 +137,7 @@ def _resolve_extras(self_name, reqs, extras): self_reqs = [] for req in reqs: - if req.name != self_name: + if req.name_ != self_name: continue if req.marker == None: diff --git a/python/private/pypi/pep508_requirement.bzl b/python/private/pypi/pep508_requirement.bzl index 7552642572..8aaaa29e37 100644 --- a/python/private/pypi/pep508_requirement.bzl +++ b/python/private/pypi/pep508_requirement.bzl @@ -56,3 +56,22 @@ def requirement(spec): extras = extras, version = version, ) + +def strip_extras(requirement_line): + """Remove the extras from the requirement line. + + Args: + requirement_line: {type}`str` the requirement line, e.g. + `foo[bar]==1.0 --hash=sha256:...`. + + Returns: + The requirement line without the extras, e.g. `foo==1.0 --hash=sha256:...`. + """ + for i, c in enumerate(requirement_line.elems()): + if c in "=<>!~;@( ": + break + if c == "[": + _, _, tail = requirement_line[i:].partition("]") + return requirement_line[:i] + tail + + return requirement_line diff --git a/python/private/pypi/pip_archive.bzl b/python/private/pypi/pip_archive.bzl index 1764abe70d..550584ef23 100644 --- a/python/private/pypi/pip_archive.bzl +++ b/python/private/pypi/pip_archive.bzl @@ -358,6 +358,11 @@ pip_archive_attrs = { "quiet", "timeout", ] +} | { + "requirement": attr.string( + mandatory = True, + doc = "Python requirement string describing the package to download or build with `pip`. The extras are used in the same way as in {obj}`whl_archive`.", + ), } pip_archive = repository_rule( diff --git a/python/private/pypi/pip_repository.bzl b/python/private/pypi/pip_repository.bzl index d02c62eae1..36d7107777 100644 --- a/python/private/pypi/pip_repository.bzl +++ b/python/private/pypi/pip_repository.bzl @@ -22,8 +22,10 @@ load("//python/private:text_util.bzl", "render") load("//python/private:version.bzl", "version") load(":default_platforms.bzl", "default_platforms") load(":hash.bzl", "hash") +load(":labels.bzl", "group_member") load(":parse_requirements.bzl", "host_platform", "parse_requirements", "select_requirement") load(":pep508_env.bzl", "env") +load(":pep508_requirement.bzl", parse_requirement = "requirement") load(":pip_repository_attrs.bzl", "ATTRS") load(":pypi_repo_utils.bzl", "pypi_repo_utils") load(":render_pkg_aliases.bzl", "render_pkg_aliases") @@ -150,6 +152,7 @@ def _pip_repository_impl(rctx): logger = logger, ) selected_requirements = {} + selected_extras = {} selected_srcs = {} options = None repository_platform = host_platform(rctx) @@ -161,7 +164,12 @@ def _pip_repository_impl(rctx): if not requirement: continue options = options or requirement.extra_pip_args + + # The extras are kept in the requirement, so that the `pkg` targets of + # the whl repositories include them when `requirements.bzl` is vendored + # and there is no hub to select the extras. selected_requirements[whl.name] = requirement.requirement_line + selected_extras[whl.name] = parse_requirement(requirement.requirement_line).extras if not requirement.url: continue @@ -216,7 +224,11 @@ def _pip_repository_impl(rctx): # label referencing a package which may not be installed on the current # platform. requirement_cycles = { - normalize_name(name): sorted([normalize_name(d) for d in group if normalize_name(d) in bzl_packages]) + normalize_name(name): sorted([ + group_member(d) + for d in group + if group_member(d).partition("[")[0] in bzl_packages + ]) for name, group in requirement_cycles.items() } @@ -224,6 +236,7 @@ def _pip_repository_impl(rctx): # NOTE: Maintain the order consistent with `buildifier` 'load("@rules_python//python:pip.bzl", "pip_utils")', 'load("@rules_python//python/pip_install:pip_repository.bzl", "whl_config_repo", "whl_library")', + 'load("@rules_python//python/private/pypi:labels.bzl", "requirement_label") # buildifier: disable=bzl-visibility', ] annotations = {} @@ -261,6 +274,7 @@ def _pip_repository_impl(rctx): for pkg in bzl_packages }, extra_hub_aliases = rctx.attr.extra_hub_aliases, + extras = selected_extras, requirement_cycles = requirement_cycles, ) for path, contents in aliases.items(): @@ -272,10 +286,13 @@ def _pip_repository_impl(rctx): "config.bzl", rctx.attr._config_template, substitutions = { + # The available extras of each package for the spoke + # repositories to check if the extras of their dependencies + # are available. "%%PACKAGES%%": render.dict({ - pkg: None + pkg: sorted(selected_extras.get(pkg, [])) for pkg in bzl_packages - }, value_repr = lambda x: "None"), + }, value_repr = render.list), }, ) config_repo_template = repr(rctx.attr.name) diff --git a/python/private/pypi/pkg_aliases.bzl b/python/private/pypi/pkg_aliases.bzl index 227e9bf10f..d64bc7a15f 100644 --- a/python/private/pypi/pkg_aliases.bzl +++ b/python/private/pypi/pkg_aliases.bzl @@ -32,6 +32,7 @@ setting maps to and their precedence, refer to documentation on that page. """ load("@bazel_skylib//lib:selects.bzl", "selects") +load("//python:py_library.bzl", "py_library") load("//python/private:common_labels.bzl", "labels") load("//python/private:text_util.bzl", "render") load( @@ -39,12 +40,12 @@ load( "DATA_LABEL", "DIST_INFO_LABEL", "EXTRACTED_WHEEL_FILES", - "PY_LIBRARY_IMPL_LABEL", "PY_LIBRARY_PUBLIC_LABEL", "PY_SRCS_LABEL", "WHEEL_FILE", "WHEEL_FILE_IMPL_LABEL", "WHEEL_FILE_PUBLIC_LABEL", + "extra_label", ) load(":whl_library_deps_targets.bzl", "whl_library_deps_targets") @@ -75,12 +76,14 @@ _LABEL_NONE = labels.NONE _LABEL_CURRENT_CONFIG = Label("//python/config_settings:current_config") _LABEL_CURRENT_CONFIG_NO_MATCH = Label("//python/config_settings:is_not_matching_current_config") _INCOMPATIBLE = "_no_matching_repository" +_DEFAULT = "//conditions:default" def pkg_aliases( *, name, actual, group_name = None, + group_extras = None, extra_aliases = None, requires_dist = [], extras = [], @@ -98,19 +101,30 @@ def pkg_aliases( the aliases to point to mapping to repositories. The keys are passed to bazel skylib's `selects.with_or`, so they can be tuples as well. group_name: {type}`str` The group name that the pkg belongs to. + group_extras: {type}`list[str] | None` The members of the group in + this package, where an empty string is the package without extras + and the other values are the extras, e.g. `["", "bar"]`. Defaults + to the package without extras if `group_name` is set. group_deps: {type}`list[str]` The packages that are in the given group. Comes as an arg through the hub repository. extra_aliases: {type}`list[str]` The extra aliases to be created. requires_dist: {type}`list[str]` The list of dependencies. Comes from METADATA or a lock file. - extras: {type}`list[str]` The extras for which we should add extra - dependencies when parsing the requires_dist. Comes from METADATA or a lock file. + extras: {type}`list[str]` The requested extras of the package when + `actual` is the name of a single repo. When `actual` is a dict, the + requested extras come from the {obj}`whl_config_setting` keys. include: {type}`list[str]` The subset of packages to include. Comes from `//:config.bzl#packages` **kwargs: extra kwargs to pass to {bzl:obj}`get_config_settings`. """ + if not group_name: + group_extras = [] + elif group_extras == None: + group_extras = [""] + _native = kwargs.pop("native", native) rules = kwargs.pop("rules", struct( + py_library = py_library, whl_library_deps_targets = whl_library_deps_targets, )) select = kwargs.pop("select", selects.with_or) @@ -129,7 +143,6 @@ def pkg_aliases( aliases = {}, # not none metadata_name = name, requires_dist = requires_dist, - extras = extras, include = include, group_deps = group_deps, group_name = group_name, @@ -140,16 +153,11 @@ def pkg_aliases( ) target_names = {} else: - if group_name: - py_library_target = PY_LIBRARY_IMPL_LABEL - whl_target = WHEEL_FILE_IMPL_LABEL - else: - py_library_target = PY_LIBRARY_PUBLIC_LABEL - whl_target = WHEEL_FILE_PUBLIC_LABEL - + # The `pkg` targets are created by `_pkg_targets` below. The whl + # targets do not use the extras, so only the package without extras + # can be a member of the group. target_names = { - PY_LIBRARY_PUBLIC_LABEL: py_library_target, - WHEEL_FILE_PUBLIC_LABEL: whl_target, + WHEEL_FILE_PUBLIC_LABEL: WHEEL_FILE_IMPL_LABEL if "" in group_extras else WHEEL_FILE_PUBLIC_LABEL, } target_names = target_names | { @@ -163,6 +171,7 @@ def pkg_aliases( for x in extra_aliases or [] } + extras_by_setting = _extras_by_setting(actual, extras) actual = multiplatform_whl_aliases(aliases = actual, **kwargs) if type(actual) == type({}) and "//conditions:default" not in actual: _native.alias( @@ -216,16 +225,130 @@ def pkg_aliases( **kwargs ) - if group_name: - _native.alias( - name = PY_LIBRARY_PUBLIC_LABEL, - actual = "//_groups:{}_pkg".format(group_name), - ) + if "" in group_extras: _native.alias( name = WHEEL_FILE_PUBLIC_LABEL, actual = "//_groups:{}_whl".format(group_name), ) + if requires_dist: + if group_name: + _native.alias( + name = PY_LIBRARY_PUBLIC_LABEL, + actual = "//_groups:{}_pkg".format(group_name), + ) + else: + _pkg_targets( + actual = actual, + extras_by_setting = extras_by_setting, + group_name = group_name, + group_extras = group_extras, + native = _native, + rules = rules, + select = select, + ) + +def _extras_by_setting(aliases, extras): + """Return the requested extras for each config setting label.""" + if type(aliases) == type(""): + # A single repo is used for all of the platforms, e.g. in `WORKSPACE`. + return {_DEFAULT: tuple(sorted(extras))} + + return { + "//_config" + setting: alias.extras + for alias in aliases + if type(alias) == "struct" and alias.extras + for setting in get_config_settings( + target_platforms = alias.target_platforms, + python_version = alias.version, + ) + } + +def _pkg_targets(*, actual, extras_by_setting, group_name, group_extras, native, rules, select): + """Create the `pkg`, `[]` and `[]` targets. + + The whl repositories have an `[]` target for every extra that the + package provides and the hub exposes only the extras requested on each + platform. The `pkg` target includes the extras requested on each platform. + + Args: + actual: {type}`str | dict[str, str]` the repo name or the config + setting labels to repo names. + extras_by_setting: {type}`dict[str, tuple[str]]` the config setting + labels to the extras requested on that platform. + group_name: {type}`str | None` the group name that the pkg belongs to. + group_extras: {type}`list[str]` the members of the group in this + package, where an empty string is the package without extras. + native: the native struct. + rules: the rules struct. + select: the select function. + """ + if type(actual) == type(""): + actual = {_DEFAULT: actual} + + def _select(values): + return values[_DEFAULT] if values.keys() == [_DEFAULT] else select(values) + + def _target(repo, name): + return repo if repo == _INCOMPATIBLE else "@{}//:{}".format(repo, name) + + group_label = "//_groups:{}_{}".format(group_name, PY_LIBRARY_PUBLIC_LABEL) + + def _hub_label(extra): + return group_label if extra in group_extras else ":" + extra_label(extra) + + all_extras = sorted({ + extra: None + for extras in list(extras_by_setting.values()) + [group_extras] + for extra in extras + if extra + }) + for extra in [""] + all_extras: + # The platforms that do not request the extra get the package without + # extras. The `pkg` targets of the whl repositories are not used, + # because they may include the requested extras. + targets = _select({ + setting: _target( + repo, + extra_label(extra if extra in extras_by_setting.get(setting, ()) else ""), + ) + for setting, repo in actual.items() + }) + + if extra not in group_extras: + native.alias(name = extra_label(extra), actual = targets) + continue + + # The group library uses the implementation targets of the members. + native.alias( + name = "_" + (extra_label(extra) if extra else PY_LIBRARY_PUBLIC_LABEL), + actual = targets, + visibility = ["//_groups:__subpackages__"], + ) + native.alias(name = extra_label(extra), actual = group_label) + + # The `[]` and `[]` targets have the no match error, so we do not + # need to handle the incompatible platforms here. + targets = { + setting: sorted({ + _hub_label(e): None + for e in extras_by_setting.get(setting, ()) or [""] + }) + for setting in actual + } + unique = {label: None for t in targets.values() for label in t} + if len(unique) == 1: + native.alias(name = PY_LIBRARY_PUBLIC_LABEL, actual = unique.keys()[0]) + elif all([len(t) == 1 for t in targets.values()]): + native.alias( + name = PY_LIBRARY_PUBLIC_LABEL, + actual = _select({setting: t[0] for setting, t in targets.items()}), + ) + else: + # Some platforms request more than one extra, so we need to combine + # the targets. + rules.py_library(name = PY_LIBRARY_PUBLIC_LABEL, deps = _select(targets)) + def multiplatform_whl_aliases( *, aliases = []): diff --git a/python/private/pypi/render_pkg_aliases.bzl b/python/private/pypi/render_pkg_aliases.bzl index f03c33355e..9ba55f3a75 100644 --- a/python/private/pypi/render_pkg_aliases.bzl +++ b/python/private/pypi/render_pkg_aliases.bzl @@ -22,6 +22,7 @@ load( ":generate_group_library_build_bazel.bzl", "generate_group_library_build_bazel", ) # buildifier: disable=bzl-visibility +load(":labels.bzl", "group_member") NO_MATCH_ERROR_MESSAGE_TEMPLATE = """\ No matching wheel for current configuration's Python version. @@ -46,10 +47,11 @@ def _repr_dict(*, value_repr = repr, **kwargs): return {k: value_repr(v) for k, v in kwargs.items() if v} def _repr_config_setting(alias): - if alias.target_platforms: + if alias.target_platforms or alias.extras: return render.call( "whl_config_setting", **_repr_dict( + extras = alias.extras, target_platforms = alias.target_platforms, version = alias.version, ) @@ -93,6 +95,7 @@ def render_pkg_aliases( aliases, requirement_cycles = None, extra_hub_aliases = {}, + extras = {}, exposed_packages = None, **kwargs): """Create alias declarations for each PyPI package. @@ -107,6 +110,8 @@ def render_pkg_aliases( requirement_cycles: any package groups to also add. extra_hub_aliases: The list of extra aliases for each whl to be added in addition to the default ones. + extras: {type}`dict[str, list[str]]` The requested extras for each + whl when the aliases are repo names. exposed_packages: The packages that should be public. When set, the aliases of the other packages are only visible to the wheel repositories. @@ -122,17 +127,23 @@ def render_pkg_aliases( fail("The aliases need to be provided as a dict, got: {}".format(type(aliases))) whl_group_mapping = {} + group_extras = {} if requirement_cycles: + # The members are the packages, e.g. `foo`, or the extras of the + # packages, e.g. `foo[bar]`. requirement_cycles = { - name: [normalize_name(whl_name) for whl_name in whls] + name: [group_member(whl_name) for whl_name in whls] for name, whls in requirement_cycles.items() } - whl_group_mapping = { - whl_name: group_name - for group_name, group_whls in requirement_cycles.items() - for whl_name in group_whls - } + for group_name, members in requirement_cycles.items(): + for member in members: + whl_name, _, extra = member.partition("[") + whl_group_mapping[whl_name] = group_name + group_extras.setdefault(whl_name, []).append(extra.rstrip("]")) + + # The package without extras is the default member. + group_extras = {k: v for k, v in group_extras.items() if v != [""]} public = ["//visibility:public"] if exposed_packages != None: @@ -155,7 +166,9 @@ def render_pkg_aliases( name = name, aliases = pkg_aliases, extra_aliases = extra_hub_aliases.get(name, []), + extras = extras.get(name, []), group_name = whl_group_mapping.get(name), + group_extras = group_extras.get(name), visibility = visibility, **kwargs ).strip() @@ -298,3 +311,22 @@ def _non_versioned_platform(p, *, strict = False): return p else: fail("Expected to always have a platform in the form '{{abi}}_{{os}}_{{arch}}', got: {}".format(p)) + +def available_extras(aliases): + """Return the extras that are available in the hub for each package. + + Args: + aliases: {type}`dict[str, dict[struct, str]]` the packages to the + {obj}`whl_config_setting` instances and the repo names. + + Returns: + {type}`dict[str, list[str]]` the sorted extras for each package. + """ + return { + pkg: sorted({ + extra: None + for setting in settings + for extra in setting.extras or [] + }) + for pkg, settings in aliases.items() + } diff --git a/python/private/pypi/requirements.bzl.tmpl.bzlmod b/python/private/pypi/requirements.bzl.tmpl.bzlmod index ba227aeb2d..b9d362c9bf 100644 --- a/python/private/pypi/requirements.bzl.tmpl.bzlmod +++ b/python/private/pypi/requirements.bzl.tmpl.bzlmod @@ -4,6 +4,7 @@ """ load("@rules_python//python:pip.bzl", "pip_utils") +load("@rules_python//python/private/pypi:labels.bzl", "requirement_label") all_requirements = %%ALL_REQUIREMENTS%% @@ -14,7 +15,16 @@ all_whl_requirements = all_whl_requirements_by_package.values() all_data_requirements = %%ALL_DATA_REQUIREMENTS%% def requirement(name): - return "%%MACRO_TMPL%%".format(pip_utils.normalize_name(name), "pkg") + """Return the label for the package. + + Args: + name: The name of the package with at most one extra, e.g. `foo`, + `foo[]` or `foo[bar]`. + + Returns: + The label of the package. + """ + return requirement_label("%%MACRO_TMPL%%", name) def whl_requirement(name): return "%%MACRO_TMPL%%".format(pip_utils.normalize_name(name), "whl") diff --git a/python/private/pypi/requirements.bzl.tmpl.workspace b/python/private/pypi/requirements.bzl.tmpl.workspace index faf774e7ed..66aa954ac4 100644 --- a/python/private/pypi/requirements.bzl.tmpl.workspace +++ b/python/private/pypi/requirements.bzl.tmpl.workspace @@ -19,7 +19,16 @@ _config = %%CONFIG%% _annotations = %%ANNOTATIONS%% def requirement(name): - return "%%MACRO_TMPL%%".format(pip_utils.normalize_name(name), "pkg") + """Return the label for the package. + + Args: + name: The name of the package with at most one extra, e.g. `foo`, + `foo[]` or `foo[bar]`. + + Returns: + The label of the package. + """ + return requirement_label("%%MACRO_TMPL%%", name) def whl_requirement(name): return "%%MACRO_TMPL%%".format(pip_utils.normalize_name(name), "whl") @@ -47,8 +56,10 @@ def install_deps(**whl_library_kwargs): # Set up the requirement groups all_requirement_groups = %%ALL_REQUIREMENT_GROUPS%% + # The members are the packages, e.g. `foo`, or the extras of the packages, + # e.g. `foo[bar]`. requirement_group_mapping = { - requirement: group_name + requirement.partition("[")[0]: group_name for group_name, group_requirements in all_requirement_groups.items() for requirement in group_requirements } diff --git a/python/private/pypi/unified_hub_repo.bzl b/python/private/pypi/unified_hub_repo.bzl index ddd15c0d86..46318282a1 100644 --- a/python/private/pypi/unified_hub_repo.bzl +++ b/python/private/pypi/unified_hub_repo.bzl @@ -43,9 +43,19 @@ _REQUIREMENTS_BZL_TMPL = '''\ """ load("@rules_python//python:pip.bzl", "pip_utils") +load("@rules_python//python/private/pypi:labels.bzl", "requirement_label") def requirement(name): - return "%%MACRO_TMPL%%".format(pip_utils.normalize_name(name), "pkg") + """Return the label for the package. + + Args: + name: The name of the package with at most one extra, e.g. `foo`, + `foo[]` or `foo[bar]`. + + Returns: + The label of the package. + """ + return requirement_label("%%MACRO_TMPL%%", name) def whl_requirement(name): return "%%MACRO_TMPL%%".format(pip_utils.normalize_name(name), "whl") diff --git a/python/private/pypi/unified_hub_setup.bzl b/python/private/pypi/unified_hub_setup.bzl index b19410fd4b..9cfba035f5 100644 --- a/python/private/pypi/unified_hub_setup.bzl +++ b/python/private/pypi/unified_hub_setup.bzl @@ -7,6 +7,7 @@ load( "EXTRACTED_WHEEL_FILES", "PY_LIBRARY_PUBLIC_LABEL", "WHEEL_FILE_PUBLIC_LABEL", + "extra_label", ) load("@rules_python//python/private/pypi:missing_package.bzl", "missing_package_error") @@ -25,6 +26,9 @@ def define_venv_flag_config_settings(name, hubs): _STANDARD_ALIASES = [ PY_LIBRARY_PUBLIC_LABEL, + # The package without extras, the `[]` targets are passed as the + # extra aliases because they are only in the hubs that request the extras. + extra_label(""), WHEEL_FILE_PUBLIC_LABEL, DATA_LABEL, DIST_INFO_LABEL, diff --git a/python/private/pypi/whl_config_setting.bzl b/python/private/pypi/whl_config_setting.bzl index 1d868b1b65..7c2c595770 100644 --- a/python/private/pypi/whl_config_setting.bzl +++ b/python/private/pypi/whl_config_setting.bzl @@ -14,7 +14,7 @@ "A small function to create an alias for a whl distribution" -def whl_config_setting(*, version = None, target_platforms = None): +def whl_config_setting(*, version = None, target_platforms = None, extras = None): """The bzl_packages value used by by the render_pkg_aliases function. This contains the minimum amount of information required to generate correct @@ -27,6 +27,8 @@ def whl_config_setting(*, version = None, target_platforms = None): is no match found during a select. target_platforms: {type}`list[str] | None` the list of target_platforms for this distribution. + extras: {type}`list[str] | None` the extras of the distribution that + are requested on the target platforms. Returns: a struct with the validated and parsed values. @@ -55,4 +57,5 @@ def whl_config_setting(*, version = None, target_platforms = None): # Make the struct hashable target_platforms = tuple(target_platforms) if target_platforms else None, version = version, + extras = tuple(sorted(extras)) if extras else None, ) diff --git a/python/private/pypi/whl_deps_repo.bzl b/python/private/pypi/whl_deps_repo.bzl index 20891da397..89d0a03e7d 100644 --- a/python/private/pypi/whl_deps_repo.bzl +++ b/python/private/pypi/whl_deps_repo.bzl @@ -27,8 +27,16 @@ For example if your whl depends on `numpy` and your Python package repo is named doc = "Name of the group, if any.", ), "requirement": attr.string( - mandatory = True, - doc = "Python requirement string describing the package to make available, if 'urls' or 'whl_file' is given, then this only needs to include foo[any_extras] as a bare minimum.", + doc = """ +Python requirement string describing the package, e.g. `foo[bar]==1.0`. Only the +extras are used: the `pkg` target includes the dependencies of the requested +extras and the `[]` targets are created for them even if the package does +not provide them. + +The targets for all of the extras that the package provides are always created, +so this is only needed if the extras are not selected by a hub repository, e.g. +when using a vendored `requirements.bzl`. +""", ), } @@ -62,6 +70,7 @@ def _whl_deps_repo_impl(rctx): repo = rctx.attr.repo or ( str(rctx.attr.metadata_file) if rctx.attr.metadata_file else None ), + provides_extra = getattr(metadata, "provides_extra", []), extras = requirement(rctx.attr.requirement).extras, ) rctx.file("BUILD.bazel", build_file_contents) diff --git a/python/private/pypi/whl_file_repo.bzl b/python/private/pypi/whl_file_repo.bzl index 40d79ac10b..0118402d11 100644 --- a/python/private/pypi/whl_file_repo.bzl +++ b/python/private/pypi/whl_file_repo.bzl @@ -36,8 +36,8 @@ def download_whl(rctx, *, logger): auth = get_auth(rctx, urls), ) if not rctx.attr.sha256 and not rctx.attr.integrity: - logger.warn("Please update the requirement line to include the hash:\n{} \\\n --hash=sha256:{}".format( - rctx.attr.requirement, + logger.warn("Please update the requirement line of '{}' to include the hash:\n --hash=sha256:{}".format( + filename, result.sha256, )) if not result.success: @@ -50,7 +50,6 @@ whl_file_repo_attrs = { "index_url": attr.string(doc = "The index URL used to resolve relative wheel URLs."), "integrity": attr.string(doc = "The expected SRI checksum, used when sha256 is unset."), "patches": attr.label_keyed_string_dict(doc = "Patch labels mapped to their strip levels."), - "requirement": attr.string(doc = "The requirement used in download diagnostics."), "sha256": attr.string(doc = "The expected SHA256 checksum."), "urls": attr.string_list(doc = "The wheel download URLs."), "whl_file": attr.label(doc = "A caller-owned wheel to use instead of downloading."), diff --git a/python/private/pypi/whl_library_deps_targets.bzl b/python/private/pypi/whl_library_deps_targets.bzl index e549f52a47..68621e5f00 100644 --- a/python/private/pypi/whl_library_deps_targets.bzl +++ b/python/private/pypi/whl_library_deps_targets.bzl @@ -8,13 +8,14 @@ load( "DATA_LABEL", "DIST_INFO_LABEL", "EXTRACTED_WHEEL_FILES", - "PY_LIBRARY_IMPL_LABEL", "PY_LIBRARY_PUBLIC_LABEL", "PY_SRCS_LABEL", "WHEEL_FILE", - "WHEEL_FILE_IMPL_LABEL", "WHEEL_FILE_PUBLIC_LABEL", + "extra_label", + "group_member", ) +load(":missing_package.bzl", "missing_extra_error") load(":pep508_deps.bzl", "deps") def whl_library_deps_targets( @@ -24,6 +25,7 @@ def whl_library_deps_targets( aliases = None, metadata_name, requires_dist = [], + provides_extra = [], extras = [], include = [], group_deps = [], @@ -35,6 +37,7 @@ def whl_library_deps_targets( rules = struct( py_library = py_library, env_marker_setting = env_marker_setting, + missing_extra_error = missing_extra_error, )): """Create all of the whl_library targets. @@ -48,11 +51,25 @@ def whl_library_deps_targets( group rules which wrap this library and its fellows together. requires_dist: {type}`list[str]` The list of `Requires-Dist` values from the whl `METADATA`. Optional because some packages don't have them. - extras: {type}`list[str]` The list of requested extras. This essentially - includes extra transitive dependencies in the final targets - depending on the wheel `METADATA`. Optional because some packages - don't request them. - include: {type}`list[str]` The list of packages to include. + provides_extra: {type}`list[str]` The list of extras that the package + provides. For each extra the `[]` target is created + that includes the package and the dependencies of that extra. + extras: {type}`list[str]` The list of requested extras. The `pkg` + target includes them, which is how the extras are used when there + is no hub repository to select them, e.g. when using a vendored + `requirements.bzl`. The `[]` targets are also created for + the requested extras that the package does not provide and they + are the same as the package without extras, because an unknown + extra has no dependencies. A warning is printed for them, like + `pip` does. + include: {type}`list[str] | dict[str, list[str] | None]` The list + of packages to include. If it is a dict, then the values are the + extras of each package that are available in the hub and the + dependencies on the extras that are not available will fail the + build with a helpful message. The `[]` targets are also + created for the extras of this package that are available in + the hub, see `extras` for the ones that the package does not + provide. group_name: {type}`str | None` name of the dependency group (if any). dep_template: {type}`str | None` The dep_template to use. tags: {type}`list[str]` The tags set on the targets. @@ -75,27 +92,33 @@ def whl_library_deps_targets( DATA_LABEL: repo_label(DATA_LABEL), } + # The members of the group are the packages, e.g. `foo`, or the extras of + # the packages, e.g. `foo[bar]`. Only the targets of the members are part + # of the group and they do not depend on the other members to avoid cycles. + self_name = normalize_name(metadata_name) + members = {group_member(m): None for m in group_deps} if group_name else {} + is_member = lambda extra: ( + "{}[{}]".format(self_name, extra) if extra else self_name + ) in members + # If this library is a member of a group, its public label aliases need to # point to the group implementation rule not the implementation rules. We # also need to mark the implementation rules as visible to the group # implementation. + group_label = None if group_name and "//:" in dep_template: # This is the legacy behaviour where the group library is outside the hub repo # # It is expected to disappear when we drop WORKSPACE or drop the vendoring of # pip_parse `requirements.bzl` in WORKSPACE. The alternative would be to add # another argument to the macro, but it is already full of arguments. - label_tmpl = dep_template.format( + group_label = dep_template.format( name = "_config", target = normalize_name(group_name) + "_{}", ).replace( "//:", "//_groups:", ) - aliases = aliases | { - PY_LIBRARY_PUBLIC_LABEL: label_tmpl.format(PY_LIBRARY_PUBLIC_LABEL), - WHEEL_FILE_PUBLIC_LABEL: label_tmpl.format(WHEEL_FILE_PUBLIC_LABEL), - } impl_vis = [dep_template.format( name = "_config", target = "__pkg__", @@ -103,25 +126,74 @@ def whl_library_deps_targets( "//:", "//_groups:", )] - - py_library_label = PY_LIBRARY_IMPL_LABEL - whl_file_label = WHEEL_FILE_IMPL_LABEL + elif group_name: + impl_vis = [dep_template.format(name = "", target = "__subpackages__")] else: - py_library_label = PY_LIBRARY_PUBLIC_LABEL - whl_file_label = WHEEL_FILE_PUBLIC_LABEL - if group_name: - impl_vis = [dep_template.format(name = "", target = "__subpackages__")] - else: - impl_vis = visibility + impl_vis = visibility + + def _name(extra, public): + # In the legacy mode the targets of the members are implementation + # targets and the public targets are aliases to the group. + prefix = "_" if group_label and is_member(extra) else "" + return prefix + (extra_label(extra) if extra else public) + + def _visibility(extra): + # In the legacy mode the targets that are not members are public. + return visibility if group_label and not is_member(extra) else impl_vis + + # Create targets for every extra that the package provides, so that the hub + # can select only the extras that are requested on each platform without + # passing the extras to this repository. The extras that are requested, + # either in the hub or by the `extras` arg, but are not provided by the + # package also get targets. They do not add any dependencies and only + # result in a warning, which is how `pip` treats unknown extras. + requested_extras = sorted({normalize_name(e): None for e in extras}) + provided_extras = {normalize_name(e): None for e in provides_extra} + hub_extras = (include.get(self_name) if type(include) == type({}) else None) or [] + unknown_extras = sorted({ + normalize_name(e): None + for e in requested_extras + list(hub_extras) + if normalize_name(e) not in provided_extras + }) + extras_targets = sorted(provided_extras.keys() + unknown_extras) + for extra in unknown_extras: + getattr(rules, "warn", _warn)("WARNING: {} does not provide the extra '{}'".format( + " ".join([metadata_name] + [ + t.partition("=")[2] + for t in tags + if t.startswith("pypi_version=") + ]), + extra, + )) + whl_file_label = _name("", WHEEL_FILE_PUBLIC_LABEL) + + # The `pkg` target includes the requested extras, so the package without + # extras needs a separate target if any are requested. In the legacy mode + # the group library is the package without extras if it is a member. + base_label = extra_label("") + has_base_target = bool(requires_dist and requested_extras and not (group_label and is_member(""))) + + # The targets to create as tuples of the name, the member of the group + # that the target is and the extras to include. + pkg_targets = [(_name("", PY_LIBRARY_PUBLIC_LABEL), "", requested_extras)] + [ + (_name(extra, PY_LIBRARY_PUBLIC_LABEL), extra, [extra]) + for extra in extras_targets + ] + ([(base_label, "", [])] if has_base_target else []) + + aliases = dict(aliases) + if group_label: + for extra in [""] + extras_targets: + if is_member(extra): + aliases[extra_label(extra) if extra else PY_LIBRARY_PUBLIC_LABEL] = group_label.format(PY_LIBRARY_PUBLIC_LABEL) + if is_member(""): + aliases[WHEEL_FILE_PUBLIC_LABEL] = group_label.format(WHEEL_FILE_PUBLIC_LABEL) if not requires_dist: - # If the package is in a group but has no deps, we still need the public labels to - # point at the srcs targets so that the group implementation can use them. We don't - # need any of the extra targets, so just create the aliases. - aliases = aliases | { - py_library_label: repo_label(PY_SRCS_LABEL), - whl_file_label: repo_label(WHEEL_FILE), - } + # If the package is in a group but has no deps, we still need the labels to point at + # the srcs targets so that the group implementation can use them. + aliases[whl_file_label] = repo_label(WHEEL_FILE) + for name, _, _ in pkg_targets: + aliases[name] = repo_label(PY_SRCS_LABEL) for alias, actual in aliases.items(): native.alias( @@ -130,41 +202,78 @@ def whl_library_deps_targets( visibility = visibility, ) + if not has_base_target: + # The same visibility as the `pkg` target. + native.alias( + name = base_label, + actual = ":" + PY_LIBRARY_PUBLIC_LABEL, + visibility = visibility if group_label or not requires_dist else impl_vis, + ) + if not requires_dist: # If there are extras, then they will be visible in requires_dist. return - package_deps = _parse_requires_dist( - name = metadata_name, - requires_dist = requires_dist, - excludes = group_deps, - extras = extras, - include = include, - ) + # The settings for the deps that are included conditionally keyed by the + # dep and the expression. + settings = {} + + # The dependencies on extras that are not available in the hub. + missing_extras = {} + + def _pkg_label(dep): + dep_name, _, extra = dep.partition("[") + if not extra: + return dep_template.format(name = dep_name, target = PY_LIBRARY_PUBLIC_LABEL) + + extra = extra.rstrip("]") + available = include.get(dep_name) if type(include) == type({}) else None + if available != None and extra not in available: + missing_extras[dep] = (dep_name, extra) + return ":_missing_" + dep - _config_settings( - dependencies_with_markers = package_deps.deps_select, - rules = rules, - visibility = ["//visibility:private"], - ) + return dep_template.format(name = dep_name, target = extra_label(extra)) + + whl_label = lambda dep: dep_template.format(name = dep, target = WHEEL_FILE_PUBLIC_LABEL) 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. + # The transitive dependencies are available via the `data` attribute. The extras + # are not used for the whl targets, so only the packages without extras can be + # members of the group for the whl targets. + whl_deps = deps( + name = self_name, + requires_dist = requires_dist, + include = include, + excludes = members if is_member("") else [], + ) native.filegroup( name = whl_file_label, srcs = [repo_label(WHEEL_FILE)], data = _deps( deps = [], - package_deps = package_deps, - tmpl = dep_template.format(name = "{}", target = WHEEL_FILE_PUBLIC_LABEL), + package_deps = whl_deps, + conditions = _conditions(settings, whl_deps), + label = whl_label, ), - visibility = impl_vis, + visibility = _visibility(""), ) - if hasattr(rules, "py_library"): + for name, extra, want_extras in pkg_targets if hasattr(rules, "py_library") else []: + package_deps = deps( + name = self_name, + requires_dist = requires_dist, + include = include, + excludes = members if is_member(extra) else [], + extras = want_extras, + # Without the hub, e.g. with the vendored `requirements.bzl`, the + # `pkg` targets of the dependencies already include the extras + # from their requirement lines, so the dependencies use them + # like before. + keep_extras = "//:" not in dep_template, + ) rules.py_library( - name = py_library_label, + name = name, # We include as srcs to ensure that the (locations :pkg) works as expected. srcs = [repo_label(PY_SRCS_LABEL)], deps = _deps( @@ -173,52 +282,61 @@ def whl_library_deps_targets( # `pyi_srcs`, see `tests/base_rules/py_library`. deps = [repo_label(PY_SRCS_LABEL)], package_deps = package_deps, - tmpl = dep_template.format(name = "{}", target = PY_LIBRARY_PUBLIC_LABEL), + conditions = _conditions(settings, package_deps), + label = _pkg_label, ), # Disable precompilation on this wrapper target to prevent duplicate # pyc generation; the underlying PY_SRCS_LABEL target handles it. precompile = "disabled", tags = tags, - visibility = impl_vis, + visibility = _visibility(extra), ) -def _parse_requires_dist( - *, - name, - requires_dist, - excludes, - include, - extras): - return deps( - name = normalize_name(name), - requires_dist = requires_dist, - excludes = excludes, - include = include, - extras = extras, - ) - -def _config_settings(dependencies_with_markers, rules, **kwargs): - """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. - """ - for dep, expression in dependencies_with_markers.items(): + for (_, expression), name in settings.items(): rules.env_marker_setting( - name = "include_{}".format(dep), + name = name, expression = expression, - **kwargs + visibility = ["//visibility:private"], ) -def _deps(deps, package_deps, tmpl): - deps = [] + deps + [tmpl.format(d) for d in sorted(package_deps.deps)] + for dep, (dep_name, extra) in sorted(missing_extras.items()): + rules.missing_extra_error( + name = "_missing_" + dep, + package_name = dep_name, + extra = extra, + required_by = metadata_name, + visibility = ["//visibility:private"], + ) + +def _warn(msg): + # buildifier: disable=print + print(msg) + +def _conditions(settings, package_deps): + return { + dep: _setting_name(settings, dep, expression) + for dep, expression in package_deps.deps_select.items() + } + +def _setting_name(settings, dep, expression): + """Return a unique name for the setting evaluating the expression for the dep. + + The first expression for a dep is named `include_` and any different + expressions for the same dep get a numeric suffix. + """ + key = (dep, expression) + if key not in settings: + n = len([d for d, _ in settings if d == dep]) + settings[key] = "include_{}".format(dep) + ("_{}".format(n + 1) if n else "") + + return settings[key] + +def _deps(deps, package_deps, conditions, label): + deps = [] + deps + [label(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(conditions[dep]): [label(dep)], "//conditions:default": [], }) diff --git a/python/private/pypi/whl_library_targets.bzl b/python/private/pypi/whl_library_targets.bzl index a1cc727460..7abc0c4ec5 100644 --- a/python/private/pypi/whl_library_targets.bzl +++ b/python/private/pypi/whl_library_targets.bzl @@ -26,6 +26,7 @@ def whl_library_targets( whl_file = None, metadata_name = "", requires_dist = [], + provides_extra = [], extras = [], entry_points = {}, include = [], @@ -55,7 +56,9 @@ def whl_library_targets( group rules which wrap this library and its fellows together. requires_dist: {type}`list[str]` The list of `Requires-Dist` values from the whl `METADATA`. - extras: {type}`list[str]` The list of requested extras. This essentially includes extra transitive dependencies in the final targets depending on the wheel `METADATA`. + provides_extra: {type}`list[str]` The list of extras that the package provides. + extras: {type}`list[str]` The list of requested extras, see + {obj}`whl_library_deps_targets`. entry_points: {type}`list[dict]` A list of parsed entry point definitions. include: {type}`list[str]` The list of packages to include. group_name: {type}`str | None` name of the dependency group (if any). @@ -97,7 +100,8 @@ def whl_library_targets( dep_template = dep_template, # only needed if requires_dist or group_name is present group_deps = group_deps, # only needed if group_name is present group_name = group_name, # must specify group_deps together - extras = extras, # only needed if requires_dist is present + provides_extra = provides_extra, + extras = extras, include = include, # only needed if requires_dist is present repo = None, # set aliases in the same repo aliases = {}, diff --git a/python/private/pypi/whl_metadata.bzl b/python/private/pypi/whl_metadata.bzl index 203caafc58..949813eba9 100644 --- a/python/private/pypi/whl_metadata.bzl +++ b/python/private/pypi/whl_metadata.bzl @@ -77,11 +77,47 @@ def parse_whl_metadata(contents): return struct( name = parsed["name"], - provides_extra = parsed["provides_extra"], + # The old metadata versions do not have `Provides-Extra`, so also use + # the extras that the requirements are using in their markers. + provides_extra = parsed["provides_extra"] + [ + extra + for extra in _extras_in_markers(parsed["requires_dist"]) + if extra not in parsed["provides_extra"] + ], requires_dist = parsed["requires_dist"], version = parsed["version"], ) +def _extras_in_markers(requires_dist): + """Return the extras that are used as `extra == ""` in the markers.""" + extras = {} + for line in requires_dist: + _, _, marker = line.partition(";") + if "extra" not in marker: + continue + + # The odd items are the string literals of the marker. + parts = marker.replace("'", "\"").split("\"") + for i in range(1, len(parts) - 1, 2): + before = parts[i - 1].rstrip() + after = parts[i + 1].lstrip() + if before.endswith("==") and _is_var(before.removesuffix("==").rstrip(), suffix = True): + extras[parts[i]] = None + elif after.startswith("==") and _is_var(after.removeprefix("==").lstrip(), suffix = False): + extras[parts[i]] = None + + return sorted(extras) + +def _is_var(text, *, suffix): + """Tell if the text ends or starts with the `extra` marker variable.""" + if suffix: + rest = text.removesuffix("extra") + boundary = rest[-1:] + else: + rest = text.removeprefix("extra") + boundary = rest[:1] + return rest != text and not (boundary.isalnum() or boundary == "_") + def find_whl_metadata(*, install_dir, logger): """Find the whl METADATA file in the install_dir. diff --git a/tests/integration/whl_library/MODULE.bazel b/tests/integration/whl_library/MODULE.bazel index 9059879187..1cafbb2024 100644 --- a/tests/integration/whl_library/MODULE.bazel +++ b/tests/integration/whl_library/MODULE.bazel @@ -44,7 +44,6 @@ whl_archive( dep_template = DEP_TEMPLATE, filename = "requests-2.34.2-py3-none-any.whl", # https://pypi.org/project/requests/#requests-2.34.2-py3-none-any.whl - requirement = "requests", sha256 = "2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", urls = [ "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", @@ -57,7 +56,6 @@ whl_deps_repo( name = "whl_deps_repo", dep_template = DEP_TEMPLATE, metadata_file = "@whl_archive//:metadata.json", - requirement = "requests", ) wheels = use_extension("//:wheels.bzl", "wheels") diff --git a/tests/integration/whl_library/wheels.bzl b/tests/integration/whl_library/wheels.bzl index b82f0c0479..c690c7f027 100644 --- a/tests/integration/whl_library/wheels.bzl +++ b/tests/integration/whl_library/wheels.bzl @@ -16,7 +16,6 @@ def _wheels_impl(mrctx): common = { "envsubst": ["WHEEL_TEST_ADDRESS"], "filename": _FILENAME, - "requirement": "storage-pkg", "sha256": mrctx.read(Label("//:wheel.sha256")).strip(), "urls": ["http://${WHEEL_TEST_ADDRESS}/" + _FILENAME], } @@ -25,12 +24,10 @@ def _wheels_impl(mrctx): whl_library(name = "nonmatching", whl_patches = _patches("other.whl"), **common) whl_library( name = "provided", - requirement = "storage-pkg", whl_file = Label("//:" + _FILENAME), ) whl_library( name = "provided_patched", - requirement = "storage-pkg", whl_file = Label("//:" + _FILENAME), whl_patches = _patches(_FILENAME), ) diff --git a/tests/pypi/extension/extension_tests.bzl b/tests/pypi/extension/extension_tests.bzl index f1974cf88c..19bb16dee3 100644 --- a/tests/pypi/extension/extension_tests.bzl +++ b/tests/pypi/extension/extension_tests.bzl @@ -17,7 +17,7 @@ load("@rules_testing//lib:test_suite.bzl", "test_suite") load("@rules_testing//lib:truth.bzl", "subjects") load("//python/private/pypi:default_platforms.bzl", "default_platforms") # buildifier: disable=bzl-visibility -load("//python/private/pypi:extension.bzl", "build_config", "parse_modules") # buildifier: disable=bzl-visibility +load("//python/private/pypi:extension.bzl", "build_config", "parse_modules", "unified_hub_args") # buildifier: disable=bzl-visibility load("//python/private/pypi:platform.bzl", _plat = "platform") # buildifier: disable=bzl-visibility load("//python/private/pypi:whl_config_setting.bzl", "whl_config_setting") # buildifier: disable=bzl-visibility load("//tests/support/mocks:mocks.bzl", "mocks") @@ -227,6 +227,54 @@ def _test_simple(env): _tests.append(_test_simple) +def _test_unified_hub_extras(env): + mods = parse_modules( + module_ctx = _pypi_mock_mctx( + _mod( + name = "rules_python", + parse = [ + _parse( + hub_name = "pypi_a", + python_version = "3.15", + simpleapi_skip = ["simple"], + requirements_lock = "requirements_extras.txt", + ), + _parse( + hub_name = "pypi_b", + python_version = "3.15", + simpleapi_skip = ["simple"], + requirements_lock = "requirements.txt", + ), + ], + ), + os_name = "linux", + arch_name = "x86_64", + mock_files = { + "requirements_extras.txt": "simple[foo,bar]==0.0.1 --hash=sha256:deadbeef", + }, + ), + available_interpreters = { + "python_3_15_host": "unit_test_interpreter_target", + }, + minor_mapping = {"3.15": "3.15.19"}, + ) + + # The targets for the extras are only in the hubs that request them, the + # `[]` target is in all of the hubs. + env.expect.that_dict(unified_hub_args(mods)).contains_exactly({ + "default_hub": "pypi_a", + "extra_aliases": { + "simple:[bar]": ["pypi_a"], + "simple:[foo]": ["pypi_a"], + }, + "hubs": ["pypi_a", "pypi_b"], + "name": "pypi", + "packages": {"simple": ["pypi_a", "pypi_b"]}, + "requirements_bzl": False, + }) + +_tests.append(_test_unified_hub_extras) + def _test_pip_parse_pyproject_toml(env): # pip.parse() reads the version from pyproject.toml's requires-python when # python_version is not set explicitly. Verify it works both when the @@ -844,7 +892,6 @@ simple==0.0.1 \ "filename": "simple-0.0.1-py3-none-any.whl", "index_url": test.want_index_url, "integrity": "sha256-3q2+7w==", - "requirement": "simple==0.0.1", "urls": ["file://simple-0.0.1-py3-none-any.whl"], }, }) diff --git a/tests/pypi/generate_group_library_build_bazel/generate_group_library_build_bazel_tests.bzl b/tests/pypi/generate_group_library_build_bazel/generate_group_library_build_bazel_tests.bzl index a91f861a36..2fe22eb487 100644 --- a/tests/pypi/generate_group_library_build_bazel/generate_group_library_build_bazel_tests.bzl +++ b/tests/pypi/generate_group_library_build_bazel/generate_group_library_build_bazel_tests.bzl @@ -95,6 +95,33 @@ py_library( _tests.append(_test_in_hub) +def _test_in_hub_with_extras(env): + actual = generate_group_library_build_bazel( + repo_prefix = "", + groups = {"vbap": ["Pcodedmp", "oletools[Full]"]}, + ) + + # The extras are members only for the py_library targets + env.expect.that_str(actual).contains("""\ +filegroup( + name = "vbap_whl", + srcs = [], + data = ["//pcodedmp:_whl"], + visibility = ["//:__subpackages__"], +)""") + env.expect.that_str(actual).contains("""\ +py_library( + name = "vbap_pkg", + srcs = [], + deps = [ + "//oletools:_[full]", + "//pcodedmp:_pkg", + ], + visibility = ["//:__subpackages__"], +)""") + +_tests.append(_test_in_hub_with_extras) + def generate_group_library_build_bazel_test_suite(name): """Create the test suite. 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 d3a390d9bb..21af3416a9 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 @@ -114,6 +114,7 @@ whl_library_targets( "data_exclude_all", ], dep_template = "@pypi//{name}:{target}", + extras = ["extra"], group_deps = [ "foo", "fox", @@ -162,6 +163,7 @@ package_metadata( group_name = "qux", purl = "foo", group_deps = ["foo", "fox", "qux"], + extras = ["extra"], ) env.expect.that_str(actual.replace("@@", "@")).equals(want) @@ -241,6 +243,39 @@ package_metadata( _tests.append(_test_all_with_loads) +def _test_no_deps_with_config(env): + # The config is loaded without any deps, because it has the extras that + # are requested from the package in the hub. + 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( + dep_template = "@pypi//{name}:{target}", + include = packages, + metadata_name = "foo", + name = "foo.whl", + 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", + requires_dist = [], + config_load = "@pypi//:config.bzl", + ) + env.expect.that_str(actual.replace("@@", "@")).equals(want) + +_tests.append(_test_no_deps_with_config) + def _test_deps_targets(env): want = """\ load("@package_metadata//rules:package_metadata.bzl", "package_metadata") diff --git a/tests/pypi/hub_builder/hub_builder_tests.bzl b/tests/pypi/hub_builder/hub_builder_tests.bzl index dd7cd650b8..f9e2b0a905 100644 --- a/tests/pypi/hub_builder/hub_builder_tests.bzl +++ b/tests/pypi/hub_builder/hub_builder_tests.bzl @@ -181,6 +181,50 @@ def _test_uv_lock_only(env): _tests.append(_test_uv_lock_only) +def _test_uv_lock_extras(env): + builder = hub_builder(env) + builder.pip_parse( + _mock_mctx( + os_name = "osx", + arch_name = "aarch64", + mock_files = { + "uv.lock": """{"package":[{"name":"simple","provides-extras":["async-rest","grpc"],"source":{"registry":"https://pypi.org/simple"},"version":"0.0.1","wheels":[{"hash":"sha256:deadbeef","url":"https://files.pythonhosted.org/packages/simple-0.0.1-py3-none-any.whl"}]}]}""", + }, + ), + _parse( + hub_name = "pypi", + python_version = "3.15", + requirements_lock = None, + uv_lock = "uv.lock", + target_platforms = ["osx_aarch64", "linux_x86_64"], + ), + ) + pypi = builder.build() + + pypi.whl_map().contains_exactly({ + "simple": { + "pypi_315_simple_py3_none_any_deadbeef": [ + whl_config_setting( + version = "3.15", + target_platforms = ["cp315_linux_x86_64", "cp315_osx_aarch64"], + extras = ["async_rest", "grpc"], + ), + ], + }, + }) + pypi.whl_libraries().contains_at_least({ + "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", + "index_url": "https://pypi.org/simple/simple", + "integrity": "sha256-3q2+7w==", + "urls": ["https://files.pythonhosted.org/packages/simple-0.0.1-py3-none-any.whl"], + }, + }) + +_tests.append(_test_uv_lock_extras) + def _test_target_platforms_all(env): builder = hub_builder(env) builder.pip_parse( @@ -377,10 +421,10 @@ _tests.append(_test_simple_multiple_requirements) def _test_simple_extras_vs_no_extras(env): sub_tests = { - ("osx", "aarch64"): "simple[foo]==0.0.1 --hash=sha256:deadbeef", - ("windows", "aarch64"): "simple==0.0.1 --hash=sha256:deadbeef", + ("osx", "aarch64"): ("simple==0.0.1 --hash=sha256:deadbeef", ["foo"]), + ("windows", "aarch64"): ("simple==0.0.1 --hash=sha256:deadbeef", None), } - for (host_os, host_arch), want_requirement in sub_tests.items(): + for (host_os, host_arch), (want_requirement, want_extras) in sub_tests.items(): builder = hub_builder(env) builder.pip_parse( mocks.mctx( @@ -405,7 +449,7 @@ def _test_simple_extras_vs_no_extras(env): pypi.whl_map().contains_exactly({ "simple": { "pypi_315_simple": [ - whl_config_setting(version = "3.15"), + whl_config_setting(version = "3.15", extras = want_extras), ], }, }) @@ -467,43 +511,35 @@ def _test_simple_extras_vs_no_extras_simpleapi(env): pypi.exposed_packages().contains_exactly(["simple"]) pypi.group_map().contains_exactly({}) + + # The same wheel is used on both platforms, so a single repository has the + # extras for all of the platforms and the hub selects the extras per platform. pypi.whl_map().contains_exactly({ "simple": { - "pypi_315_simple_py3_none_any_deadbeef_osx_aarch64": [ + "pypi_315_simple_py3_none_any_deadbeef": [ whl_config_setting( target_platforms = [ - "cp315_osx_aarch64", + "cp315_windows_aarch64", ], version = "3.15", ), - ], - "pypi_315_simple_py3_none_any_deadbeef_windows_aarch64": [ whl_config_setting( target_platforms = [ - "cp315_windows_aarch64", + "cp315_osx_aarch64", ], version = "3.15", + extras = ["foo"], ), ], }, }) pypi.whl_libraries().contains_exactly({ - "pypi_315_simple_py3_none_any_deadbeef_osx_aarch64": { - "config_load": "@pypi//:config.bzl", - "dep_template": "@pypi//{name}:{target}", - "filename": "simple-0.0.1-py3-none-any.whl", - "index_url": "https://example.com/simple/", - "integrity": "sha256-3q2+7w==", - "requirement": "simple[foo]==0.0.1", - "urls": ["/simple-0.0.1-py3-none-any.whl"], - }, - "pypi_315_simple_py3_none_any_deadbeef_windows_aarch64": { + "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", "index_url": "https://example.com/simple/", "integrity": "sha256-3q2+7w==", - "requirement": "simple==0.0.1", "urls": ["/simple-0.0.1-py3-none-any.whl"], }, }) @@ -575,7 +611,6 @@ def _test_simple_sha512_simpleapi(env): "filename": "simple-0.0.1-py3-none-any.whl", "index_url": "https://example.com/simple/", "integrity": "sha512-3q2+7w==", - "requirement": "simple==0.0.1", "urls": ["/simple-0.0.1-py3-none-any.whl"], }, }) @@ -966,7 +1001,6 @@ torch==2.4.1+cpu ; platform_machine == 'x86_64' \ "filename": "torch-2.4.1+cpu-cp312-cp312-linux_x86_64.whl", "index_url": "https://torch.index/torch/", "integrity": "sha256-iADe7wAmAR1QLAwlbMS2fQAjR/Y8OjjNjkXx9EXGE2Q=", - "requirement": "torch==2.4.1+cpu", "urls": ["/whl/cpu/torch-2.4.1%2Bcpu-cp312-cp312-linux_x86_64.whl"], }, "pypi_312_torch_cp312_cp312_manylinux_2_17_aarch64_36109432_linux_aarch64": { @@ -975,7 +1009,6 @@ torch==2.4.1+cpu ; platform_machine == 'x86_64' \ "filename": "torch-2.4.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", "index_url": "https://torch.index/torch/", "integrity": "sha256-NhCUMrEL1xY8mzDOiW88LMobhrl2X5VqFZTw/0MJHio=", - "requirement": "torch==2.4.1", "urls": ["/whl/cpu/torch-2.4.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl"], }, "pypi_312_torch_cp312_cp312_win_amd64_3a570e5c_windows_x86_64": { @@ -984,7 +1017,6 @@ torch==2.4.1+cpu ; platform_machine == 'x86_64' \ "filename": "torch-2.4.1+cpu-cp312-cp312-win_amd64.whl", "index_url": "https://torch.index/torch/", "integrity": "sha256-OlcOXFU0Fc293+Z5IHMns6OAayHGreoU+6d2hNFhnpc=", - "requirement": "torch==2.4.1+cpu", "urls": ["/whl/cpu/torch-2.4.1%2Bcpu-cp312-cp312-win_amd64.whl"], }, "pypi_312_torch_cp312_none_macosx_11_0_arm64_72b484d5_osx_aarch64": { @@ -993,7 +1025,6 @@ torch==2.4.1+cpu ; platform_machine == 'x86_64' \ "filename": "torch-2.4.1-cp312-none-macosx_11_0_arm64.whl", "index_url": "https://torch.index/torch/", "integrity": "sha256-crSE1bbOwac1vz+locSIPQF0hpjF6c/b60/6t8eYfg0=", - "requirement": "torch==2.4.1", "urls": ["/whl/cpu/torch-2.4.1-cp312-none-macosx_11_0_arm64.whl"], }, }) @@ -1136,7 +1167,6 @@ simple==0.0.1 --hash=sha256:deadb00f "filename": "simple-0.0.1-py3-none-any.whl", "index_url": test.expect_index_url, "integrity": "sha256-3q2wDw==", - "requirement": "simple==0.0.1", "urls": [test.expect_url], } if getattr(test, "envsubst", []): @@ -1489,7 +1519,6 @@ git_dep @ git+https://git.server/repo/project@deadbeefdeadbeef "dep_template": "@pypi//{name}:{target}", "filename": "direct_without_sha-0.0.1-py3-none-any.whl", "integrity": "", - "requirement": "direct_without_sha==0.0.1", "urls": ["example-direct.org/direct_without_sha-0.0.1-py3-none-any.whl"], "whl_patches": {"my_patch": "1"}, }, @@ -1513,7 +1542,6 @@ git_dep @ git+https://git.server/repo/project@deadbeefdeadbeef "filename": "plat-pkg-0.0.4-py3-none-linux_x86_64.whl", "index_url": "https://pypi.org/simple", "integrity": "sha256-3q20Tw==", - "requirement": "plat_pkg==0.0.4", "urls": ["example2.org/index/plat_pkg/"], }, "pypi_315_simple_py3_none_any_deadb00f": { @@ -1522,7 +1550,6 @@ git_dep @ git+https://git.server/repo/project@deadbeefdeadbeef "filename": "simple-0.0.1-py3-none-any.whl", "index_url": "https://pypi.org/simple", "integrity": "sha256-3q2wDw==", - "requirement": "simple==0.0.1", "urls": ["example2.org"], }, "pypi_315_some_pkg_py3_none_any_deadbaaf": { @@ -1530,7 +1557,6 @@ git_dep @ git+https://git.server/repo/project@deadbeefdeadbeef "dep_template": "@pypi//{name}:{target}", "filename": "some_pkg-0.0.1-py3-none-any.whl", "integrity": "sha256-3q26rw==", - "requirement": "some_pkg==0.0.1", "urls": ["example-direct.org/some_pkg-0.0.1-py3-none-any.whl"], }, "pypi_315_some_py3_none_any_deadb33f": { @@ -1539,7 +1565,6 @@ git_dep @ git+https://git.server/repo/project@deadbeefdeadbeef "filename": "some-other-pkg-0.0.1-py3-none-any.whl", "index_url": "https://with_index_url", "integrity": "sha256-3q2zPw==", - "requirement": "some_other_pkg==0.0.1", "urls": ["example2.org/index/some_other_pkg/"], }, }) @@ -1569,10 +1594,10 @@ _tests.append(_test_simple_get_index) def _test_optimum_sys_platform_extra(env): sub_tests = { - ("osx", "aarch64"): "optimum[onnxruntime]==1.17.1", - ("linux", "aarch64"): "optimum[onnxruntime-gpu]==1.17.1", + ("osx", "aarch64"): ("optimum==1.17.1", ["onnxruntime"]), + ("linux", "aarch64"): ("optimum==1.17.1", ["onnxruntime_gpu"]), } - for (host_os, host_arch), want_requirement in sub_tests.items(): + for (host_os, host_arch), (want_requirement, want_extras) in sub_tests.items(): builder = hub_builder( env, ) @@ -1600,7 +1625,7 @@ optimum[onnxruntime-gpu]==1.17.1 ; sys_platform == 'linux' pypi.whl_map().contains_exactly({ "optimum": { "pypi_315_optimum": [ - whl_config_setting(version = "3.15"), + whl_config_setting(version = "3.15", extras = want_extras), ], }, }) @@ -1662,38 +1687,36 @@ optimum[onnxruntime-gpu]==1.17.1 ; sys_platform == 'linux' pypi.exposed_packages().contains_exactly(["optimum"]) pypi.group_map().contains_exactly({}) + + # The same distribution is requested with different extras on different + # platforms, so a single repository has all of the extras and the hub + # selects the extras per platform. pypi.whl_map().contains_exactly({ "optimum": { - "pypi_315_optimum_mylinuxx86_64": [ + "pypi_315_optimum": [ whl_config_setting( version = "3.15", target_platforms = [ "cp315_mylinuxx86_64", ], + extras = ["onnxruntime_gpu"], ), - ], - "pypi_315_optimum_myosxaarch64": [ whl_config_setting( version = "3.15", target_platforms = [ "cp315_myosxaarch64", ], + extras = ["onnxruntime"], ), ], }, }) pypi.whl_libraries().contains_exactly({ - "pypi_315_optimum_mylinuxx86_64": { - "config_load": "@pypi//:config.bzl", - "dep_template": "@pypi//{name}:{target}", - "python_interpreter_target": "unit_test_interpreter_target", - "requirement": "optimum[onnxruntime-gpu]==1.17.1", - }, - "pypi_315_optimum_myosxaarch64": { + "pypi_315_optimum": { "config_load": "@pypi//:config.bzl", "dep_template": "@pypi//{name}:{target}", "python_interpreter_target": "unit_test_interpreter_target", - "requirement": "optimum[onnxruntime]==1.17.1", + "requirement": "optimum==1.17.1", }, }) pypi.extra_aliases().contains_exactly({}) @@ -1751,7 +1774,7 @@ optimum[onnxruntime-gpu]==1.17.1 ; sys_platform == 'linux' pypi.whl_map().contains_exactly({ "optimum": { "pypi_315_optimum": [ - whl_config_setting(version = "3.15"), + whl_config_setting(version = "3.15", extras = ["onnxruntime_gpu"]), ], }, }) @@ -1760,7 +1783,7 @@ optimum[onnxruntime-gpu]==1.17.1 ; sys_platform == 'linux' "config_load": "@pypi//:config.bzl", "dep_template": "@pypi//{name}:{target}", "python_interpreter_target": "unit_test_interpreter_target", - "requirement": "optimum[onnxruntime-gpu]==1.17.1", + "requirement": "optimum==1.17.1", }, }) pypi.extra_aliases().contains_exactly({}) @@ -1830,6 +1853,46 @@ Attempting to create a duplicate library pypi_315_foo for foo with different arg _tests.append(_test_err_duplicate_repos) +def _test_groups_with_extras(env): + builder = hub_builder(env) + builder.pip_parse( + _mock_mctx( + os_name = "osx", + arch_name = "aarch64", + mock_files = { + "requirements.txt": """\ +simple==0.0.1 --hash=sha256:deadbeef +other==0.0.1 --hash=sha256:deadbaaf +""", + }, + ), + _parse( + hub_name = "pypi", + python_version = "3.15", + requirements_lock = "requirements.txt", + experimental_requirement_cycles = { + "group": ["Simple[Foo]", "other"], + }, + ), + ) + pypi = builder.build() + + pypi.group_map().contains_exactly({ + "group": ["simple[foo]", "other"], + }) + pypi.whl_libraries().contains_at_least({ + "pypi_315_simple": { + "config_load": "@pypi//:config.bzl", + "dep_template": "@pypi//{name}:{target}", + "group_deps": ["simple[foo]", "other"], + "group_name": "group", + "python_interpreter_target": "unit_test_interpreter_target", + "requirement": "simple==0.0.1 --hash=sha256:deadbeef", + }, + }) + +_tests.append(_test_groups_with_extras) + def hub_builder_test_suite(name): """Create the test suite. diff --git a/tests/pypi/labels/BUILD.bazel b/tests/pypi/labels/BUILD.bazel new file mode 100644 index 0000000000..ed55e66eae --- /dev/null +++ b/tests/pypi/labels/BUILD.bazel @@ -0,0 +1,5 @@ +load(":labels_tests.bzl", "labels_test_suite") + +labels_test_suite( + name = "labels_tests", +) diff --git a/tests/pypi/labels/labels_tests.bzl b/tests/pypi/labels/labels_tests.bzl new file mode 100644 index 0000000000..c344ace51e --- /dev/null +++ b/tests/pypi/labels/labels_tests.bzl @@ -0,0 +1,40 @@ +"" + +load("@rules_testing//lib:test_suite.bzl", "test_suite") +load("//python/private/pypi:labels.bzl", "requirement_label") # buildifier: disable=bzl-visibility + +_tests = [] + +_TMPL = "@@pypi//{}:{}" + +def _test_requirement_label(env): + for requirement, want in { + "Foo.Bar": "@@pypi//foo_bar:pkg", + "foo[ grpc ]": "@@pypi//foo:[grpc]", + "foo[Async-Rest]": "@@pypi//foo:[async_rest]", + "foo[]": "@@pypi//foo:[]", + "foo[grpc]": "@@pypi//foo:[grpc]", + }.items(): + env.expect.where(requirement = requirement).that_str(requirement_label(_TMPL, requirement)).equals(want) + +_tests.append(_test_requirement_label) + +def _test_requirement_label_multiple_extras_fails(env): + errors = [] + requirement_label( + _TMPL, + "google-api-core[grpc,async_rest]", + fail = lambda msg: errors.append(msg), + ) + env.expect.that_collection(errors).has_size(1) + env.expect.that_str(errors[0]).contains("got 'google-api-core[grpc,async_rest]'") + +_tests.append(_test_requirement_label_multiple_extras_fails) + +def labels_test_suite(name): + """Create the test suite. + + Args: + name: the name of the test suite + """ + test_suite(name = name, basic_tests = _tests) diff --git a/tests/pypi/pep508/deps_tests.bzl b/tests/pypi/pep508/deps_tests.bzl index 0d171d8e95..be288fe308 100644 --- a/tests/pypi/pep508/deps_tests.bzl +++ b/tests/pypi/pep508/deps_tests.bzl @@ -140,6 +140,25 @@ def test_self_extras_chain_is_fully_resolved(env): _tests.append(test_self_extras_chain_is_fully_resolved) +def test_self_extras_of_multi_word_package_are_resolved(env): + # The name of the package is normalized, so the self edges have to be + # matched using the normalized names. + got = deps( + "foo-bar", + requires_dist = [ + "baz", + "Foo.Bar[a,b]; extra == 'all'", + "a_dep; extra == 'a'", + "b_dep; extra == 'b'", + ], + extras = ["all"], + ) + + env.expect.that_collection(got.deps).contains_exactly(["a_dep", "b_dep", "baz"]) + env.expect.that_dict(got.deps_select).contains_exactly({}) + +_tests.append(test_self_extras_of_multi_word_package_are_resolved) + def test_self_extras_chain_with_multiple_requested_extras(env): # Two requested extras, and the first round discovers exactly two new ones # ('a' and 'b'), so the count of newly found extras again matches the number @@ -320,6 +339,43 @@ def test_extras_with_hyphens_are_normalized(env): _tests.append(test_extras_with_hyphens_are_normalized) +def test_deps_with_extras(env): + got = deps( + "foo", + requires_dist = [ + "bar[Socks]", + "baz[a,b]; sys_platform == 'linux'", + "qux", + "qux[c]; extra == 'feat'", + ], + extras = ["feat"], + keep_extras = True, + ) + + # The extras of the dependencies are kept so that the targets with the + # extras can be used. + env.expect.that_collection(got.deps).contains_exactly(["bar[socks]", "qux", "qux[c]"]) + env.expect.that_dict(got.deps_select).contains_exactly({ + "baz[a]": "sys_platform == \"linux\"", + "baz[b]": "sys_platform == \"linux\"", + }) + +_tests.append(test_deps_with_extras) + +def test_deps_with_extras_excludes_and_includes(env): + got = deps( + "foo", + requires_dist = ["bar", "bar[socks]", "baz[a]", "baz[b]", "qux[b]"], + # The excludes are dependencies and the includes are packages + excludes = ["Bar", "baz[A]"], + include = ["bar", "baz"], + keep_extras = True, + ) + + env.expect.that_collection(got.deps).contains_exactly(["bar[socks]", "baz[b]"]) + +_tests.append(test_deps_with_extras_excludes_and_includes) + def deps_test_suite(name): # buildifier: disable=function-docstring test_suite( name = name, diff --git a/tests/pypi/pep508/requirement_tests.bzl b/tests/pypi/pep508/requirement_tests.bzl index 2ce45922da..c027209aa1 100644 --- a/tests/pypi/pep508/requirement_tests.bzl +++ b/tests/pypi/pep508/requirement_tests.bzl @@ -14,7 +14,7 @@ """Tests for parsing the requirement specifier.""" load("@rules_testing//lib:test_suite.bzl", "test_suite") -load("//python/private/pypi:pep508_requirement.bzl", "requirement") # buildifier: disable=bzl-visibility +load("//python/private/pypi:pep508_requirement.bzl", "requirement", "strip_extras") # buildifier: disable=bzl-visibility _tests = [] @@ -42,6 +42,19 @@ def _test_requirement_line_parsing(env): _tests.append(_test_requirement_line_parsing) +def _test_strip_extras(env): + for line, want in { + "foo": "foo", + "foo @ https://example.org/foo[1].whl": "foo @ https://example.org/foo[1].whl", + "foo==1.0 ; python_version < '3.12' --hash=sha256:deadbeef": "foo==1.0 ; python_version < '3.12' --hash=sha256:deadbeef", + "foo[bar,baz] @ https://example.org/foo.whl": "foo @ https://example.org/foo.whl", + "foo[bar]": "foo", + "foo[bar]==1.0 --hash=sha256:deadbeef": "foo==1.0 --hash=sha256:deadbeef", + }.items(): + env.expect.where(line = line).that_str(strip_extras(line)).equals(want) + +_tests.append(_test_strip_extras) + def requirement_test_suite(name): # buildifier: disable=function-docstring test_suite( name = name, diff --git a/tests/pypi/pkg_aliases/pkg_aliases_test.bzl b/tests/pypi/pkg_aliases/pkg_aliases_test.bzl index 2d54bd34db..b1ff1bf698 100644 --- a/tests/pypi/pkg_aliases/pkg_aliases_test.bzl +++ b/tests/pypi/pkg_aliases/pkg_aliases_test.bzl @@ -41,7 +41,8 @@ def _test_legacy_aliases(env): # buildifier: disable=unsorted-dict-items want = { "foo": ":pkg", - "pkg": "@repo//:pkg", + "pkg": ":[]", + "[]": "@repo//:[]", "srcs": "@repo//:srcs", "whl_file": "@repo//:whl_file", "whl": "@repo//:whl", @@ -79,8 +80,9 @@ def _test_config_setting_aliases(env): # buildifier: disable=unsorted-dict-items want = { - "pkg": { - "//:my_config_setting": "@bar_baz_repo//:pkg", + "pkg": ":[]", + "[]": { + "//:my_config_setting": "@bar_baz_repo//:[]", "//conditions:default": "_no_matching_repository", }, # This will be printing the current config values and will make sure we @@ -180,10 +182,11 @@ def _test_multiplatform_whl_aliases(env): # buildifier: disable=unsorted-dict-items want = { - "pkg": { - "//:my_config_setting": "@bzlmod_repo//:pkg", - "//_config:is_cp39": "@version_repo//:pkg", - "//_config:is_cp39_linux_x86_64": "@version_platform_repo//:pkg", + "pkg": ":[]", + "[]": { + "//:my_config_setting": "@bzlmod_repo//:[]", + "//_config:is_cp39": "@version_repo//:[]", + "//_config:is_cp39_linux_x86_64": "@version_platform_repo//:[]", "//conditions:default": "_no_matching_repository", }, } @@ -220,7 +223,7 @@ def _test_group_aliases(env): }, { "name": "_pkg", - "actual": "@repo//:pkg", + "actual": "@repo//:[]", "visibility": ["//_groups:__subpackages__"], }, { @@ -240,6 +243,10 @@ def _test_group_aliases(env): "name": "extracted_whl_files", "actual": "@repo//:extracted_whl_files", }, + { + "name": "[]", + "actual": "//_groups:my_group_pkg", + }, { "name": "pkg", "actual": "//_groups:my_group_pkg", @@ -308,7 +315,6 @@ def _test_deps_and_aliases(env): want_deps_targets = { "aliases": {}, "dep_template": "//{name}:{target}", - "extras": [], "group_deps": ["bar", "foo"], "group_name": "my_group", "include": [], @@ -354,6 +360,11 @@ def _test_deps_and_aliases_integration(env): "name": "foo", "actual": ":pkg", }, + { + "name": "[]", + "actual": ":pkg", + "visibility": ["//:__subpackages__"], + }, { "name": "data", "actual": "@repo//:data", @@ -521,6 +532,189 @@ def _test_config_settings_exist_legacy(env): _tests.append(_test_config_settings_exist_legacy) +_LINUX = "//_config:is_cp312_linux_x86_64" +_OSX = "//_config:is_cp312_osx_aarch64" +_WINDOWS = "//_config:is_cp312_windows_x86_64" + +def _extras_actual(extras_by_platform): + return { + whl_config_setting( + version = "3.12", + target_platforms = ["cp312_" + platform], + extras = extras, + ): repo + for platform, (repo, extras) in extras_by_platform.items() + } + +def _test_extras_aliases(env): + got = {} + py_library_calls = [] + pkg_aliases( + name = "foo", + actual = _extras_actual({ + "linux_x86_64": ("repo", ["bar"]), + "osx_aarch64": ("repo", ["baz"]), + "windows_x86_64": ("other_repo", []), + }), + native = struct( + alias = lambda *, name, actual, visibility = None, tags = None: got.update({name: actual}), + ), + rules = struct( + py_library = lambda **kwargs: py_library_calls.append(kwargs), + ), + select = lambda value, no_match_error = None: value, + ) + + # buildifier: disable=unsorted-dict-items + want = { + "foo": ":pkg", + "pkg": { + _LINUX: ":[bar]", + _OSX: ":[baz]", + _WINDOWS: ":[]", + # The `[]` target has the no match error. + "//conditions:default": ":[]", + }, + "whl": { + _LINUX: "@repo//:whl", + _OSX: "@repo//:whl", + _WINDOWS: "@other_repo//:whl", + "//conditions:default": "_no_matching_repository", + }, + "[]": { + _LINUX: "@repo//:[]", + _OSX: "@repo//:[]", + _WINDOWS: "@other_repo//:[]", + "//conditions:default": "_no_matching_repository", + }, + "[bar]": { + _LINUX: "@repo//:[bar]", + _OSX: "@repo//:[]", + _WINDOWS: "@other_repo//:[]", + "//conditions:default": "_no_matching_repository", + }, + "[baz]": { + _LINUX: "@repo//:[]", + _OSX: "@repo//:[baz]", + _WINDOWS: "@other_repo//:[]", + "//conditions:default": "_no_matching_repository", + }, + } + env.expect.that_dict(got).contains_at_least(want) + env.expect.that_collection(py_library_calls).contains_exactly([]) + +_tests.append(_test_extras_aliases) + +def _test_extras_aliases_union(env): + got = {} + py_library_calls = [] + pkg_aliases( + name = "foo", + actual = _extras_actual({ + "linux_x86_64": ("repo", ["a", "b"]), + "osx_aarch64": ("repo", ["c"]), + "windows_x86_64": ("repo", []), + }), + native = struct( + alias = lambda *, name, actual, visibility = None, tags = None: got.update({name: actual}), + ), + rules = struct( + py_library = lambda **kwargs: py_library_calls.append(kwargs), + ), + select = lambda value, no_match_error = None: value, + ) + + # buildifier: disable=unsorted-dict-items + env.expect.that_collection(py_library_calls).contains_exactly([{ + "name": "pkg", + "deps": { + _LINUX: [":[a]", ":[b]"], + _OSX: [":[c]"], + _WINDOWS: [":[]"], + "//conditions:default": [":[]"], + }, + }]) + env.expect.that_collection(got.keys()).not_contains("pkg") + +_tests.append(_test_extras_aliases_union) + +def _test_extras_aliases_group(env): + got = {} + got_visibility = {} + + def _alias(*, name, actual, visibility = None, **_): + got[name] = actual + if visibility: + got_visibility[name] = visibility + + pkg_aliases( + name = "foo", + actual = _extras_actual({ + "linux_x86_64": ("repo", ["bar"]), + "osx_aarch64": ("repo", []), + }), + group_name = "group", + native = struct(alias = _alias), + select = lambda value, no_match_error = None: value, + ) + + # The package without extras is the member of the group by default, the + # `[bar]` extra is not a member of the group. + # buildifier: disable=unsorted-dict-items + env.expect.that_dict(got).contains_at_least({ + "pkg": { + _LINUX: ":[bar]", + _OSX: "//_groups:group_pkg", + "//conditions:default": "//_groups:group_pkg", + }, + "[]": "//_groups:group_pkg", + "_pkg": { + _LINUX: "@repo//:[]", + _OSX: "@repo//:[]", + "//conditions:default": "_no_matching_repository", + }, + "[bar]": { + _LINUX: "@repo//:[bar]", + _OSX: "@repo//:[]", + "//conditions:default": "_no_matching_repository", + }, + }) + env.expect.that_dict(got_visibility).contains_at_least({ + "_pkg": ["//_groups:__subpackages__"], + }) + +_tests.append(_test_extras_aliases_group) + +def _test_extras_aliases_group_with_extras(env): + got = {} + + # This is how `WORKSPACE` uses a single repo for each package. + pkg_aliases( + name = "foo", + actual = "repo", + extras = ["bar"], + group_name = "group", + # Only the `bar` extra is the member of the group. + group_extras = ["bar"], + native = struct( + alias = lambda *, name, actual, visibility = None, tags = None: got.update({name: actual}), + ), + select = lambda value, no_match_error = None: value, + ) + + # buildifier: disable=unsorted-dict-items + env.expect.that_dict(got).contains_at_least({ + "pkg": "//_groups:group_pkg", + "[]": "@repo//:[]", + "[bar]": "//_groups:group_pkg", + "_[bar]": "@repo//:[bar]", + "whl": "@repo//:whl", + }) + env.expect.that_collection(got.keys()).not_contains("_pkg") + env.expect.that_collection(got.keys()).not_contains("_whl") + +_tests.append(_test_extras_aliases_group_with_extras) + def pkg_aliases_test_suite(name): """Create the test suite. diff --git a/tests/pypi/render_pkg_aliases/render_pkg_aliases_test.bzl b/tests/pypi/render_pkg_aliases/render_pkg_aliases_test.bzl index 13bee38ff5..4e67a51de5 100644 --- a/tests/pypi/render_pkg_aliases/render_pkg_aliases_test.bzl +++ b/tests/pypi/render_pkg_aliases/render_pkg_aliases_test.bzl @@ -17,6 +17,7 @@ load("@rules_testing//lib:test_suite.bzl", "test_suite") load( "//python/private/pypi:render_pkg_aliases.bzl", + "available_extras", "get_whl_flag_versions", "render_multiplatform_pkg_aliases", "render_pkg_aliases", @@ -309,6 +310,85 @@ def _test_get_flag_versions_from_alias_target_platforms(env): _tests.append(_test_get_flag_versions_from_alias_target_platforms) +def _test_aliases_with_extras(env): + actual = render_pkg_aliases( + aliases = { + "foo": { + whl_config_setting(version = "3.2", extras = ["b", "a"]): "pypi_32_foo", + }, + }, + ) + + env.expect.that_str(actual["foo/BUILD.bazel"]).contains("""\ +pkg_aliases( + name = "foo", + actual = { + whl_config_setting( + extras = ("a", "b"), + version = "3.2", + ): "pypi_32_foo", + }, +)""") + +_tests.append(_test_aliases_with_extras) + +def _test_available_extras(env): + got = available_extras({ + "bar": { + whl_config_setting(version = "3.2"): "pypi_32_bar", + }, + "foo": { + whl_config_setting(version = "3.2", target_platforms = ["cp32_linux_x86_64"], extras = ["b"]): "pypi_32_foo", + whl_config_setting(version = "3.2", target_platforms = ["cp32_osx_aarch64"], extras = ["a", "b"]): "pypi_32_foo", + }, + }) + + env.expect.that_dict(got).contains_exactly({ + "bar": [], + "foo": ["a", "b"], + }) + +_tests.append(_test_available_extras) + +def _test_aliases_with_extras_for_repo_names(env): + actual = render_pkg_aliases( + aliases = { + "foo": "pypi_foo", + }, + extras = {"foo": ["a"]}, + ) + + env.expect.that_str(actual["foo/BUILD.bazel"]).contains("""\ +pkg_aliases( + name = "foo", + actual = "pypi_foo", + extras = ["a"], +)""") + +_tests.append(_test_aliases_with_extras_for_repo_names) + +def _test_groups_with_extras(env): + actual = render_pkg_aliases( + aliases = { + "bar": {whl_config_setting(version = "3.1"): "pypi_31_bar"}, + "foo": {whl_config_setting(version = "3.1"): "pypi_31_foo"}, + }, + requirement_cycles = { + "group": ["Bar", "foo[Extra]"], + }, + ) + + env.expect.that_str(actual["foo/BUILD.bazel"]).contains("""\ + group_name = "group", + group_extras = ["extra"], +""") + env.expect.that_str(actual["bar/BUILD.bazel"]).contains("""\ + group_name = "group", +""") + env.expect.that_bool("group_extras" in actual["bar/BUILD.bazel"]).equals(False) + +_tests.append(_test_groups_with_extras) + def render_pkg_aliases_test_suite(name): """Create the test suite. diff --git a/tests/pypi/whl_library/BUILD.bazel b/tests/pypi/whl_library/BUILD.bazel index cade0d2b8e..51e894693d 100644 --- a/tests/pypi/whl_library/BUILD.bazel +++ b/tests/pypi/whl_library/BUILD.bazel @@ -6,6 +6,41 @@ py_test( srcs = ["whl_library_extras_test.py"], target_compatible_with = SUPPORTS_BZLMOD, deps = [ + "@whl_library_extras_direct_dep//:[optional]", + ], +) + +py_test( + name = "whl_library_requested_extras_test", + srcs = ["whl_library_extras_test.py"], + main = "whl_library_extras_test.py", + target_compatible_with = SUPPORTS_BZLMOD, + deps = [ + # The `pkg` target includes the extras from the `requirement`. "@whl_library_extras_direct_dep//:pkg", ], ) + +py_test( + name = "whl_library_no_extras_test", + srcs = ["whl_library_no_extras_test.py"], + target_compatible_with = SUPPORTS_BZLMOD, + deps = [ + "@whl_library_extras_direct_dep//:[]", + # The extra that the package does not provide is the same as the + # package without extras. + "@whl_library_extras_direct_dep//:[unknown]", + # The same for the extra that is only requested in the hub config. + "@whl_library_extras_direct_dep//:[nope]", + ], +) + +py_test( + name = "whl_library_transitive_extras_test", + srcs = ["whl_library_transitive_extras_test.py"], + target_compatible_with = SUPPORTS_BZLMOD, + deps = [ + # The METADATA of the consumer requires `pkg[optional]`. + "@whl_library_extras_consumer//:pkg", + ], +) diff --git a/tests/pypi/whl_library/testdata/consumer/BUILD.bazel b/tests/pypi/whl_library/testdata/consumer/BUILD.bazel new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/pypi/whl_library/testdata/consumer/consumer-1.0.dist-info/METADATA b/tests/pypi/whl_library/testdata/consumer/consumer-1.0.dist-info/METADATA new file mode 100644 index 0000000000..9a723c958a --- /dev/null +++ b/tests/pypi/whl_library/testdata/consumer/consumer-1.0.dist-info/METADATA @@ -0,0 +1,3 @@ +Name: consumer +Version: 1.0 +Requires-Dist: pkg[optional] diff --git a/tests/pypi/whl_library/testdata/consumer/consumer-1.0.dist-info/RECORD b/tests/pypi/whl_library/testdata/consumer/consumer-1.0.dist-info/RECORD new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/pypi/whl_library/testdata/consumer/consumer-1.0.dist-info/WHEEL b/tests/pypi/whl_library/testdata/consumer/consumer-1.0.dist-info/WHEEL new file mode 100644 index 0000000000..a64521a1cc --- /dev/null +++ b/tests/pypi/whl_library/testdata/consumer/consumer-1.0.dist-info/WHEEL @@ -0,0 +1 @@ +Wheel-Version: 1.0 diff --git a/tests/pypi/whl_library/testdata/consumer/consumer.py b/tests/pypi/whl_library/testdata/consumer/consumer.py new file mode 100644 index 0000000000..20da50d156 --- /dev/null +++ b/tests/pypi/whl_library/testdata/consumer/consumer.py @@ -0,0 +1,3 @@ +import pkg + +WITH_EXTRAS = pkg.WITH_EXTRAS diff --git a/tests/pypi/whl_library/testdata/packages.bzl b/tests/pypi/whl_library/testdata/packages.bzl index e4a9b0af4c..627c3a84c2 100644 --- a/tests/pypi/whl_library/testdata/packages.bzl +++ b/tests/pypi/whl_library/testdata/packages.bzl @@ -1,6 +1,12 @@ """A list of packages that this logical testdata hub repo contains.""" -packages = [ - "optional_dep", - "pkg", -] +# The values are the extras that are requested in the hub, the `pkg` package +# does not provide the `nope` extra. +packages = { + "consumer": [], + "optional_dep": [], + "pkg": [ + "nope", + "optional", + ], +} diff --git a/tests/pypi/whl_library/whl_library_no_extras_test.py b/tests/pypi/whl_library/whl_library_no_extras_test.py new file mode 100644 index 0000000000..1972498e45 --- /dev/null +++ b/tests/pypi/whl_library/whl_library_no_extras_test.py @@ -0,0 +1,12 @@ +import unittest + + +class NoExtrasTest(unittest.TestCase): + def test_extras_not_propagated(self): + import pkg + + self.assertEqual(pkg.WITH_EXTRAS, False) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/pypi/whl_library/whl_library_transitive_extras_test.py b/tests/pypi/whl_library/whl_library_transitive_extras_test.py new file mode 100644 index 0000000000..9aa7a80f04 --- /dev/null +++ b/tests/pypi/whl_library/whl_library_transitive_extras_test.py @@ -0,0 +1,12 @@ +import unittest + + +class TransitiveExtrasTest(unittest.TestCase): + def test_extras_from_metadata_propagated(self): + import consumer + + self.assertEqual(consumer.WITH_EXTRAS, True) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/pypi/whl_library_deps_targets/whl_library_deps_targets_tests.bzl b/tests/pypi/whl_library_deps_targets/whl_library_deps_targets_tests.bzl index e8659ff642..551ab7c767 100644 --- a/tests/pypi/whl_library_deps_targets/whl_library_deps_targets_tests.bzl +++ b/tests/pypi/whl_library_deps_targets/whl_library_deps_targets_tests.bzl @@ -33,7 +33,6 @@ def _test_whl_library_deps_targets(env): # Overrides for testing repo = None, aliases = None, - extras = [], native = struct( filegroup = lambda **kwargs: filegroup_calls.append(kwargs), alias = lambda **kwargs: None, @@ -102,10 +101,10 @@ def _test_whl_library_deps_targets_no_deps(env): metadata_name = "Foo", dep_template = "@pypi//{name}:{target}", requires_dist = [], + provides_extra = ["A"], group_name = "qux", repo = None, aliases = {}, - extras = [], native = struct( filegroup = lambda **kwargs: filegroup_calls.append(kwargs), alias = lambda **kwargs: alias_calls.append(kwargs), @@ -131,6 +130,16 @@ def _test_whl_library_deps_targets_no_deps(env): "actual": "whl_file", "visibility": ["//visibility:public"], }, + { + "name": "[a]", + "actual": "srcs", + "visibility": ["//visibility:public"], + }, + { + "name": "[]", + "actual": ":pkg", + "visibility": ["//visibility:public"], + }, ]) # buildifier: @unsorted-dict-items env.expect.that_collection(filegroup_calls).contains_exactly([]) @@ -139,6 +148,522 @@ def _test_whl_library_deps_targets_no_deps(env): _tests.append(_test_whl_library_deps_targets_no_deps) +def _test_extras(env): + filegroup_calls = [] + py_library_calls = [] + env_marker_setting_calls = [] + + whl_library_deps_targets( + name = "foo-0-py3-none-any.whl", + metadata_name = "Foo", + dep_template = "@pypi//{name}:{target}", + requires_dist = [ + "bar[socks]", + "grpc; extra == 'grpc'", + "aiohttp; extra == 'async' and python_version < '3.12'", + "uvloop; extra == 'async'", + "foo[grpc]; extra == 'all'", + ], + provides_extra = ["async", "grpc", "all"], + include = ["bar", "grpc", "aiohttp", "uvloop"], + repo = None, + aliases = {}, + native = struct( + filegroup = lambda **kwargs: filegroup_calls.append(kwargs), + alias = lambda **kwargs: None, + ), + rules = struct( + py_library = lambda **kwargs: py_library_calls.append(kwargs), + env_marker_setting = lambda **kwargs: env_marker_setting_calls.append(kwargs), + ), + ) + + # The `pkg` target has no extras because none were requested and there is + # a target for each extra that the package provides. The `whl` target does + # not use the extras. Without the extras available in the hub, the + # dependencies use the targets with the extras directly. + env.expect.that_collection([ + (c["name"], c["deps"]) + for c in py_library_calls + ]).contains_exactly([ + ("pkg", ["srcs", "@pypi//bar:[socks]"]), + ("[all]", ["srcs", "@pypi//bar:[socks]", "@pypi//grpc:pkg"]), + ("[async]", ["srcs", "@pypi//bar:[socks]", "@pypi//uvloop:pkg"] + select({ + ":is_include_aiohttp_true": ["@pypi//aiohttp:pkg"], + "//conditions:default": [], + })), + ("[grpc]", ["srcs", "@pypi//bar:[socks]", "@pypi//grpc:pkg"]), + ]) + env.expect.that_collection([ + (c["name"], c["data"]) + for c in filegroup_calls + ]).contains_exactly([ + ("whl", ["@pypi//bar:whl"]), + ]) + env.expect.that_collection(env_marker_setting_calls).contains_exactly([ + { + "name": "include_aiohttp", + "expression": "python_version < \"3.12\"", + "visibility": ["//visibility:private"], + }, + ]) # buildifier: @unsorted-dict-items + +_tests.append(_test_extras) + +def _test_unknown_extras_in_hub(env): + alias_calls = [] + py_library_calls = [] + warnings = [] + + whl_library_deps_targets( + name = "foo-1.0-py3-none-any.whl", + metadata_name = "Foo", + dep_template = "@pypi//{name}:{target}", + requires_dist = [ + "bar", + "grpc; extra == 'grpc'", + ], + provides_extra = ["grpc", "async"], + # The hub requests the `grpc` extra and the `nope` extra that the + # package does not provide. + include = {"bar": [], "foo": ["grpc", "nope"], "grpc": []}, + tags = ["pypi_name=Foo", "pypi_version=1.0"], + repo = None, + aliases = {}, + native = struct( + filegroup = lambda **kwargs: None, + alias = lambda **kwargs: alias_calls.append(kwargs), + ), + rules = struct( + py_library = lambda **kwargs: py_library_calls.append(kwargs), + env_marker_setting = lambda **kwargs: None, + warn = warnings.append, + ), + ) + + # The extras are not passed to the whl repositories of a hub, so the `pkg` + # target does not include them. The extra that the package does not + # provide is the same as the package without extras and results in a + # warning, just like in `pip`. + env.expect.that_collection([ + (c["name"], c["actual"]) + for c in alias_calls + ]).contains_exactly([ + ("[]", ":pkg"), + ]) + env.expect.that_collection([ + (c["name"], c["deps"]) + for c in py_library_calls + ]).contains_exactly([ + ("pkg", ["srcs", "@pypi//bar:pkg"]), + ("[async]", ["srcs", "@pypi//bar:pkg"]), + ("[grpc]", ["srcs", "@pypi//bar:pkg", "@pypi//grpc:pkg"]), + ("[nope]", ["srcs", "@pypi//bar:pkg"]), + ]) + env.expect.that_collection(warnings).contains_exactly([ + "WARNING: Foo 1.0 does not provide the extra 'nope'", + ]) + +_tests.append(_test_unknown_extras_in_hub) + +def _test_unknown_extras_in_hub_no_deps(env): + alias_calls = [] + warnings = [] + + whl_library_deps_targets( + name = "foo-1.0-py3-none-any.whl", + metadata_name = "foo", + dep_template = "@pypi//{name}:{target}", + requires_dist = [], + include = {"foo": ["nope"]}, + repo = None, + aliases = {}, + native = struct( + filegroup = lambda **kwargs: None, + alias = lambda **kwargs: alias_calls.append(kwargs), + ), + rules = struct( + py_library = lambda **kwargs: None, + env_marker_setting = lambda **kwargs: None, + warn = warnings.append, + ), + ) + + env.expect.that_collection([ + (c["name"], c["actual"]) + for c in alias_calls + ]).contains_exactly([ + ("whl", "whl_file"), + ("pkg", "srcs"), + ("[nope]", "srcs"), + ("[]", ":pkg"), + ]) + env.expect.that_collection(warnings).contains_exactly([ + "WARNING: foo does not provide the extra 'nope'", + ]) + +_tests.append(_test_unknown_extras_in_hub_no_deps) + +def _test_requested_extras(env): + alias_calls = [] + py_library_calls = [] + filegroup_calls = [] + warnings = [] + + whl_library_deps_targets( + name = "foo-0-py3-none-any.whl", + metadata_name = "Foo", + dep_template = "@pip_{name}//:{target}", + requires_dist = [ + "bar", + "grpc; extra == 'grpc'", + "uvloop; extra == 'async'", + ], + provides_extra = ["async", "grpc"], + extras = ["Grpc", "nope"], + repo = None, + aliases = {}, + native = struct( + filegroup = lambda **kwargs: filegroup_calls.append(kwargs), + alias = lambda **kwargs: alias_calls.append(kwargs), + ), + rules = struct( + py_library = lambda **kwargs: py_library_calls.append(kwargs), + env_marker_setting = lambda **kwargs: None, + warn = warnings.append, + ), + ) + env.expect.that_collection(warnings).contains_exactly([ + "WARNING: Foo does not provide the extra 'nope'", + ]) + + # The `pkg` target includes the requested extras, which is needed if there + # is no hub to select the extras, and the `[]` target is the package + # without extras. The requested extra that the package does not provide + # does not have any dependencies, just like in `pip`. + env.expect.that_collection(alias_calls).contains_exactly([]) + env.expect.that_collection([ + (c["name"], c["deps"]) + for c in py_library_calls + ]).contains_exactly([ + ("pkg", ["srcs", "@pip_bar//:pkg", "@pip_grpc//:pkg"]), + ("[]", ["srcs", "@pip_bar//:pkg"]), + ("[async]", ["srcs", "@pip_bar//:pkg", "@pip_uvloop//:pkg"]), + ("[grpc]", ["srcs", "@pip_bar//:pkg", "@pip_grpc//:pkg"]), + ("[nope]", ["srcs", "@pip_bar//:pkg"]), + ]) + env.expect.that_collection([ + (c["name"], c["data"]) + for c in filegroup_calls + ]).contains_exactly([ + ("whl", ["@pip_bar//:whl"]), + ]) + +_tests.append(_test_requested_extras) + +def _test_requested_extras_no_deps(env): + alias_calls = [] + py_library_calls = [] + + whl_library_deps_targets( + name = "foo-0-py3-none-any.whl", + metadata_name = "Foo", + dep_template = "@pypi//{name}:{target}", + requires_dist = [], + extras = ["nope"], + repo = None, + aliases = {}, + native = struct( + filegroup = lambda **kwargs: None, + alias = lambda **kwargs: alias_calls.append(kwargs), + ), + rules = struct( + py_library = lambda **kwargs: py_library_calls.append(kwargs), + env_marker_setting = lambda **kwargs: None, + warn = lambda _: None, + ), + ) + + env.expect.that_collection([ + (c["name"], c["actual"]) + for c in alias_calls + ]).contains_exactly([ + ("whl", "whl_file"), + ("pkg", "srcs"), + ("[nope]", "srcs"), + ("[]", ":pkg"), + ]) + env.expect.that_collection(py_library_calls).contains_exactly([]) + +_tests.append(_test_requested_extras_no_deps) + +def _test_requested_extras_in_group_legacy(env): + alias_calls = [] + py_library_calls = [] + + whl_library_deps_targets( + name = "foo-0-py3-none-any.whl", + metadata_name = "foo", + dep_template = "@pip_{name}//:{target}", + requires_dist = ["qux", "bar; extra == 'a'", "baz; extra == 'a'"], + provides_extra = ["a"], + extras = ["a"], + group_name = "group", + group_deps = ["foo", "bar"], + repo = None, + aliases = {}, + native = struct( + filegroup = lambda **kwargs: None, + alias = lambda **kwargs: alias_calls.append(kwargs), + ), + rules = struct( + py_library = lambda **kwargs: py_library_calls.append(kwargs), + env_marker_setting = lambda **kwargs: None, + ), + ) + + # The implementation target of the member includes the requested extras + # and the package without extras is the group library. + env.expect.that_collection([ + (c["name"], c["actual"], c["visibility"]) + for c in alias_calls + ]).contains_exactly([ + ("pkg", "@pip__config//_groups:group_pkg", ["//visibility:public"]), + ("whl", "@pip__config//_groups:group_whl", ["//visibility:public"]), + ("[]", ":pkg", ["//visibility:public"]), + ]) + env.expect.that_collection([ + (c["name"], c["deps"], c["visibility"]) + for c in py_library_calls + ]).contains_exactly([ + ("_pkg", ["srcs", "@pip_baz//:pkg", "@pip_qux//:pkg"], ["@pip__config//_groups:__pkg__"]), + ("[a]", ["srcs", "@pip_bar//:pkg", "@pip_baz//:pkg", "@pip_qux//:pkg"], ["//visibility:public"]), + ]) + +_tests.append(_test_requested_extras_in_group_legacy) + +def _test_extras_in_group(env): + py_library_calls = [] + filegroup_calls = [] + + whl_library_deps_targets( + name = "foo-0-py3-none-any.whl", + metadata_name = "foo", + dep_template = "@pypi//{name}:{target}", + requires_dist = ["baz", "bar; extra == 'a'", "qux; extra == 'a'"], + provides_extra = ["a"], + group_name = "group", + # Only the `a` extra is in a cycle with `qux`. + group_deps = ["Foo[A]", "qux"], + repo = None, + aliases = {}, + native = struct( + filegroup = lambda **kwargs: filegroup_calls.append(kwargs), + alias = lambda **kwargs: None, + ), + rules = struct( + py_library = lambda **kwargs: py_library_calls.append(kwargs), + env_marker_setting = lambda **kwargs: None, + ), + ) + + # Only the member targets exclude the other members and the targets are + # visible to the hub that creates the group library. + env.expect.that_collection([ + (c["name"], c["deps"], c["visibility"]) + for c in py_library_calls + ]).contains_exactly([ + ("pkg", ["srcs", "@pypi//baz:pkg"], ["@pypi//:__subpackages__"]), + ("[a]", ["srcs", "@pypi//bar:pkg", "@pypi//baz:pkg"], ["@pypi//:__subpackages__"]), + ]) + env.expect.that_collection([ + (c["name"], c["data"]) + for c in filegroup_calls + ]).contains_exactly([ + ("whl", ["@pypi//baz:whl"]), + ]) + +_tests.append(_test_extras_in_group) + +def _test_extras_in_group_legacy(env): + alias_calls = [] + py_library_calls = [] + filegroup_calls = [] + + whl_library_deps_targets( + name = "foo-0-py3-none-any.whl", + metadata_name = "foo", + dep_template = "@pip_{name}//:{target}", + requires_dist = ["qux", "bar; extra == 'a'"], + provides_extra = ["a", "b"], + group_name = "group", + group_deps = ["foo", "foo[a]", "qux"], + repo = None, + aliases = {}, + native = struct( + filegroup = lambda **kwargs: filegroup_calls.append(kwargs), + alias = lambda **kwargs: alias_calls.append(kwargs), + ), + rules = struct( + py_library = lambda **kwargs: py_library_calls.append(kwargs), + env_marker_setting = lambda **kwargs: None, + ), + ) + + # The member targets are implementation targets and the public targets + # point to the group library in the config repo. + env.expect.that_collection([ + (c["name"], c["actual"]) + for c in alias_calls + ]).contains_exactly([ + ("pkg", "@pip__config//_groups:group_pkg"), + ("[a]", "@pip__config//_groups:group_pkg"), + ("whl", "@pip__config//_groups:group_whl"), + ("[]", ":pkg"), + ]) + env.expect.that_collection([ + (c["name"], c["deps"], c["visibility"]) + for c in py_library_calls + ]).contains_exactly([ + ("_pkg", ["srcs"], ["@pip__config//_groups:__pkg__"]), + ("_[a]", ["srcs", "@pip_bar//:pkg"], ["@pip__config//_groups:__pkg__"]), + ("[b]", ["srcs", "@pip_qux//:pkg"], ["//visibility:public"]), + ]) + env.expect.that_collection([ + (c["name"], c["data"], c["visibility"]) + for c in filegroup_calls + ]).contains_exactly([ + ("_whl", [], ["@pip__config//_groups:__pkg__"]), + ]) + +_tests.append(_test_extras_in_group_legacy) + +def _test_deps_with_extras(env): + filegroup_calls = [] + py_library_calls = [] + env_marker_setting_calls = [] + missing_calls = [] + + whl_library_deps_targets( + name = "foo-0-py3-none-any.whl", + metadata_name = "foo", + dep_template = "@pypi//{name}:{target}", + requires_dist = [ + "bar[socks]", + "baz[a,b]; sys_platform == 'linux'", + "baz; sys_platform == 'darwin'", + "qux[missing]", + ], + # The values are the extras that are available in the hub + include = { + "bar": ["socks"], + "baz": ["a", "b"], + "qux": [], + }, + repo = None, + aliases = {}, + native = struct( + filegroup = lambda **kwargs: filegroup_calls.append(kwargs), + alias = lambda **kwargs: None, + ), + rules = struct( + py_library = lambda **kwargs: py_library_calls.append(kwargs), + env_marker_setting = lambda **kwargs: env_marker_setting_calls.append(kwargs), + missing_extra_error = lambda **kwargs: missing_calls.append(kwargs), + ), + ) + + # The dependencies use the targets with the extras, the missing extras use + # a target that fails the build with a helpful message. + env.expect.that_collection([ + (c["name"], c["deps"]) + for c in py_library_calls + ]).contains_exactly([ + ("pkg", ["srcs", "@pypi//bar:[socks]", ":_missing_qux[missing]"] + select({ + ":is_include_baz_2_true": ["@pypi//baz:pkg"], + "//conditions:default": [], + }) + select({ + ":is_include_baz[a]_true": ["@pypi//baz:[a]"], + "//conditions:default": [], + }) + select({ + ":is_include_baz[b]_true": ["@pypi//baz:[b]"], + "//conditions:default": [], + })), + ]) + env.expect.that_collection(missing_calls).contains_exactly([ + { + "name": "_missing_qux[missing]", + "package_name": "qux", + "extra": "missing", + "required_by": "foo", + "visibility": ["//visibility:private"], + }, + ]) # buildifier: @unsorted-dict-items + + # The whl targets do not use the extras. + env.expect.that_collection([ + (c["name"], c["data"]) + for c in filegroup_calls + ]).contains_exactly([ + ("whl", ["@pypi//bar:whl", "@pypi//qux:whl"] + select({ + ":is_include_baz_true": ["@pypi//baz:whl"], + "//conditions:default": [], + })), + ]) + env.expect.that_collection([ + (c["name"], c["expression"]) + for c in env_marker_setting_calls + ]).contains_exactly([ + ("include_baz", "(sys_platform == \"darwin\") or (sys_platform == \"linux\")"), + ("include_baz_2", "sys_platform == \"darwin\""), + ("include_baz[a]", "sys_platform == \"linux\""), + ("include_baz[b]", "sys_platform == \"linux\""), + ]) + +_tests.append(_test_deps_with_extras) + +def _test_deps_with_extras_legacy(env): + py_library_calls = [] + missing_calls = [] + + whl_library_deps_targets( + name = "foo-0-py3-none-any.whl", + metadata_name = "foo", + # Without the hub, e.g. with the vendored `requirements.bzl`. + dep_template = "@pip_{name}//:{target}", + requires_dist = [ + "bar[socks]", + "baz[a]; sys_platform == 'linux'", + "qux[missing]", + ], + repo = None, + aliases = {}, + native = struct( + alias = lambda **kwargs: None, + ), + rules = struct( + py_library = lambda **kwargs: py_library_calls.append(kwargs), + env_marker_setting = lambda **kwargs: None, + missing_extra_error = lambda **kwargs: missing_calls.append(kwargs), + ), + ) + + # The dependencies use the `pkg` targets, which include the extras from + # the requirement lines of the dependencies, so the extras that are not + # provided or not requested do not result in missing targets. + env.expect.that_collection([ + (c["name"], c["deps"]) + for c in py_library_calls + ]).contains_exactly([ + ("pkg", ["srcs", "@pip_bar//:pkg", "@pip_qux//:pkg"] + select({ + ":is_include_baz_true": ["@pip_baz//:pkg"], + "//conditions:default": [], + })), + ]) + env.expect.that_collection(missing_calls).contains_exactly([]) + +_tests.append(_test_deps_with_extras_legacy) + def whl_library_deps_targets_test_suite(name): """create the test suite. diff --git a/tests/pypi/whl_metadata/whl_metadata_tests.bzl b/tests/pypi/whl_metadata/whl_metadata_tests.bzl index 8aca204146..080e346ef9 100644 --- a/tests/pypi/whl_metadata/whl_metadata_tests.bzl +++ b/tests/pypi/whl_metadata/whl_metadata_tests.bzl @@ -141,6 +141,47 @@ Requires-Dist: this will be ignored _tests.append(_test_parse_metadata_all) +def _test_parse_metadata_without_provides_extra(env): + got = _parse_whl_metadata( + env, + contents = """\ +Name: foo +Version: 0.0.1 +Requires-Dist: plain +Requires-Dist: no-extra; python_version < "3.11" +Requires-Dist: bar; extra == "all" +Requires-Dist: baz>=1; python_version < "3.11" and extra == 'toml' +Requires-Dist: qux; (os_name == "nt" or "Rev_Ersed"==extra) and extra != "not-this" +Requires-Dist: other; some_extra == "not-a-var" or "nope" == extra_var +Requires-Dist: again; extra == "all" +""", + ) + + # The extras are from the markers, because there is no `Provides-Extra`. + got.provides_extra().contains_exactly([ + "Rev_Ersed", + "all", + "toml", + ]).in_order() + +_tests.append(_test_parse_metadata_without_provides_extra) + +def _test_parse_metadata_provides_extra_and_markers(env): + got = _parse_whl_metadata( + env, + contents = """\ +Name: foo +Version: 0.0.1 +Requires-Dist: bar; extra == "all" +Requires-Dist: baz; extra == "undeclared" +Requires-Dist: qux; extra == "all" +Provides-Extra: all +""", + ) + got.provides_extra().contains_exactly(["all", "undeclared"]).in_order() + +_tests.append(_test_parse_metadata_provides_extra_and_markers) + def _test_parse_metadata_multiline_license(env): got = _parse_whl_metadata( env,