Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(bzlmod): support entry_point in bzlmod hub repos #1294

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 0 additions & 46 deletions docs/pip_repository.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 7 additions & 4 deletions examples/bzlmod/MODULE.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@ use_repo(pip, "whl_mods_hub")
# Because we do not have a python_version defined here
# pip.parse uses the python toolchain that is set as default.
pip.parse(
entry_points = {
"yamllint": ["yamllint"],
},
hub_name = "pip",
requirements_lock = "//:requirements_lock_3_9.txt",
requirements_windows = "//:requirements_windows_3_9.txt",
Expand All @@ -106,6 +109,9 @@ pip.parse(
},
)
pip.parse(
entry_points = {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rickeylev, instead of entry_point macros, what do you think about the following extension API? You can see the bzlmod example entry_point test for how it works.

"yamllint": ["yamllint"],
},
hub_name = "pip",
python_version = "3.10",
requirements_lock = "//:requirements_lock_3_10.txt",
Expand All @@ -118,10 +124,7 @@ pip.parse(
"@whl_mods_hub//:wheel.json": "wheel",
},
)

# NOTE: The pip_39 repo is only used because the plain `@pip` repo doesn't
# yet support entry points; see https://github.com/bazelbuild/rules_python/issues/1262
use_repo(pip, "pip", "pip_39")
use_repo(pip, "pip")

