Skip to content

Commit 14bd140

Browse files
committed
remove the implicit namespace packages
1 parent 89384c7 commit 14bd140

File tree

10 files changed

+130
-418
lines changed

10 files changed

+130
-418
lines changed

python/config_settings/BUILD.bazel

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,15 @@ string_flag(
217217
visibility = ["//visibility:public"],
218218
)
219219

220+
config_setting(
221+
name = "is_venvs_site_packages",
222+
flag_values = {
223+
":venvs_site_packages": VenvsSitePackages.YES,
224+
},
225+
# NOTE: Only public because it is used in whl_library repos.
226+
visibility = ["//visibility:public"],
227+
)
228+
220229
define_pypi_internal_flags(
221230
name = "define_pypi_internal_flags",
222231
)
Lines changed: 55 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,59 @@
11
"""Utilities to get where we should write namespace pkg paths."""
22

3-
EXTS = [
4-
".py",
5-
".pyd",
6-
".so",
7-
".pyc",
8-
]
3+
load("@bazel_skylib//rules:write_file.bzl", "write_file")
4+
5+
_ext = struct(
6+
py = ".py",
7+
pyi = ".pyi",
8+
pyd = ".pyd",
9+
so = ".so",
10+
pyc = ".pyc",
11+
)
12+
13+
_INIT_CONTENTS = """\
14+
# __path__ manipulation added by bazel-contrib/rules_python to support namespace pkgs.
15+
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
16+
""".split("\n")
917

1018
def _add_all(dirname, dirs):
1119
dir_path = "."
1220
for dir_name in dirname.split("/"):
1321
dir_path = "{}/{}".format(dir_path, dir_name)
1422
dirs[dir_path[2:]] = None
1523

16-
def _get_files(files, ignored_dirnames = [], root = None):
24+
def get_files(*, srcs, ignored_dirnames = [], root = None):
25+
"""Get the list of filenames to write the namespace pkg files.
26+
27+
Args:
28+
srcs: {type}`src` a list of files to be passed to {bzl:obj}`py_library`
29+
as `srcs` and `data`. This is usually a result of a {obj}`glob`.
30+
ignored_dirnames: {type}`str` a list of patterns to ignore.
31+
root: {type}`str` the prefix to use as the root.
32+
33+
Returns:
34+
{type}`src` a list of paths to write the namespace pkg `__init__.py` file.
35+
"""
1736
dirs = {}
1837
ignored = {i: None for i in ignored_dirnames}
1938

2039
if root:
2140
_add_all(root, ignored)
2241

23-
for file in files:
42+
for file in srcs:
2443
dirname, _, filename = file.rpartition("/")
2544

2645
if filename == "__init__.py":
2746
ignored[dirname] = None
2847
dirname, _, _ = dirname.rpartition("/")
29-
elif filename.endswith(EXTS[0]):
48+
elif filename.endswith(_ext.py):
49+
pass
50+
elif filename.endswith(_ext.pyc):
3051
pass
31-
elif filename.endswith(EXTS[1]):
52+
elif filename.endswith(_ext.pyd):
3253
pass
33-
elif filename.endswith(EXTS[2]):
54+
elif filename.endswith(_ext.pyi):
3455
pass
35-
elif filename.endswith(EXTS[3]):
56+
elif filename.endswith(_ext.so):
3657
pass
3758
else:
3859
continue
@@ -44,6 +65,25 @@ def _get_files(files, ignored_dirnames = [], root = None):
4465

4566
return sorted([d for d in dirs if d not in ignored])
4667

47-
namespace_pkgs = struct(
48-
get_files = _get_files,
49-
)
68+
def create_inits(**kwargs):
69+
"""Create init files and return the list to be included `py_library` srcs.
70+
71+
Args:
72+
**kwargs: passed to {obj}`get_files`.
73+
74+
Returns:
75+
{type}`list[str]` to be included as part of `py_library`.
76+
"""
77+
srcs = []
78+
for out in get_files(**kwargs):
79+
src = "{}/__init__.py".format(out)
80+
srcs.append(srcs)
81+
82+
write_file(
83+
name = "_gen_{}_namespace".format(out),
84+
out = src,
85+
content = _INIT_CONTENTS,
86+
**kwargs
87+
)
88+
89+
return srcs

