• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2023 The Bazel Authors. All rights reserved
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"Repo rule used by bzlmod extension to create a repo that has a map of Python interpreters and their labels"
16
17load("//python:versions.bzl", "PLATFORMS")
18load(":text_util.bzl", "render")
19load(":toolchains_repo.bzl", "python_toolchain_build_file_content")
20
21def _have_same_length(*lists):
22    if not lists:
23        fail("expected at least one list")
24    return len({len(length): None for length in lists}) == 1
25
26_HUB_BUILD_FILE_TEMPLATE = """\
27load("@bazel_skylib//:bzl_library.bzl", "bzl_library")
28load("@@{rules_python}//python/private:py_toolchain_suite.bzl", "py_toolchain_suite")
29
30bzl_library(
31    name = "interpreters_bzl",
32    srcs = ["interpreters.bzl"],
33    visibility = ["@rules_python//:__subpackages__"],
34)
35
36bzl_library(
37    name = "versions_bzl",
38    srcs = ["versions.bzl"],
39    visibility = ["@rules_python//:__subpackages__"],
40)
41
42{toolchains}
43"""
44
45def _hub_build_file_content(
46        prefixes,
47        python_versions,
48        set_python_version_constraints,
49        user_repository_names,
50        workspace_location,
51        loaded_platforms):
52    """This macro iterates over each of the lists and returns the toolchain content.
53
54    python_toolchain_build_file_content is called to generate each of the toolchain
55    definitions.
56    """
57
58    if not _have_same_length(python_versions, set_python_version_constraints, user_repository_names):
59        fail("all lists must have the same length")
60
61    # Iterate over the length of python_versions and call
62    # build the toolchain content by calling python_toolchain_build_file_content
63    toolchains = "\n".join(
64        [
65            python_toolchain_build_file_content(
66                prefix = prefixes[i],
67                python_version = python_versions[i],
68                set_python_version_constraint = set_python_version_constraints[i],
69                user_repository_name = user_repository_names[i],
70                loaded_platforms = {
71                    k: v
72                    for k, v in PLATFORMS.items()
73                    if k in loaded_platforms[python_versions[i]]
74                },
75            )
76            for i in range(len(python_versions))
77        ],
78    )
79
80    return _HUB_BUILD_FILE_TEMPLATE.format(
81        toolchains = toolchains,
82        rules_python = workspace_location.workspace_name,
83    )
84
85_interpreters_bzl_template = """
86INTERPRETER_LABELS = {{
87{interpreter_labels}
88}}
89"""
90
91_line_for_hub_template = """\
92    "{name}_host": Label("@{name}_host//:python"),
93"""
94
95_versions_bzl_template = """
96DEFAULT_PYTHON_VERSION = "{default_python_version}"
97MINOR_MAPPING = {minor_mapping}
98PYTHON_VERSIONS = {python_versions}
99"""
100
101def _hub_repo_impl(rctx):
102    # Create the various toolchain definitions and
103    # write them to the BUILD file.
104    rctx.file(
105        "BUILD.bazel",
106        _hub_build_file_content(
107            rctx.attr.toolchain_prefixes,
108            rctx.attr.toolchain_python_versions,
109            rctx.attr.toolchain_set_python_version_constraints,
110            rctx.attr.toolchain_user_repository_names,
111            rctx.attr._rules_python_workspace,
112            rctx.attr.loaded_platforms,
113        ),
114        executable = False,
115    )
116
117    # Create a dict that is later used to create
118    # a symlink to a interpreter.
119    interpreter_labels = "".join([
120        _line_for_hub_template.format(name = name)
121        for name in rctx.attr.toolchain_user_repository_names
122    ])
123
124    rctx.file(
125        "interpreters.bzl",
126        _interpreters_bzl_template.format(
127            interpreter_labels = interpreter_labels,
128        ),
129        executable = False,
130    )
131
132    rctx.file(
133        "versions.bzl",
134        _versions_bzl_template.format(
135            default_python_version = rctx.attr.default_python_version,
136            minor_mapping = render.dict(rctx.attr.minor_mapping),
137            python_versions = rctx.attr.python_versions or render.list(sorted({
138                v: None
139                for v in rctx.attr.toolchain_python_versions
140            })),
141        ),
142        executable = False,
143    )
144
145hub_repo = repository_rule(
146    doc = """\
147This private rule create a repo with a BUILD file that contains a map of interpreter names
148and the labels to said interpreters. This map is used to by the interpreter hub extension.
149This rule also writes out the various toolchains for the different Python versions.
150""",
151    implementation = _hub_repo_impl,
152    attrs = {
153        "default_python_version": attr.string(
154            doc = "Default Python version for the build in `X.Y` or `X.Y.Z` format.",
155            mandatory = True,
156        ),
157        "loaded_platforms": attr.string_list_dict(
158            doc = "The list of loaded platforms keyed by the toolchain full python version",
159        ),
160        "minor_mapping": attr.string_dict(
161            doc = "The minor mapping of the `X.Y` to `X.Y.Z` format that is used in config settings.",
162            mandatory = True,
163        ),
164        "python_versions": attr.string_list(
165            doc = "The list of python versions to include in the `interpreters.bzl` if the toolchains are not specified. Used in `WORKSPACE` builds.",
166            mandatory = False,
167        ),
168        "toolchain_prefixes": attr.string_list(
169            doc = "List prefixed for the toolchains",
170            mandatory = True,
171        ),
172        "toolchain_python_versions": attr.string_list(
173            doc = "List of Python versions for the toolchains. In `X.Y.Z` format.",
174            mandatory = True,
175        ),
176        "toolchain_set_python_version_constraints": attr.string_list(
177            doc = "List of version contraints for the toolchains",
178            mandatory = True,
179        ),
180        "toolchain_user_repository_names": attr.string_list(
181            doc = "List of the user repo names for the toolchains",
182            mandatory = True,
183        ),
184        "_rules_python_workspace": attr.label(default = Label("//:does_not_matter_what_this_name_is")),
185    },
186)
187