xref: /aosp_15_r20/external/bazelbuild-rules_python/python/current_py_toolchain.bzl (revision 60517a1edbc8ecf509223e9af94a7adec7d736b8)
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"""Public entry point for current_py_toolchain rule."""
16
17load("//python/private:toolchain_types.bzl", "TARGET_TOOLCHAIN_TYPE")
18
19def _current_py_toolchain_impl(ctx):
20    toolchain = ctx.toolchains[ctx.attr._toolchain]
21
22    direct = []
23    transitive = []
24    vars = {}
25
26    if toolchain.py3_runtime and toolchain.py3_runtime.interpreter:
27        direct.append(toolchain.py3_runtime.interpreter)
28        transitive.append(toolchain.py3_runtime.files)
29        vars["PYTHON3"] = toolchain.py3_runtime.interpreter.path
30
31    if toolchain.py2_runtime and toolchain.py2_runtime.interpreter:
32        direct.append(toolchain.py2_runtime.interpreter)
33        transitive.append(toolchain.py2_runtime.files)
34        vars["PYTHON2"] = toolchain.py2_runtime.interpreter.path
35
36    files = depset(direct, transitive = transitive)
37    return [
38        toolchain,
39        platform_common.TemplateVariableInfo(vars),
40        DefaultInfo(
41            runfiles = ctx.runfiles(transitive_files = files),
42            files = files,
43        ),
44    ]
45
46current_py_toolchain = rule(
47    doc = """
48    This rule exists so that the current python toolchain can be used in the `toolchains` attribute of
49    other rules, such as genrule. It allows exposing a python toolchain after toolchain resolution has
50    happened, to a rule which expects a concrete implementation of a toolchain, rather than a
51    toolchain_type which could be resolved to that toolchain.
52    """,
53    implementation = _current_py_toolchain_impl,
54    attrs = {
55        "_toolchain": attr.string(default = str(TARGET_TOOLCHAIN_TYPE)),
56    },
57    toolchains = [
58        str(TARGET_TOOLCHAIN_TYPE),
59    ],
60)
61