feat(pypi): add pip.configure to select the exposed packages of a hub (#4395)
Before this change a hub exposed all of the packages from its
requirements files or `uv.lock` file, including the transitive
dependencies, and there was no way to limit them to the direct
dependencies of a project.
This adds the `pip.configure` tag class, which limits the packages that
a hub exposes to the ones listed in the dependency groups of a
`pyproject.toml` file, i.e. the `[project] dependencies`,
`[project.optional-dependencies]` and PEP 735 `[dependency-groups]`
tables:
```starlark
pip.parse(
hub_name = "pypi_hub",
pyproject_toml = "//:pyproject.toml",
requirements_lock = "//:requirements_lock.txt",
)
pip.configure(
hub_name = "pypi_hub",
dependency_groups = ["default", "group:dev"],
)
```
The other packages of the hub are still used by the wheels that need
them, but their aliases are only visible to the wheel repositories, and
they are left out of the `all_requirements` lists and the unified
`@pypi` hub. The transitive dependencies of selected groups are not
supported, the only exception is `["*", "transitive"]`, which exposes
all of the packages of the hub. Only the root module and the module that
created the hub can configure it, and the root module wins if both do.
The hubs that are not configured are unchanged.
The `pip.configure` tags work like a builder: the tags of a hub are
applied in order and combined, and a `pyproject_toml` set on one tag is
used by the later tags of the same module and hub. The
`dependency_groups` default to `[]`, so a tag only needs a
`pyproject.toml` when it selects dependency groups, which leaves room
for the tags that configure other parts of the hub.
This is only supported with bzlmod; the `WORKSPACE` code is unchanged.
Work towards #3413
---------
Co-authored-by: Richard Levasseur <richardlev@gmail.com>
diff --git a/docs/pypi/download.md b/docs/pypi/download.md
index cc8b789..ad8b40e 100644
--- a/docs/pypi/download.md
+++ b/docs/pypi/download.md
@@ -176,6 +176,76 @@
`python` interpreter), you can force it to re-execute by running `bazel sync --only [pip_parse
name]`.
+(pip-configure)=
+## Configuring the Exposed Packages (pip.configure)
+
+By default a hub exposes all of the packages from its requirements files or
+`uv.lock` file, including the transitive dependencies. A `pip.configure` tag
+can limit the hub to the packages listed in a `pyproject.toml` file: the
+`[project] dependencies`, `[project.optional-dependencies]` and PEP 735
+`[dependency-groups]` tables.
+
+```toml
+[project]
+requires-python = "==3.13.0"
+dependencies = ["numpy"]
+
+[dependency-groups]
+dev = ["pytest"]
+```
+
+```starlark
+pip.parse(
+ hub_name = "pypi_hub",
+ pyproject_toml = "//:pyproject.toml",
+ requirements_lock = "//:requirements_lock.txt",
+)
+
+pip.configure(
+ hub_name = "pypi_hub",
+ dependency_groups = ["default", "group:dev"],
+)
+```
+
+Here `@pypi_hub//numpy` and `@pypi_hub//pytest` can be used, but the
+dependencies of `numpy` are only used through `@pypi_hub//numpy`. The
+`all_requirements` lists in the hub's `requirements.bzl` and the
+[Unified @pypi Hub](unified-pypi-hub) only contain the exposed packages.
+
+Use `["*"]` to select every group, or `["*", "transitive"]` to expose all of
+the packages of the hub, including the transitive dependencies, which is the
+same as not configuring the hub. Selecting the transitive dependencies of only
+some of the groups is not supported. A tag without
+{attr}`pip.configure.dependency_groups` does not limit the hub and does not
+need a `pyproject.toml`.
+
+The `pip.configure` tags work like a builder: they are applied in order and
+the tags for the same hub are combined. A `pyproject_toml` set on a tag is used
+by the later tags of the same module and hub, so it only needs to be set once:
+
+```starlark
+pip.configure(
+ hub_name = "pypi_hub",
+ pyproject_toml = "//tools:pyproject.toml",
+ dependency_groups = ["default"],
+)
+
+# Uses //tools:pyproject.toml
+pip.configure(
+ hub_name = "pypi_hub",
+ dependency_groups = ["group:dev"],
+)
+```
+
+Only the root module and the module that created the hub can configure it; if
+both do, the root module wins. A self reference such as `my-project[test]` in
+the `pyproject.toml` selects the optional dependencies of the project. The
+packages that are not part of the hub are ignored, so a single `pyproject.toml`
+can list tools that are missing from the lock file.
+
+:::{versionadded} VERSION_NEXT_FEATURE
+:::
+
(per-os-arch-requirements)=
## Requirements for a specific OS/Architecture
diff --git a/news/4395.added.md b/news/4395.added.md
new file mode 100644
index 0000000..3e633cc
--- /dev/null
+++ b/news/4395.added.md
@@ -0,0 +1,3 @@
+(pypi) Added {obj}`pip.configure` to limit the packages that a hub exposes to
+the ones listed in the dependency groups of a `pyproject.toml` file
+([#3413](https://github.com/bazel-contrib/rules_python/issues/3413)).
diff --git a/python/private/pypi/BUILD.bazel b/python/private/pypi/BUILD.bazel
index 1754c17..e867cd9 100644
--- a/python/private/pypi/BUILD.bazel
+++ b/python/private/pypi/BUILD.bazel
@@ -139,6 +139,7 @@
deps = [
":default_platforms",
":hub_builder",
+ ":hub_exposure",
":hub_repository",
":parse_whl_name",
":pep508_env",
@@ -637,6 +638,25 @@
)
bzl_library(
+ name = "dependency_groups",
+ srcs = ["dependency_groups.bzl"],
+ deps = [
+ ":pep508_requirement",
+ "//python/private:normalize_name",
+ "@bazel_skylib//lib:types",
+ ],
+)
+
+bzl_library(
+ name = "hub_exposure",
+ srcs = ["hub_exposure.bzl"],
+ deps = [
+ ":dependency_groups",
+ "//python/private:pyproject_utils",
+ ],
+)
+
+bzl_library(
name = "argparse",
srcs = ["argparse.bzl"],
)
diff --git a/python/private/pypi/dependency_groups.bzl b/python/private/pypi/dependency_groups.bzl
new file mode 100644
index 0000000..13b164c
--- /dev/null
+++ b/python/private/pypi/dependency_groups.bzl
@@ -0,0 +1,179 @@
+"""Select PyPI packages using pyproject.toml dependency groups."""
+
+load("@bazel_skylib//lib:types.bzl", "types")
+load("//python/private:normalize_name.bzl", "normalize_name")
+load(":pep508_requirement.bzl", "requirement")
+
+def select_dependency_groups(pyproject, specs, _fail = fail):
+ """Select the packages named by the given dependency group specifiers.
+
+ Supported specifiers are:
+
+ * `"default"`: the `[project] dependencies`.
+ * `"optional:<name>"`: a `[project.optional-dependencies]` entry.
+ * `"group:<name>"`: a PEP 735 `[dependency-groups]` entry.
+ * `"optional:*"` and `"group:*"`: all entries of the table.
+ * `"*"`: all of the above.
+ * `"<name>"`: a dependency group, or an optional dependency group if
+ there is no dependency group with that name.
+ * `"transitive"`: only supported together with `"*"` and selects all
+ of the packages, including the transitive dependencies.
+
+ Args:
+ pyproject: {type}`struct` returned by `read_pyproject`.
+ specs: {type}`list[str]` the specifiers.
+ _fail: {type}`callable` the failure function, mainly for testing.
+
+ Returns:
+ {type}`struct | None` with the attributes:
+ * `packages`: {type}`list[str]` the sorted normalized package names.
+ * `all`: {type}`bool` whether all of the packages including the
+ transitive dependencies should be selected, i.e. `"*"` and
+ `"transitive"` were given.
+ Returns `None` on failure.
+ """
+ groups = {"default": pyproject.dependencies}
+ for name, reqs in pyproject.optional_dependencies.items():
+ groups["optional:" + normalize_name(name)] = reqs
+ expanded = _expand_dependency_groups(pyproject.dependency_groups, _fail)
+ if expanded == None:
+ return None
+ for name, reqs in expanded.items():
+ groups["group:" + name] = reqs
+
+ if "transitive" in specs:
+ if "*" not in specs:
+ _fail("The 'transitive' dependency group specifier is only supported together with '*', which selects all of the packages, got: {}".format(
+ specs,
+ ))
+ return None
+ return struct(
+ # list[str]: sorted normalized package names selected by `specs`.
+ packages = [],
+ # bool: True when all hub packages are selected.
+ all = True,
+ )
+
+ selected = {}
+ for spec in specs:
+ keys = _match(spec, groups)
+
+ # A wildcard matches nothing when its table is empty or missing.
+ if not keys and spec not in ("*", "optional:*", "group:*"):
+ _fail("Unknown dependency group '{}'. Available groups: {}".format(
+ spec,
+ ", ".join(sorted(groups)),
+ ))
+ return None
+ for key in keys:
+ selected[key] = None
+
+ # A self reference like `my-project[test]` selects the optional
+ # dependencies, including nested composite extras.
+ project = normalize_name(pyproject.name or "")
+ packages = {}
+ queue = list(selected)
+ for _ in range(len(groups)):
+ if not queue:
+ break
+ for req in groups[queue.pop(0)]:
+ req = requirement(req)
+ if req.name_ != project:
+ packages[req.name_] = None
+ continue
+ for extra in req.extras:
+ opt_key = "optional:" + extra
+ if opt_key in groups and opt_key not in selected:
+ selected[opt_key] = None
+ queue.append(opt_key)
+
+ return struct(
+ # list[str]: sorted normalized package names selected by `specs`.
+ packages = sorted(packages),
+ # bool: True when all packages including transitive ones are selected.
+ all = False,
+ )
+
+def _match(spec, groups):
+ """Match a dependency group specifier against normalized group keys.
+
+ Args:
+ spec: {type}`str` the dependency group specifier.
+ groups: {type}`dict[str, list[str]]` available groups keyed by
+ prefixed group name.
+
+ Returns:
+ {type}`list[str]` matching keys in `groups`.
+ """
+ if spec == "*":
+ return groups.keys()
+ if spec in ("optional:*", "group:*"):
+ prefix = spec[:-1]
+ return [key for key in groups if key.startswith(prefix)]
+
+ kind, _, name = spec.rpartition(":")
+ name = normalize_name(name)
+ if kind:
+ candidates = [kind + ":" + name]
+ elif name == "default":
+ candidates = ["default"]
+ else:
+ candidates = ["group:" + name, "optional:" + name]
+
+ for key in candidates:
+ if key in groups:
+ return [key]
+ return []
+
+def _expand_dependency_groups(dependency_groups, _fail):
+ """Expand the PEP 735 `include-group` entries.
+
+ Args:
+ dependency_groups: {type}`dict[str, list[str | dict[str, str]]]` the
+ `[dependency-groups]` table.
+ _fail: {type}`callable` the failure function.
+
+ Returns:
+ {type}`dict[str, list[str]] | None` normalized group names mapped to
+ their requirement strings, or `None` on failure.
+ """
+ groups = {
+ normalize_name(name): items
+ for name, items in dependency_groups.items()
+ }
+
+ # Each round expands at least one group unless there is a cycle.
+ expanded = {}
+ for _ in range(len(groups)):
+ for name, items in groups.items():
+ if name in expanded:
+ continue
+
+ reqs = []
+ for item in items:
+ if types.is_string(item):
+ reqs.append(item)
+ continue
+
+ include = normalize_name(item.get("include-group", ""))
+ if include not in groups:
+ _fail("Unknown dependency group '{}' included from '{}'".format(
+ include,
+ name,
+ ))
+ return None
+ if include not in expanded:
+ reqs = None
+ break
+ reqs.extend(expanded[include])
+
+ if reqs != None:
+ expanded[name] = reqs
+
+ if len(expanded) != len(groups):
+ unexpanded = [name for name in groups if name not in expanded]
+ _fail("Cyclic dependency group includes: {}".format(
+ ", ".join(sorted(unexpanded)),
+ ))
+ return None
+ return expanded
diff --git a/python/private/pypi/extension.bzl b/python/private/pypi/extension.bzl
index 21d5ba5..753e34e 100644
--- a/python/private/pypi/extension.bzl
+++ b/python/private/pypi/extension.bzl
@@ -24,6 +24,7 @@
load("//python/private:repo_utils.bzl", "repo_utils")
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(":parse_whl_name.bzl", "parse_whl_name")
load(":pep508_env.bzl", "env")
@@ -89,6 +90,7 @@
unified_hub_requirements_bzl = False
defaults = {
"platforms": default_platforms(),
+ "pyproject_toml": None,
"python_version": None,
}
for mod in module_ctx.modules:
@@ -105,6 +107,8 @@
unified_hub_requirements_bzl = True
pyproject_toml = tag.pyproject_toml
if pyproject_toml:
+ if mod.is_root:
+ defaults["pyproject_toml"] = pyproject_toml
pyproject = read_pyproject(module_ctx, pyproject_toml)
if pyproject.requires_python:
defaults["python_version"] = version_from_requires_python(pyproject.requires_python)
@@ -153,6 +157,8 @@
for name, values in defaults["platforms"].items()
},
enable_pipstar_extract = enable_pipstar_extract,
+ # Label | None: default `pyproject.toml` from `pip.default`.
+ pyproject_toml = defaults["pyproject_toml"],
toml_decode = toml.decode,
unified_hub_requirements_bzl = unified_hub_requirements_bzl,
)
@@ -245,6 +251,7 @@
# dict[str repo, HubBuilder]
# See `hub_builder.bzl%hub_builder()` for `HubBuilder`
pip_hub_map = {}
+ hub_pyproject = {}
simpleapi_cache = pypi_cache(mctx = module_ctx)
is_pypi_hub_reserved = module_ctx.getenv("RULES_PYTHON_PYPI_HUB_RESERVED", "0") == "1"
@@ -321,6 +328,9 @@
else:
builder = pip_hub_map[hub_name]
+ if pip_attr.pyproject_toml and hub_name not in hub_pyproject:
+ hub_pyproject[hub_name] = pip_attr.pyproject_toml
+
builder.pip_parse(
module_ctx,
pip_attr = pip_attr,
@@ -345,6 +355,7 @@
exposed_packages = {}
extra_aliases = {}
whl_libraries = {}
+ hubs = {}
for hub in pip_hub_map.values():
out = hub.build()
@@ -358,8 +369,38 @@
extra_aliases[hub.name] = out.extra_aliases
hub_group_map[hub.name] = out.group_map
hub_whl_map[hub.name] = out.whl_map
+ hubs[hub.name] = struct(
+ # str: module that created the hub.
+ module_name = hub.module_name,
+ # Label | None: `pyproject_toml` set on `pip.parse`.
+ pyproject = hub_pyproject.get(hub.name),
+ # list[str]: normalized names of all packages in the hub.
+ packages = out.whl_map.keys(),
+ )
+
+ configured_hubs = hub_exposure(
+ module_ctx,
+ hubs = hubs,
+ default_pyproject = config.pyproject_toml,
+ _fail = _fail,
+ )
+ if configured_hubs == None:
+ return None
+
+ # The `all_*requirements` only list the selected packages that are
+ # available on all of the platforms, while all of the selected packages
+ # stay public.
+ for hub_name, packages in configured_hubs.items():
+ selected = {name: None for name in packages}
+ exposed_packages[hub_name] = [
+ name
+ for name in exposed_packages[hub_name]
+ if name in selected
+ ]
return struct(
+ # dict[str, list[str]]: configured hubs and exposed packages.
+ configured_hubs = configured_hubs,
config = config,
declared_deps = declared_deps,
default_hub = config.default_hub or renamed_default_hub,
@@ -392,7 +433,12 @@
extra_aliases = {}
for hub_name in hubs:
- for pkg_name in mods.hub_whl_map[hub_name]:
+ # The hubs configured with `pip.configure` only expose some packages.
+ hub_packages = mods.configured_hubs.get(
+ hub_name,
+ mods.hub_whl_map[hub_name],
+ )
+ for pkg_name in hub_packages:
norm_pkg = normalize_name(pkg_name)
if norm_pkg not in packages:
packages[norm_pkg] = []
@@ -514,6 +560,9 @@
packages = mods.exposed_packages.get(hub_name, []),
platform_config_settings = mods.platform_config_settings.get(hub_name, {}),
groups = mods.hub_group_map.get(hub_name),
+ # The hubs configured with `pip.configure` hide the other packages.
+ hide_unexposed_packages = hub_name in mods.configured_hubs,
+ public_packages = mods.configured_hubs.get(hub_name, []),
)
_create_unified_hub_repo(mods)
@@ -656,6 +705,10 @@
:::{versionadded} 2.3.0
:::
+
+:::{versionchanged} VERSION_NEXT_FEATURE
+Also used by {obj}`pip.configure` for the hubs of the root module.
+:::
""",
),
"unified_hub_requirements_bzl": attr.bool(
@@ -875,6 +928,10 @@
:::{versionadded} 2.3.0
:::
+
+:::{versionchanged} VERSION_NEXT_FEATURE
+Also used by {obj}`pip.configure` to select the packages that the hub exposes.
+:::
""",
),
"python_version": attr.string(
@@ -1074,6 +1131,83 @@
""",
)
+_configure_tag = tag_class(
+ attrs = {
+ "dependency_groups": attr.string_list(
+ default = [],
+ doc = """
+The `pyproject.toml` dependency groups whose packages the hub exposes. The
+default, `[]`, does not select any packages, so the tag does not limit the hub
+and it does not need a `pyproject.toml`.
+
+Each item is one of:
+
+* `"default"`: the `[project] dependencies`.
+* `"optional:<name>"`: the `[project.optional-dependencies]` entry `<name>`.
+* `"group:<name>"`: the PEP 735 `[dependency-groups]` entry `<name>`.
+* `"optional:*"` or `"group:*"`: all entries of the table.
+* `"*"`: all of the above.
+* `"<name>"`: the dependency group `<name>` if it exists, otherwise the
+ optional dependency group `<name>`.
+* `"transitive"`: only supported together with `"*"`, exposes all of the
+ packages of the hub including the transitive dependencies, i.e. all of the
+ packages from the requirements files or the `uv.lock` file.
+
+See {ref}`Configuring the Exposed Packages <pip-configure>` for examples.
+
+:::{versionadded} VERSION_NEXT_FEATURE
+:::
+""",
+ ),
+ "hub_name": attr.string(
+ mandatory = True,
+ doc = """
+The name of the hub to configure.
+
+:::{versionadded} VERSION_NEXT_FEATURE
+:::
+""",
+ ),
+ "pyproject_toml": attr.label(
+ mandatory = False,
+ doc = """
+The `pyproject.toml` file that defines the dependency groups. It is also used
+by the later `pip.configure` tags of the same module and hub that don't set it.
+Defaults to the last `pyproject_toml` set by an earlier `pip.configure` tag of
+the same module and hub, then to the {attr}`pip.parse.pyproject_toml` of the
+hub, then to {attr}`pip.default.pyproject_toml` if the hub is defined by the
+root module. It is only needed when {attr}`dependency_groups` is set.
+
+:::{versionadded} VERSION_NEXT_FEATURE
+:::
+""",
+ ),
+ },
+ doc = """
+Configure the packages exposed by a hub.
+
+The packages are selected from a `pyproject.toml` file using the
+`[project] dependencies`, `[project.optional-dependencies]` and PEP 735
+`[dependency-groups]` tables. The other packages of the hub, e.g. the
+transitive dependencies, are still used by the packages that need them, but
+they are not public.
+
+The tags work like a builder: they are applied in order and multiple tags for
+the same hub are combined, so each tag can configure a different part of the
+hub. A `pyproject_toml` set on a tag is used by the later tags of the same
+module and hub. A tag that does not select any {attr}`dependency_groups` does
+not limit the hub.
+
+Only the root module and the module that created the hub can configure it. If
+both do, the root module wins.
+
+See {ref}`Configuring the Exposed Packages <pip-configure>` for examples.
+
+:::{versionadded} VERSION_NEXT_FEATURE
+:::
+""",
+)
+
pypi = module_extension(
environ = ["RULES_PYTHON_PYPI_HUB_RESERVED"],
doc = """\
@@ -1097,12 +1231,17 @@
- `RULES_PYTHON_PYPI_HUB_RESERVED`: Enable fallback renaming for reserved hub name collisions.
See the {envvar}`RULES_PYTHON_PYPI_HUB_RESERVED` documentation for details.
+pip.configure:
+This tag class configures the packages exposed by a hub using the dependency
+groups from a pyproject.toml file.
+
pip.whl_mods:
This tag class is used to help create JSON files to describe modifications to
the BUILD files for wheels.
""",
implementation = _pip_impl,
tag_classes = {
+ "configure": _configure_tag,
"default": tag_class(
attrs = _default_attrs,
doc = """\
diff --git a/python/private/pypi/hub_exposure.bzl b/python/private/pypi/hub_exposure.bzl
new file mode 100644
index 0000000..7393c28
--- /dev/null
+++ b/python/private/pypi/hub_exposure.bzl
@@ -0,0 +1,97 @@
+"""Compute the packages exposed by the hubs configured with `pip.configure`."""
+
+load("//python/private:pyproject_utils.bzl", "read_pyproject")
+load(":dependency_groups.bzl", "select_dependency_groups")
+
+def hub_exposure(module_ctx, *, hubs, default_pyproject = None, _fail = fail):
+ """Compute the packages exposed by the hubs configured with `pip.configure`.
+
+ Args:
+ module_ctx: {type}`module_ctx` the module context.
+ hubs: {type}`dict[str, struct]` the hubs by name. Each struct has:
+ * `module_name`: {type}`str` the module that created the hub.
+ * `pyproject`: {type}`Label | None` from `pip.parse`.
+ * `packages`: {type}`list[str]` the normalized names of all
+ packages in the hub.
+ default_pyproject: {type}`Label | None` from `pip.default`, only used
+ for the hubs of the root module.
+ _fail: {type}`callable` the failure function, mainly for testing.
+
+ Returns:
+ {type}`dict[str, list[str]] | None` the configured hubs mapped to the
+ sorted packages that they expose. The hubs that are not configured or
+ that expose all of their packages are not included, so that they
+ behave the same. Returns `None` on failure.
+ """
+
+ # The root module wins over the owner of the hub when both configure it.
+ root_modules = [mod for mod in module_ctx.modules if mod.is_root]
+ root_name = root_modules[0].name if root_modules else None
+ root_configured = {}
+ for mod in root_modules:
+ for tag in mod.tags.configure:
+ if tag.dependency_groups:
+ root_configured[tag.hub_name] = None
+
+ configured = {}
+ exposes_all = {}
+ for mod in module_ctx.modules:
+ # The tags of a module are applied in order like a builder: a tag
+ # without a `pyproject_toml` uses the last one set for the hub.
+ last_pyproject = {}
+ for tag in mod.tags.configure:
+ hub = tag.hub_name
+ if hub not in hubs:
+ _fail("pip.configure() refers to unknown hub '{}'. Available hubs: {}".format(
+ hub,
+ ", ".join(sorted(hubs)),
+ ))
+ return None
+
+ info = hubs[hub]
+ if not mod.is_root and mod.name != info.module_name:
+ # Only the root module and the module that created the hub can
+ # configure it.
+ continue
+ if not mod.is_root and hub in root_configured:
+ continue
+
+ if tag.pyproject_toml:
+ last_pyproject[hub] = tag.pyproject_toml
+ if not tag.dependency_groups:
+ # The tag does not select any packages.
+ continue
+
+ pyproject = last_pyproject.get(hub) or info.pyproject
+ if not pyproject and info.module_name == root_name:
+ pyproject = default_pyproject
+ if not pyproject:
+ _fail("pip.configure() for hub '{}' selects the dependency groups {}, which need a pyproject.toml, set `pyproject_toml` on this or an earlier `pip.configure` or on `pip.parse`".format(
+ hub,
+ tag.dependency_groups,
+ ))
+ return None
+
+ selection = select_dependency_groups(
+ read_pyproject(module_ctx, pyproject),
+ tag.dependency_groups,
+ _fail = _fail,
+ )
+ if selection == None:
+ return None
+ if selection.all:
+ exposes_all[hub] = None
+
+ # Multiple tags for the same hub are combined.
+ exposed = configured.setdefault(hub, {})
+ for name in selection.packages:
+ # The pyproject.toml may list packages that are not in the hub,
+ # e.g. tools that are not locked.
+ if name in info.packages:
+ exposed[name] = None
+
+ return {
+ hub: sorted(packages)
+ for hub, packages in configured.items()
+ if hub not in exposes_all
+ }
diff --git a/python/private/pypi/hub_repository.bzl b/python/private/pypi/hub_repository.bzl
index f915aa1..c401168 100644
--- a/python/private/pypi/hub_repository.bzl
+++ b/python/private/pypi/hub_repository.bzl
@@ -26,12 +26,18 @@
"""
def _impl(rctx):
- bzl_packages = rctx.attr.packages or rctx.attr.whl_map.keys()
+ if rctx.attr.hide_unexposed_packages:
+ bzl_packages = rctx.attr.packages
+ exposed_packages = rctx.attr.public_packages
+ else:
+ bzl_packages = rctx.attr.packages or rctx.attr.whl_map.keys()
+ exposed_packages = None
aliases = render_multiplatform_pkg_aliases(
aliases = {
key: _whl_config_settings_from_json(values)
for key, values in rctx.attr.whl_map.items()
},
+ exposed_packages = exposed_packages,
extra_hub_aliases = rctx.attr.extra_hub_aliases,
requirement_cycles = rctx.attr.groups,
platform_config_settings = rctx.attr.platform_config_settings,
@@ -78,16 +84,32 @@
"groups": attr.string_list_dict(
mandatory = False,
),
+ "hide_unexposed_packages": attr.bool(
+ default = False,
+ doc = """
+Make the aliases of the packages that are not in `public_packages` visible only
+to the wheel repositories.
+""",
+ ),
"packages": attr.string_list(
mandatory = False,
- doc = """\
-The list of packages that will be exposed via all_*requirements macros. Defaults to whl_map keys.
+ doc = """
+The list of packages that will be exposed via all_*requirements macros.
+Defaults to whl_map keys unless `hide_unexposed_packages` is set.
""",
),
"platform_config_settings": attr.string_list_dict(
doc = "The constraint values for each platform name. The values are string canonical string Label representations",
mandatory = False,
),
+ "public_packages": attr.string_list(
+ mandatory = False,
+ doc = """
+The packages whose aliases are public when `hide_unexposed_packages` is set.
+Unlike `packages`, it includes the packages that are not available on all of
+the platforms.
+""",
+ ),
"repo_name": attr.string(
mandatory = True,
doc = "The apparent name of the repo. This is needed because in bzlmod, the name attribute becomes the canonical name.",
diff --git a/python/private/pypi/render_pkg_aliases.bzl b/python/private/pypi/render_pkg_aliases.bzl
index 0a1c328..f03c333 100644
--- a/python/private/pypi/render_pkg_aliases.bzl
+++ b/python/private/pypi/render_pkg_aliases.bzl
@@ -65,7 +65,7 @@
else:
return render.dict(aliases, key_repr = _repr_config_setting)
-def _render_common_aliases(*, name, aliases, **kwargs):
+def _render_common_aliases(*, name, aliases, visibility, **kwargs):
pkg_aliases = render.call(
"pkg_aliases",
name = repr(name),
@@ -80,14 +80,21 @@
return """\
load("@rules_python//python/private/pypi:pkg_aliases.bzl", "pkg_aliases")
{extra_loads}
-package(default_visibility = ["//visibility:public"])
+package(default_visibility = {visibility})
{aliases}""".format(
aliases = pkg_aliases,
extra_loads = extra_loads,
+ visibility = render.list(visibility),
)
-def render_pkg_aliases(*, aliases, requirement_cycles = None, extra_hub_aliases = {}, **kwargs):
+def render_pkg_aliases(
+ *,
+ aliases,
+ requirement_cycles = None,
+ extra_hub_aliases = {},
+ exposed_packages = None,
+ **kwargs):
"""Create alias declarations for each PyPI package.
The aliases should be appended to the pip_repository BUILD.bazel file. These aliases
@@ -100,6 +107,9 @@
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.
+ exposed_packages: The packages that should be public. When set, the
+ aliases of the other packages are only visible to the wheel
+ repositories.
**kwargs: Extra kwargs to pass to the rules.
Returns:
@@ -124,21 +134,67 @@
for whl_name in group_whls
}
- files = {
- "{}/BUILD.bazel".format(normalize_name(name)): _render_common_aliases(
- name = normalize_name(name),
+ public = ["//visibility:public"]
+ if exposed_packages != None:
+ exposed_packages = {
+ normalize_name(name): None
+ for name in exposed_packages
+ }
+ internal_visibility = _internal_visibility(
+ aliases,
+ has_groups = bool(requirement_cycles),
+ )
+
+ files = {}
+ for name, pkg_aliases in aliases.items():
+ name = normalize_name(name)
+ visibility = public
+ if exposed_packages != None and name not in exposed_packages:
+ visibility = internal_visibility
+ files["{}/BUILD.bazel".format(name)] = _render_common_aliases(
+ name = name,
aliases = pkg_aliases,
- extra_aliases = extra_hub_aliases.get(normalize_name(name), []),
- group_name = whl_group_mapping.get(normalize_name(name)),
+ extra_aliases = extra_hub_aliases.get(name, []),
+ group_name = whl_group_mapping.get(name),
+ visibility = visibility,
**kwargs
).strip()
- for name, pkg_aliases in aliases.items()
- }
if requirement_cycles:
files["_groups/BUILD.bazel"] = generate_group_library_build_bazel("", requirement_cycles)
return files
+def _internal_visibility(aliases, has_groups = False):
+ """Return the visibility list for packages that are not exposed.
+
+ The wheel repositories depend on the aliases of the hub, so the aliases
+ have to be visible to them.
+
+ Args:
+ aliases: {type}`dict[str, str | dict[struct, str]]` package-to-repo
+ alias mapping.
+ has_groups: {type}`bool` whether requirement cycle groups exist.
+
+ Returns:
+ {type}`list[str]` visibility package specifications.
+ """
+ repo_names = {}
+ for pkg_aliases in aliases.values():
+ if type(pkg_aliases) == type(""):
+ repo_names[pkg_aliases] = None
+ continue
+
+ for repo_name in pkg_aliases.values():
+ repo_names[repo_name] = None
+
+ visibility = [
+ "@{}//:__pkg__".format(repo_name)
+ for repo_name in sorted(repo_names)
+ ]
+ if has_groups:
+ visibility.append("//_groups:__pkg__")
+ return visibility
+
def _major_minor(python_version):
major, _, tail = python_version.partition(".")
minor, _, _ = tail.partition(".")
diff --git a/python/private/pyproject_utils.bzl b/python/private/pyproject_utils.bzl
index e96ffd2..c65157d 100644
--- a/python/private/pyproject_utils.bzl
+++ b/python/private/pyproject_utils.bzl
@@ -18,10 +18,29 @@
{type}`struct` with the attributes:
* `requires_python`: {type}`str | None` the raw `requires-python`
value (e.g. `"==3.13.9"`), or `None` if it is not set.
+ * `name`: {type}`str | None` the `[project] name`.
+ * `dependencies`: {type}`list[str]` the `[project] dependencies`.
+ * `optional_dependencies`: {type}`dict[str, list[str]]` the
+ `[project.optional-dependencies]` table.
+ * `dependency_groups`: {type}`dict[str, list[str | dict[str, str]]]`
+ the PEP 735 `[dependency-groups]` table. Items are either
+ requirement strings or `{include-group = "<name>"}` tables.
"""
- data = toml.decode(module_ctx.read(module_ctx.path(pyproject), watch = "yes"))
+ raw = module_ctx.read(module_ctx.path(pyproject), watch = "yes")
+ data = toml.decode(raw)
+ project = data.get("project", {})
return struct(
- requires_python = data.get("project", {}).get("requires-python"),
+ # str | None: raw `[project] requires-python` value.
+ requires_python = project.get("requires-python"),
+ # str | None: `[project] name`.
+ name = project.get("name"),
+ # list[str]: `[project] dependencies` requirement strings.
+ dependencies = project.get("dependencies") or [],
+ # dict[str, list[str]]: `[project.optional-dependencies]` table.
+ optional_dependencies = project.get("optional-dependencies") or {},
+ # dict[str, list[str | dict[str, str]]]: PEP 735 `[dependency-groups]`
+ # table of requirement strings and `{"include-group": str}` dicts.
+ dependency_groups = data.get("dependency-groups") or {},
)
def version_from_requires_python(requires_python):
diff --git a/tests/integration/unified_pypi/BUILD.bazel b/tests/integration/unified_pypi/BUILD.bazel
index 13d188d..78f9a85 100644
--- a/tests/integration/unified_pypi/BUILD.bazel
+++ b/tests/integration/unified_pypi/BUILD.bazel
@@ -95,3 +95,31 @@
"@platforms//os:windows",
],
)
+
+# The pypi_filtered hub only makes its pyproject.toml packages public.
+py_test(
+ name = "test_filtered_direct",
+ srcs = ["test_default.py"],
+ main = "test_default.py",
+ deps = ["@pypi_filtered//colorama"],
+)
+
+# six is not exposed by pypi_filtered, so it is missing in the unified hub.
+py_binary(
+ name = "bin_filtered_six_unified",
+ srcs = ["bin_six_a.py"],
+ config_settings = {
+ "@rules_python//python/config_settings:venv": "pypi_filtered",
+ },
+ main = "bin_six_a.py",
+ tags = ["manual"],
+ deps = ["@pypi//six"],
+)
+
+py_binary(
+ name = "bin_filtered_six",
+ srcs = ["bin_six_a.py"],
+ main = "bin_six_a.py",
+ tags = ["manual"],
+ deps = ["@pypi_filtered//six"],
+)
diff --git a/tests/integration/unified_pypi/MODULE.bazel b/tests/integration/unified_pypi/MODULE.bazel
index ee8f622..70e01cc 100644
--- a/tests/integration/unified_pypi/MODULE.bazel
+++ b/tests/integration/unified_pypi/MODULE.bazel
@@ -53,6 +53,20 @@
)
use_repo(pip, "pypi_b")
+# `pypi_filtered` only exposes the `[project] dependencies` of the
+# `pyproject.toml`, the other packages are not public.
+pip.parse(
+ hub_name = "pypi_filtered",
+ pyproject_toml = "//:pyproject_filtered.toml",
+ python_version = "3.11",
+ requirements_lock = "//:requirements_b.txt",
+)
+pip.configure(
+ dependency_groups = ["default"],
+ hub_name = "pypi_filtered",
+)
+use_repo(pip, "pypi_filtered")
+
pip.default(default_hub = "pypi_b")
pip.default(unified_hub_requirements_bzl = True)
pip.dep(
diff --git a/tests/integration/unified_pypi/pyproject_filtered.toml b/tests/integration/unified_pypi/pyproject_filtered.toml
new file mode 100644
index 0000000..632f72f
--- /dev/null
+++ b/tests/integration/unified_pypi/pyproject_filtered.toml
@@ -0,0 +1,4 @@
+[project]
+name = "unified-pypi"
+version = "0.0.0"
+dependencies = ["colorama"]
diff --git a/tests/integration/unified_pypi_test.py b/tests/integration/unified_pypi_test.py
index 9ce41fa..f59a19f 100644
--- a/tests/integration/unified_pypi_test.py
+++ b/tests/integration/unified_pypi_test.py
@@ -7,6 +7,32 @@
class UnifiedPypiTest(runner.TestCase):
+ def test_configure_hides_unexposed_packages(self):
+ self.run_bazel("test", "//:test_filtered_direct")
+ result = self.run_bazel("build", "//:bin_filtered_six", check=False)
+ self.assertNotEqual(
+ result.exit_code,
+ 0,
+ "Expected the alias of the unexposed package to be hidden",
+ )
+ self.assert_result_matches(
+ result,
+ r"alias '[^']*//six:six'.*is not visible from",
+ )
+
+ def test_configure_hides_unexposed_packages_in_unified_hub(self):
+ self.run_bazel("cquery", "//:bin_filtered_six_unified")
+ result = self.run_bazel("build", "//:bin_filtered_six_unified", check=False)
+ self.assertNotEqual(
+ result.exit_code,
+ 0,
+ "Expected build to fail during execution phase",
+ )
+ self.assert_result_matches(
+ result,
+ 'ERROR: PyPI package "six" is not available when building under PyPI hub "pypi_filtered"\\. Try adding it to the requirements of this hub',
+ )
+
def test_default_fallback_hub(self):
self.run_bazel("test", "//:test_default")
diff --git a/tests/pypi/dependency_groups/BUILD.bazel b/tests/pypi/dependency_groups/BUILD.bazel
new file mode 100644
index 0000000..ba6877e
--- /dev/null
+++ b/tests/pypi/dependency_groups/BUILD.bazel
@@ -0,0 +1,3 @@
+load(":dependency_groups_tests.bzl", "dependency_groups_test_suite")
+
+dependency_groups_test_suite(name = "dependency_groups_tests")
diff --git a/tests/pypi/dependency_groups/dependency_groups_tests.bzl b/tests/pypi/dependency_groups/dependency_groups_tests.bzl
new file mode 100644
index 0000000..a53905b
--- /dev/null
+++ b/tests/pypi/dependency_groups/dependency_groups_tests.bzl
@@ -0,0 +1,168 @@
+"""dependency_groups tests"""
+
+load("@rules_testing//lib:test_suite.bzl", "test_suite")
+load(
+ "//python/private/pypi:dependency_groups.bzl",
+ "select_dependency_groups",
+) # buildifier: disable=bzl-visibility
+
+_tests = []
+
+_PYPROJECT = struct(
+ name = "my-project",
+ dependencies = ["main-pkg>=1.0"],
+ optional_dependencies = {
+ "Docs": ["docs-pkg"],
+ "all": ["My_Project[docs, grpc]"],
+ "grpc": ["grpc-pkg"],
+ },
+ dependency_groups = {
+ "dev": ["dev-pkg", "shared-pkg", {"include-group": "Test"}],
+ "test": ["test_pkg", "shared-pkg"],
+ },
+)
+
+def _select(specs, pyproject = _PYPROJECT):
+ failures = []
+ got = select_dependency_groups(pyproject, specs, _fail = failures.append)
+ return got, failures
+
+def _test_select(env):
+ for specs, want in [
+ (["default"], ["main_pkg"]),
+ (["optional:docs"], ["docs_pkg"]),
+ (["group:test"], ["shared_pkg", "test_pkg"]),
+ (["dev"], ["dev_pkg", "shared_pkg", "test_pkg"]),
+ (["grpc"], ["grpc_pkg"]),
+ (["all"], ["docs_pkg", "grpc_pkg"]),
+ (["optional:*"], ["docs_pkg", "grpc_pkg"]),
+ (["group:*"], ["dev_pkg", "shared_pkg", "test_pkg"]),
+ (["default", "group:test"], ["main_pkg", "shared_pkg", "test_pkg"]),
+ (
+ ["*"],
+ [
+ "dev_pkg",
+ "docs_pkg",
+ "grpc_pkg",
+ "main_pkg",
+ "shared_pkg",
+ "test_pkg",
+ ],
+ ),
+ ]:
+ got, failures = _select(specs)
+ env.expect.where(specs = specs).that_collection(
+ failures,
+ ).contains_exactly([])
+ env.expect.where(specs = specs).that_collection(
+ got.packages,
+ ).contains_exactly(want).in_order()
+ env.expect.where(specs = specs).that_bool(got.all).equals(False)
+
+_tests.append(_test_select)
+
+def _test_self_reference_extras(env):
+ pyproject = struct(
+ name = "my-project",
+ dependencies = [],
+ optional_dependencies = {
+ "a": ["a-pkg", "my-project[b]"],
+ "all": ["My_Project[docs, grpc]"],
+ "b": ["b-pkg", "my-project[a]"],
+ "docs": ["docs-pkg"],
+ "everything": ["my-project[all]", "my-project"],
+ "grpc": ["grpc-pkg"],
+ },
+ dependency_groups = {
+ "ci": ["ci-pkg", "my-project[all]"],
+ },
+ )
+ for specs, want in [
+ (["everything"], ["docs_pkg", "grpc_pkg"]),
+ (["ci"], ["ci_pkg", "docs_pkg", "grpc_pkg"]),
+ (["a"], ["a_pkg", "b_pkg"]),
+ ]:
+ got, failures = _select(specs, pyproject = pyproject)
+ env.expect.where(specs = specs).that_collection(
+ failures,
+ ).contains_exactly([])
+ env.expect.where(specs = specs).that_collection(
+ got.packages,
+ ).contains_exactly(want).in_order()
+
+_tests.append(_test_self_reference_extras)
+
+def _test_select_all(env):
+ got, failures = _select(["*", "transitive"])
+ env.expect.that_collection(failures).contains_exactly([])
+ env.expect.that_bool(got.all).equals(True)
+ env.expect.that_collection(got.packages).contains_exactly([])
+
+_tests.append(_test_select_all)
+
+def _test_select_empty_wildcards(env):
+ pyproject = struct(
+ name = "my-project",
+ dependencies = ["main-pkg"],
+ optional_dependencies = {},
+ dependency_groups = {},
+ )
+ for specs, want in [
+ (["optional:*"], []),
+ (["group:*"], []),
+ (["*"], ["main_pkg"]),
+ ]:
+ got, failures = _select(specs, pyproject = pyproject)
+ env.expect.where(specs = specs).that_collection(failures).contains_exactly([])
+ env.expect.where(specs = specs).that_collection(got.packages).contains_exactly(want)
+
+_tests.append(_test_select_empty_wildcards)
+
+def _test_select_errors(env):
+ for specs, want in [
+ (
+ ["missing"],
+ "Unknown dependency group 'missing'. Available groups: default, group:dev, group:test, optional:all, optional:docs, optional:grpc",
+ ),
+ (
+ ["default", "transitive"],
+ "The 'transitive' dependency group specifier is only supported together with '*', which selects all of the packages, got: [\"default\", \"transitive\"]",
+ ),
+ ]:
+ got, failures = _select(specs)
+ env.expect.where(specs = specs).that_str(got).equals(None)
+ env.expect.where(specs = specs).that_collection(
+ failures,
+ ).contains_exactly([want])
+
+_tests.append(_test_select_errors)
+
+def _test_include_group_errors(env):
+ for groups, want in [
+ (
+ {"a": [{"include-group": "missing"}]},
+ "Unknown dependency group 'missing' included from 'a'",
+ ),
+ (
+ {"a": [{"include-group": "b"}], "b": [{"include-group": "a"}]},
+ "Cyclic dependency group includes: a, b",
+ ),
+ ]:
+ got, failures = _select(["a"], pyproject = struct(
+ name = None,
+ dependencies = [],
+ optional_dependencies = {},
+ dependency_groups = groups,
+ ))
+ env.expect.that_str(got).equals(None)
+ env.expect.that_collection(failures).contains_exactly([want])
+
+_tests.append(_test_include_group_errors)
+
+def dependency_groups_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/extension/extension_tests.bzl b/tests/pypi/extension/extension_tests.bzl
index 91bf3c7..f1974cf 100644
--- a/tests/pypi/extension/extension_tests.bzl
+++ b/tests/pypi/extension/extension_tests.bzl
@@ -21,10 +21,31 @@
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")
-load(":pip_parse.bzl", _parse = "pip_parse")
+load(":pip_parse.bzl", _configure = "configure", _parse = "pip_parse")
_tests = []
+_CONFIGURE_REQUIREMENTS = """\
+simple==0.0.1 \
+ --hash=sha256:deadbeef \
+ --hash=sha256:deadbaaf
+other-pkg==0.0.2 \
+ --hash=sha256:deadbeef \
+ --hash=sha256:deadbaaf
+transitive-pkg==0.0.3 \
+ --hash=sha256:deadbeef \
+ --hash=sha256:deadbaaf
+"""
+
+_CONFIGURE_PYPROJECT = """\
+[project]
+dependencies = ["simple"]
+
+[dependency-groups]
+dev = ["other-pkg"]
+test = ["simple"]
+"""
+
def _pypi_mock_mctx(*modules, os_name = "unittest", arch_name = "exotic", environ = {}, read = None, mock_files = {}):
_ = read # @unused
return mocks.mctx(
@@ -107,10 +128,20 @@
extra_targets = extra_targets,
)
-def _mod(*, name, default = _default_tags_default, parse = [], override = [], whl_mods = [], dep = [], is_root = True):
+def _mod(
+ *,
+ name,
+ default = _default_tags_default,
+ parse = [],
+ override = [],
+ whl_mods = [],
+ dep = [],
+ configure = [],
+ is_root = True):
return struct(
name = name,
tags = struct(
+ configure = configure,
parse = parse,
override = override,
whl_mods = whl_mods,
@@ -124,6 +155,7 @@
return env.expect.that_struct(
parse_modules(**kwargs),
attrs = dict(
+ configured_hubs = subjects.dict,
declared_deps = subjects.dict,
default_hub = subjects.str,
exposed_packages = subjects.dict,
@@ -819,6 +851,125 @@
_tests.append(_test_default_index_setting)
+def _configure_parse_modules(env, *modules):
+ return _parse_modules(
+ env,
+ module_ctx = _pypi_mock_mctx(
+ os_name = "linux",
+ arch_name = "x86_64",
+ mock_files = {
+ "pyproject.toml": _CONFIGURE_PYPROJECT,
+ "requirements.txt": _CONFIGURE_REQUIREMENTS,
+ },
+ *modules
+ ),
+ available_interpreters = {
+ "python_3_15_host": "unit_test_interpreter_target",
+ },
+ minor_mapping = {"3.15": "3.15.19"},
+ )
+
+def _configure_parse(**kwargs):
+ return _parse(
+ hub_name = "pypi_a",
+ python_version = "3.15",
+ simpleapi_skip = ["simple", "other-pkg", "transitive-pkg"],
+ requirements_lock = "requirements.txt",
+ **kwargs
+ )
+
+def _test_configure(env):
+ # The selection itself is tested in `hub_exposure_tests`.
+ pypi = _configure_parse_modules(
+ env,
+ _mod(
+ name = "rules_python",
+ parse = [_configure_parse(pyproject_toml = "pyproject.toml")],
+ configure = [
+ _configure(hub_name = "pypi_a", dependency_groups = ["test"]),
+ ],
+ ),
+ )
+
+ pypi.exposed_packages().contains_exactly({"pypi_a": ["simple"]})
+ pypi.configured_hubs().contains_exactly({"pypi_a": ["simple"]})
+
+_tests.append(_test_configure)
+
+def _test_configure_platform_specific(env):
+ # A selected package that is not available on all of the platforms is
+ # public, but it is not in the `all_*requirements`.
+ pypi = _parse_modules(
+ env,
+ module_ctx = _pypi_mock_mctx(
+ _mod(
+ name = "rules_python",
+ parse = [_configure_parse(
+ pyproject_toml = "pyproject.toml",
+ target_platforms = ["linux_x86_64", "windows_aarch64"],
+ )],
+ configure = [
+ _configure(hub_name = "pypi_a", dependency_groups = ["default", "dev"]),
+ ],
+ ),
+ os_name = "linux",
+ arch_name = "x86_64",
+ mock_files = {
+ "pyproject.toml": _CONFIGURE_PYPROJECT,
+ "requirements.txt": _CONFIGURE_REQUIREMENTS.replace(
+ "other-pkg==0.0.2",
+ "other-pkg==0.0.2 ; sys_platform == 'win32'",
+ ),
+ },
+ ),
+ available_interpreters = {
+ "python_3_15_host": "unit_test_interpreter_target",
+ },
+ minor_mapping = {"3.15": "3.15.19"},
+ )
+
+ pypi.exposed_packages().contains_exactly({"pypi_a": ["simple"]})
+ pypi.configured_hubs().contains_exactly({"pypi_a": ["other_pkg", "simple"]})
+
+_tests.append(_test_configure_platform_specific)
+
+def _test_configure_default_pyproject(env):
+ # The `pip.default` pyproject.toml is used for the hubs of the root module.
+ pypi = _configure_parse_modules(
+ env,
+ _mod(
+ name = "rules_python",
+ default = _default_tags_default + [
+ _default(pyproject_toml = "pyproject.toml"),
+ ],
+ parse = [_configure_parse()],
+ configure = [
+ _configure(hub_name = "pypi_a", dependency_groups = ["dev"]),
+ ],
+ ),
+ )
+
+ pypi.configured_hubs().contains_exactly({"pypi_a": ["other_pkg"]})
+
+_tests.append(_test_configure_default_pyproject)
+
+def _test_not_configured_exposes_all(env):
+ # The pyproject.toml does not filter the hub without `pip.configure`.
+ pypi = _configure_parse_modules(
+ env,
+ _mod(
+ name = "rules_python",
+ parse = [_configure_parse()],
+ ),
+ )
+
+ pypi.exposed_packages().contains_exactly({
+ "pypi_a": ["other_pkg", "simple", "transitive_pkg"],
+ })
+ pypi.configured_hubs().contains_exactly({})
+
+_tests.append(_test_not_configured_exposes_all)
+
def extension_test_suite(name):
"""Create the test suite.
diff --git a/tests/pypi/extension/pip_parse.bzl b/tests/pypi/extension/pip_parse.bzl
index 638836e..d048f99 100644
--- a/tests/pypi/extension/pip_parse.bzl
+++ b/tests/pypi/extension/pip_parse.bzl
@@ -1,5 +1,17 @@
"""A simple test helper"""
+def configure(
+ *,
+ dependency_groups = [],
+ hub_name,
+ pyproject_toml = None):
+ """Simulate the PyPI extension configure tag class for testing."""
+ return struct(
+ dependency_groups = dependency_groups,
+ hub_name = hub_name,
+ pyproject_toml = pyproject_toml,
+ )
+
def pip_parse(
*,
hub_name,
diff --git a/tests/pypi/hub_exposure/BUILD.bazel b/tests/pypi/hub_exposure/BUILD.bazel
new file mode 100644
index 0000000..187361e
--- /dev/null
+++ b/tests/pypi/hub_exposure/BUILD.bazel
@@ -0,0 +1,3 @@
+load(":hub_exposure_tests.bzl", "hub_exposure_test_suite")
+
+hub_exposure_test_suite(name = "hub_exposure_tests")
diff --git a/tests/pypi/hub_exposure/hub_exposure_tests.bzl b/tests/pypi/hub_exposure/hub_exposure_tests.bzl
new file mode 100644
index 0000000..1f2b136
--- /dev/null
+++ b/tests/pypi/hub_exposure/hub_exposure_tests.bzl
@@ -0,0 +1,254 @@
+"""hub_exposure tests"""
+
+load("@rules_testing//lib:test_suite.bzl", "test_suite")
+load(
+ "//python/private/pypi:hub_exposure.bzl",
+ "hub_exposure",
+) # buildifier: disable=bzl-visibility
+load("//tests/support/mocks:mocks.bzl", "mocks")
+
+_tests = []
+
+_PYPROJECT = """\
+[project]
+dependencies = ["simple"]
+
+[dependency-groups]
+dev = ["other-pkg"]
+test = ["simple", "not-in-hub"]
+"""
+
+def _hub(*, module_name = "root", pyproject = None):
+ return struct(
+ module_name = module_name,
+ pyproject = pyproject,
+ packages = ["other_pkg", "simple", "transitive_pkg"],
+ )
+
+def _configure(
+ hub_name = "hub",
+ dependency_groups = [],
+ pyproject_toml = None):
+ return mocks.tag(
+ hub_name = hub_name,
+ dependency_groups = dependency_groups,
+ pyproject_toml = pyproject_toml,
+ )
+
+def _module(name = "root", is_root = True, configure = []):
+ return mocks.module(name = name, is_root = is_root, configure = configure)
+
+def _exposure(*modules, hubs = None, default_pyproject = None):
+ failures = []
+ got = hub_exposure(
+ mocks.mctx(
+ modules = list(modules),
+ mock_files = {
+ "other.toml": "[project]\ndependencies = [\"other-pkg\"]\n",
+ "pyproject.toml": _PYPROJECT,
+ },
+ ),
+ hubs = hubs or {"hub": _hub(pyproject = "pyproject.toml")},
+ default_pyproject = default_pyproject,
+ _fail = failures.append,
+ )
+ return got, failures
+
+def _test_not_configured(env):
+ got, failures = _exposure(_module())
+ env.expect.that_collection(failures).contains_exactly([])
+ env.expect.that_dict(got).contains_exactly({})
+
+_tests.append(_test_not_configured)
+
+def _test_configure(env):
+ for groups, want in [
+ (["*"], ["other_pkg", "simple"]),
+ (["default"], ["simple"]),
+ (["dev"], ["other_pkg"]),
+ # `not-in-hub` is ignored
+ (["group:test"], ["simple"]),
+ ]:
+ got, failures = _exposure(
+ _module(configure = [_configure(dependency_groups = groups)]),
+ )
+ env.expect.where(groups = groups).that_collection(
+ failures,
+ ).contains_exactly([])
+ env.expect.where(groups = groups).that_dict(got).contains_exactly(
+ {"hub": want},
+ )
+
+_tests.append(_test_configure)
+
+def _test_configure_all_packages(env):
+ # Exposing all of the packages is the same as not configuring the hub, so
+ # that e.g. the platform-specific packages stay public.
+ got, failures = _exposure(_module(configure = [
+ _configure(dependency_groups = ["default"]),
+ _configure(dependency_groups = ["*", "transitive"]),
+ ]))
+ env.expect.that_collection(failures).contains_exactly([])
+ env.expect.that_dict(got).contains_exactly({})
+
+_tests.append(_test_configure_all_packages)
+
+def _test_configure_combines_tags(env):
+ got, failures = _exposure(_module(configure = [
+ _configure(dependency_groups = ["default"]),
+ _configure(dependency_groups = ["dev"]),
+ ]))
+ env.expect.that_collection(failures).contains_exactly([])
+ env.expect.that_dict(got).contains_exactly(
+ {"hub": ["other_pkg", "simple"]},
+ )
+
+_tests.append(_test_configure_combines_tags)
+
+def _test_configure_pyproject_precedence(env):
+ # The tag wins over the `pip.parse` value.
+ got, _ = _exposure(_module(configure = [
+ _configure(pyproject_toml = "other.toml", dependency_groups = ["*"]),
+ ]))
+ env.expect.that_dict(got).contains_exactly({"hub": ["other_pkg"]})
+
+ # The `pip.default` value is used for the hubs of the root module.
+ got, failures = _exposure(
+ _module(configure = [_configure(dependency_groups = ["default"])]),
+ hubs = {"hub": _hub()},
+ default_pyproject = "pyproject.toml",
+ )
+ env.expect.that_collection(failures).contains_exactly([])
+ env.expect.that_dict(got).contains_exactly({"hub": ["simple"]})
+
+_tests.append(_test_configure_pyproject_precedence)
+
+def _test_configure_without_pyproject(env):
+ # A tag without the dependency groups does not need a pyproject.toml and
+ # does not limit the hub.
+ got, failures = _exposure(
+ _module(configure = [_configure()]),
+ hubs = {"hub": _hub()},
+ )
+ env.expect.that_collection(failures).contains_exactly([])
+ env.expect.that_dict(got).contains_exactly({})
+
+_tests.append(_test_configure_without_pyproject)
+
+def _test_configure_builder(env):
+ # The `pyproject_toml` of a tag is used by the later tags of the hub.
+ got, failures = _exposure(
+ _module(configure = [
+ _configure(pyproject_toml = "other.toml"),
+ _configure(dependency_groups = ["default"]),
+ ]),
+ hubs = {"hub": _hub(pyproject = "pyproject.toml")},
+ )
+ env.expect.that_collection(failures).contains_exactly([])
+ env.expect.that_dict(got).contains_exactly({"hub": ["other_pkg"]})
+
+ # The tags before it use the `pip.parse` value.
+ got, failures = _exposure(
+ _module(configure = [
+ _configure(dependency_groups = ["default"]),
+ _configure(pyproject_toml = "other.toml", dependency_groups = ["default"]),
+ ]),
+ hubs = {"hub": _hub(pyproject = "pyproject.toml")},
+ )
+ env.expect.that_collection(failures).contains_exactly([])
+ env.expect.that_dict(got).contains_exactly({"hub": ["other_pkg", "simple"]})
+
+ # It is not used by the other modules.
+ hubs = {"hub": _hub(module_name = "dep")}
+ got, failures = _exposure(
+ _module(configure = [_configure(hub_name = "hub", pyproject_toml = "other.toml")]),
+ _module(
+ name = "dep",
+ is_root = False,
+ configure = [_configure(hub_name = "hub", dependency_groups = ["default"])],
+ ),
+ hubs = hubs,
+ )
+ env.expect.that_str(got).equals(None)
+ env.expect.that_collection(failures).contains_exactly([
+ "pip.configure() for hub 'hub' selects the dependency groups [\"default\"], which need a pyproject.toml, set `pyproject_toml` on this or an earlier `pip.configure` or on `pip.parse`",
+ ])
+
+_tests.append(_test_configure_builder)
+
+def _test_configure_module_precedence(env):
+ hubs = {"hub": _hub(module_name = "dep", pyproject = "pyproject.toml")}
+
+ # The owner of the hub can configure it.
+ got, _ = _exposure(
+ _module(),
+ _module(
+ name = "dep",
+ is_root = False,
+ configure = [_configure(dependency_groups = ["dev"])],
+ ),
+ hubs = hubs,
+ )
+ env.expect.that_dict(got).contains_exactly({"hub": ["other_pkg"]})
+
+ # The root module wins over the owner.
+ got, _ = _exposure(
+ _module(configure = [_configure(dependency_groups = ["default"])]),
+ _module(
+ name = "dep",
+ is_root = False,
+ configure = [_configure(dependency_groups = ["dev"])],
+ ),
+ hubs = hubs,
+ )
+ env.expect.that_dict(got).contains_exactly({"hub": ["simple"]})
+
+ # Other modules are ignored.
+ got, _ = _exposure(
+ _module(),
+ _module(
+ name = "other",
+ is_root = False,
+ configure = [_configure(dependency_groups = ["dev"])],
+ ),
+ hubs = hubs,
+ )
+ env.expect.that_dict(got).contains_exactly({})
+
+_tests.append(_test_configure_module_precedence)
+
+def _test_configure_errors(env):
+ got, failures = _exposure(
+ _module(configure = [_configure(hub_name = "missing")]),
+ )
+ env.expect.that_str(got).equals(None)
+ env.expect.that_collection(failures).contains_exactly([
+ "pip.configure() refers to unknown hub 'missing'. Available hubs: hub",
+ ])
+
+ got, failures = _exposure(
+ _module(configure = [_configure(dependency_groups = ["*"])]),
+ hubs = {"hub": _hub()},
+ )
+ env.expect.that_str(got).equals(None)
+ env.expect.that_collection(failures).contains_exactly([
+ "pip.configure() for hub 'hub' selects the dependency groups [\"*\"], which need a pyproject.toml, set `pyproject_toml` on this or an earlier `pip.configure` or on `pip.parse`",
+ ])
+
+ got, failures = _exposure(
+ _module(configure = [_configure(dependency_groups = ["missing"])]),
+ )
+ env.expect.that_str(got).equals(None)
+ env.expect.that_collection(failures).contains_exactly([
+ "Unknown dependency group 'missing'. Available groups: default, group:dev, group:test",
+ ])
+
+_tests.append(_test_configure_errors)
+
+def hub_exposure_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/render_pkg_aliases/render_pkg_aliases_test.bzl b/tests/pypi/render_pkg_aliases/render_pkg_aliases_test.bzl
index 9114f59..13bee38 100644
--- a/tests/pypi/render_pkg_aliases/render_pkg_aliases_test.bzl
+++ b/tests/pypi/render_pkg_aliases/render_pkg_aliases_test.bzl
@@ -58,6 +58,68 @@
_tests.append(_test_legacy_aliases)
+def _test_hidden_aliases(env):
+ actual = render_pkg_aliases(
+ aliases = {
+ "bar": "pypi_bar",
+ "foo": "pypi_foo",
+ },
+ exposed_packages = ["foo"],
+ )
+
+ env.expect.that_str(actual["bar/BUILD.bazel"]).equals("""\
+load("@rules_python//python/private/pypi:pkg_aliases.bzl", "pkg_aliases")
+
+package(default_visibility = [
+ "@pypi_bar//:__pkg__",
+ "@pypi_foo//:__pkg__",
+])
+
+pkg_aliases(
+ name = "bar",
+ actual = "pypi_bar",
+)""")
+ env.expect.that_str(actual["foo/BUILD.bazel"]).equals("""\
+load("@rules_python//python/private/pypi:pkg_aliases.bzl", "pkg_aliases")
+
+package(default_visibility = ["//visibility:public"])
+
+pkg_aliases(
+ name = "foo",
+ actual = "pypi_foo",
+)""")
+
+_tests.append(_test_hidden_aliases)
+
+def _test_hidden_aliases_in_groups(env):
+ actual = render_pkg_aliases(
+ aliases = {
+ "bar": "pypi_bar",
+ "baz": "pypi_baz",
+ },
+ requirement_cycles = {
+ "group": ["bar", "baz"],
+ },
+ exposed_packages = ["baz"],
+ )
+
+ env.expect.that_str(actual["bar/BUILD.bazel"]).equals("""\
+load("@rules_python//python/private/pypi:pkg_aliases.bzl", "pkg_aliases")
+
+package(default_visibility = [
+ "@pypi_bar//:__pkg__",
+ "@pypi_baz//:__pkg__",
+ "//_groups:__pkg__",
+])
+
+pkg_aliases(
+ name = "bar",
+ actual = "pypi_bar",
+ group_name = "group",
+)""")
+
+_tests.append(_test_hidden_aliases_in_groups)
+
def _test_bzlmod_aliases(env):
# Use this function as it is used in pip_repository
actual = render_multiplatform_pkg_aliases(