bazel_dep(name = "other_module", version = "", repo_name = "our_other_module")
local_path_override(
Expand Down
3 changes: 1 addition & 2 deletions examples/bzlmod/entry_point/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
load("@pip_39//:requirements.bzl", "entry_point")
load("@rules_python//python:defs.bzl", "py_test")

alias(
name = "yamllint",
actual = entry_point("yamllint"),
actual = "@pip//yamllint/bin:yamllint",
)

py_test(
Expand Down
69 changes: 29 additions & 40 deletions python/extensions/pip.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,16 @@
"pip module extension for use with bzlmod"

load("@pythons_hub//:interpreters.bzl", "DEFAULT_PYTHON_VERSION", "INTERPRETER_LABELS")
load("@rules_python//python:pip.bzl", "whl_library_alias")
load(
"@rules_python//python/pip_install:pip_repository.bzl",
"locked_requirements_label",
"pip_hub_repository_bzlmod",
"pip_repository_attrs",
"pip_repository_bzlmod",
"use_isolated",
"whl_library",
)
load("@rules_python//python/pip_install:requirements_parser.bzl", parse_requirements = "parse")
load("//python/extensions/private:pip_hub_repository.bzl", "pip_hub_repository")
load("//python/private:full_version.bzl", "full_version")
load("//python/private:normalize_name.bzl", "normalize_name")
load("//python/private:version_label.bzl", "version_label")

Expand Down Expand Up @@ -111,18 +110,11 @@ def _create_versioned_pip_and_whl_repos(module_ctx, pip_attr, whl_map):
requirements = parse_result.requirements
extra_pip_args = pip_attr.extra_pip_args + parse_result.options

# Create the repository where users load the `requirement` macro. Under bzlmod
# this does not create the install_deps() macro.
# TODO: we may not need this repository once we have entry points
# supported. For now a user can access this repository and use
# the entrypoint functionality.
pip_repository_bzlmod(
name = pip_name,
repo_name = pip_name,
requirements_lock = pip_attr.requirements_lock,
)
if hub_name not in whl_map:
whl_map[hub_name] = {}
whl_map[hub_name] = struct(
wheels = {},
entry_points = {},
)

whl_modifications = {}
if pip_attr.whl_modifications != None:
Expand Down Expand Up @@ -154,10 +146,20 @@ def _create_versioned_pip_and_whl_repos(module_ctx, pip_attr, whl_map):
environment = pip_attr.environment,
)

if whl_name not in whl_map[hub_name]:
whl_map[hub_name][whl_name] = {}
if whl_name not in whl_map[hub_name].wheels:
whl_map[hub_name].wheels[whl_name] = []

whl_map[hub_name].wheels[whl_name].append(full_version(pip_attr.python_version))

for whl_name, scripts in pip_attr.entry_points.items():
if whl_name not in whl_map[hub_name].entry_points:
whl_map[hub_name].entry_points[whl_name] = {}

for script in scripts:
if script not in whl_map[hub_name].entry_points[whl_name]:
whl_map[hub_name].entry_points[whl_name][script] = []

whl_map[hub_name][whl_name][pip_attr.python_version] = pip_name + "_"
whl_map[hub_name].entry_points[whl_name][script].append(full_version(pip_attr.python_version))

def _pip_impl(module_ctx):
"""Implementation of a class tag that creates the pip hub(s) and corresponding pip spoke, alias and whl repositories.
Expand Down Expand Up @@ -295,36 +297,23 @@ def _pip_impl(module_ctx):
_create_versioned_pip_and_whl_repos(module_ctx, pip_attr, hub_whl_map)

for hub_name, whl_map in hub_whl_map.items():
for whl_name, version_map in whl_map.items():
if DEFAULT_PYTHON_VERSION not in version_map:
fail((
"Default python version '{version}' missing in pip " +
"hub '{hub}': update your pip.parse() calls so that " +
'includes `python_version = "{version}"`'
).format(
version = DEFAULT_PYTHON_VERSION,
hub = hub_name,
))

# Create the alias repositories which contains different select
# statements These select statements point to the different pip
# whls that are based on a specific version of Python.
whl_library_alias(
name = hub_name + "_" + whl_name,
wheel_name = whl_name,
default_version = DEFAULT_PYTHON_VERSION,
version_map = version_map,
)

# Create the hub repository for pip.
pip_hub_repository_bzlmod(
pip_hub_repository(
name = hub_name,
repo_name = hub_name,
whl_library_alias_names = whl_map.keys(),
whl_map = whl_map.wheels,
whl_entry_points = {
whl_name: json.encode(values)
for whl_name, values in whl_map.entry_points.items()
},
default_version = full_version(DEFAULT_PYTHON_VERSION),
)

def _pip_parse_ext_attrs():
attrs = dict({
"entry_points": attr.string_list_dict(
doc = "TODO",
),
"hub_name": attr.string(
mandatory = True,
doc = """
Expand Down
103 changes: 103 additions & 0 deletions python/extensions/private/pip_hub_repository.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Copyright 2023 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
A pip_hub_repository rule used to create bzlmod hub repos for PyPI packages.

It assumes that version aware toolchain is used and is responsible for setting up
aliases for entry points and the actual package targets.
"""

load("//python/private:render_pkg_aliases.bzl", "render_pkg_aliases")

_BUILD_FILE_CONTENTS = """\
package(default_visibility = ["//visibility:public"])

# Ensure the `requirements.bzl` source can be accessed by stardoc, since users load() from it
exports_files(["requirements.bzl"])
"""

def _impl(rctx):
bzl_packages = rctx.attr.whl_map.keys()
repo_name = rctx.attr.repo_name

aliases = render_pkg_aliases(
repo_name = repo_name,
whl_map = rctx.attr.whl_map,
whl_entry_points = {
whl_name: json.decode(values)
for whl_name, values in rctx.attr.whl_entry_points.items()
},
default_version = rctx.attr.default_version,
rules_python = rctx.attr._template.workspace_name,
)
for path, contents in aliases.items():
rctx.file(path, contents)

# NOTE: we are using the canonical name with the double '@' in order to
# always uniquely identify a repository, as the labels are being passed as
# a string and the resolution of the label happens at the call-site of the
# `requirement`, et al. macros.
macro_tmpl = "@@{name}//{{}}:{{}}".format(name = rctx.attr.name)

rctx.file("BUILD.bazel", _BUILD_FILE_CONTENTS)
rctx.template("requirements.bzl", rctx.attr._template, substitutions = {
"%%ALL_DATA_REQUIREMENTS%%": repr([
macro_tmpl.format(p, "data")
for p in bzl_packages
]),
"%%ALL_REQUIREMENTS%%": repr([
macro_tmpl.format(p, p)
for p in bzl_packages
]),
"%%ALL_WHL_REQUIREMENTS%%": repr([
macro_tmpl.format(p, "whl")
for p in bzl_packages
]),
"%%DEFAULT_PY_VERSION%%": repr(rctx.attr.default_version),
"%%MACRO_TMPL%%": macro_tmpl,
"%%NAME%%": rctx.attr.name,
"%%PACKAGE_AVAILABILITY%%": repr({
k: [v for v in versions]
for k, versions in rctx.attr.whl_map.items()
}),
"%%RULES_PYTHON%%": rctx.attr._template.workspace_name,
})

pip_hub_repository = repository_rule(
attrs = {
"default_version": attr.string(
mandatory = True,
doc = """\
This is the default python version in the format of X.Y.Z. This should match
what is setup by the 'python' extension using the 'is_default = True'
setting.""",
),
"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.",
),
"whl_entry_points": attr.string_dict(
mandatory = False,
doc = "The entry points that we will create aliases for.",
),
"whl_map": attr.string_list_dict(
mandatory = True,
doc = "The wheel map where values are python versions",
),
"_template": attr.label(default = ":requirements.bzl.tmpl"),
},
doc = """A rule for creating bzlmod hub repo for PyPI packages. PRIVATE USE ONLY.""",
implementation = _impl,
)
11 changes: 3 additions & 8 deletions python/extensions/private/pythons_hub.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@

"Repo rule used by bzlmod extension to create a repo that has a map of Python interpreters and their labels"

load("//python:versions.bzl", "MINOR_MAPPING", "WINDOWS_NAME")
load("//python:versions.bzl", "WINDOWS_NAME")
load("//python/private:full_version.bzl", "full_version")
load(
"//python/private:toolchains_repo.bzl",
"get_host_os_arch",
Expand All @@ -28,12 +29,6 @@ def _have_same_length(*lists):
fail("expected at least one list")
return len({len(length): None for length in lists}) == 1

def _get_version(python_version):
# we need to get the MINOR_MAPPING or use the full version
if python_version in MINOR_MAPPING:
python_version = MINOR_MAPPING[python_version]
return python_version

def _python_toolchain_build_file_content(
prefixes,
python_versions,
Expand All @@ -55,7 +50,7 @@ def _python_toolchain_build_file_content(
# build the toolchain content by calling python_toolchain_build_file_content
return "\n".join([python_toolchain_build_file_content(
prefix = prefixes[i],
python_version = _get_version(python_versions[i]),
python_version = full_version(python_versions[i]),
set_python_version_constraint = set_python_version_constraints[i],
user_repository_name = user_repository_names[i],
rules_python = rules_python,
Expand Down
Loading