python/private/pypi/whl_installer/arguments.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,11 +57,6 @@ def parser(**kwargs: Any) -> argparse.ArgumentParser:
5757
action="store",
5858
help="Additional data exclusion parameters to add to the pip packages BUILD file.",
5959
)
60-
parser.add_argument(
61-
"--enable_implicit_namespace_pkgs",
62-
action="store_true",
63-
help="Disables conversion of implicit namespace packages into pkg-util style packages.",
64-
)
6560
parser.add_argument(
6661
"--environment",
6762
action="store",

python/private/pypi/whl_installer/namespace_pkgs.py

Lines changed: 0 additions & 121 deletions
This file was deleted.

python/private/pypi/whl_installer/wheel_installer.py

Lines changed: 1 addition & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727

2828
from pip._vendor.packaging.utils import canonicalize_name
2929

30-
from python.private.pypi.whl_installer import arguments, namespace_pkgs, wheel
30+
from python.private.pypi.whl_installer import arguments, wheel
3131

3232

3333
def _configure_reproducible_wheels() -> None:
@@ -77,35 +77,10 @@ def _parse_requirement_for_extra(
7777
return None, None
7878

7979

80-
def _setup_namespace_pkg_compatibility(wheel_dir: str) -> None:
81-
"""Converts native namespace packages to pkgutil-style packages
82-
83-
Namespace packages can be created in one of three ways. They are detailed here:
84-
https://packaging.python.org/guides/packaging-namespace-packages/#creating-a-namespace-package
85-
86-
'pkgutil-style namespace packages' (2) and 'pkg_resources-style namespace packages' (3) works in Bazel, but
87-
'native namespace packages' (1) do not.
88-
89-
We ensure compatibility with Bazel of method 1 by converting them into method 2.
90-
91-
Args:
92-
wheel_dir: the directory of the wheel to convert
93-
"""
94-
95-
namespace_pkg_dirs = namespace_pkgs.implicit_namespace_packages(
96-
wheel_dir,
97-
ignored_dirnames=["%s/bin" % wheel_dir],
98-
)
99-
100-
for ns_pkg_dir in namespace_pkg_dirs:
101-
namespace_pkgs.add_pkgutil_style_namespace_pkg_init(ns_pkg_dir)
102-
103-
10480
def _extract_wheel(
10581
wheel_file: str,
10682
extras: Dict[str, Set[str]],
10783
enable_pipstar: bool,
108-
enable_implicit_namespace_pkgs: bool,
10984
platforms: List[wheel.Platform],
11085
installation_dir: Path = Path("."),
11186
) -> None:
@@ -116,15 +91,11 @@ def _extract_wheel(
11691
installation_dir: the destination directory for installation of the wheel.
11792
extras: a list of extras to add as dependencies for the installed wheel
11893
enable_pipstar: if true, turns off certain operations.
119-
enable_implicit_namespace_pkgs: if true, disables conversion of implicit namespace packages and will unzip as-is
12094
"""
12195

12296
whl = wheel.Wheel(wheel_file)
12397
whl.unzip(installation_dir)
12498

125-
if not enable_implicit_namespace_pkgs:
126-
_setup_namespace_pkg_compatibility(installation_dir)
127-
12899
metadata = {
129100
"entry_points": [
130101
{
@@ -168,7 +139,6 @@ def main() -> None:
168139
wheel_file=whl,
169140
extras=extras,
170141
enable_pipstar=args.enable_pipstar,
171-
enable_implicit_namespace_pkgs=args.enable_implicit_namespace_pkgs,
172142
platforms=arguments.get_platforms(args),
173143
)
174144
return

python/private/pypi/whl_library.bzl

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,9 +173,6 @@ def _parse_optional_attrs(rctx, args, extra_pip_args = None):
173173
json.encode(struct(arg = rctx.attr.pip_data_exclude)),
174174
]
175175

176-
if rctx.attr.enable_implicit_namespace_pkgs:
177-
args.append("--enable_implicit_namespace_pkgs")
178-
179176
env = {}
180177
if rctx.attr.environment != None:
181178
for key, value in rctx.attr.environment.items():
@@ -389,6 +386,8 @@ def _whl_library_impl(rctx):
389386
metadata_name = metadata.name,
390387
metadata_version = metadata.version,
391388
requires_dist = metadata.requires_dist,
389+
# TODO @aignas 2025-05-17: maybe have a build flag for this instead
390+
enable_implicit_namespace_pkgs = rctx.attr.enable_implicit_namespace_pkgs,
392391
# TODO @aignas 2025-04-14: load through the hub:
393392
annotation = None if not rctx.attr.annotation else struct(**json.decode(rctx.read(rctx.attr.annotation))),
394393
data_exclude = rctx.attr.pip_data_exclude,
@@ -457,6 +456,8 @@ def _whl_library_impl(rctx):
457456
name = whl_path.basename,
458457
dep_template = rctx.attr.dep_template or "@{}{{name}}//:{{target}}".format(rctx.attr.repo_prefix),
459458
entry_points = entry_points,
459+
# TODO @aignas 2025-05-17: maybe have a build flag for this instead
460+
enable_implicit_namespace_pkgs = rctx.attr.enable_implicit_namespace_pkgs,
460461
# TODO @aignas 2025-04-14: load through the hub:
461462
dependencies = metadata["deps"],
462463
dependencies_by_platform = metadata["deps_by_platform"],

0 commit comments

Comments
 (0)