xref: /aosp_15_r20/external/bazelbuild-rules_python/python/py_import.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 py_import rule."""
16
17load(":py_info.bzl", "PyInfo")
18
19def _py_import_impl(ctx):
20    # See https://github.com/bazelbuild/bazel/blob/0.24.0/src/main/java/com/google/devtools/build/lib/bazel/rules/python/BazelPythonSemantics.java#L104 .
21    import_paths = [
22        "/".join([ctx.workspace_name, x.short_path])
23        for x in ctx.files.srcs
24    ]
25
26    return [
27        DefaultInfo(
28            default_runfiles = ctx.runfiles(ctx.files.srcs, collect_default = True),
29        ),
30        PyInfo(
31            transitive_sources = depset(transitive = [
32                dep[PyInfo].transitive_sources
33                for dep in ctx.attr.deps
34            ]),
35            imports = depset(direct = import_paths, transitive = [
36                dep[PyInfo].imports
37                for dep in ctx.attr.deps
38            ]),
39        ),
40    ]
41
42py_import = rule(
43    doc = """This rule allows the use of Python packages as dependencies.
44
45    It imports the given `.egg` file(s), which might be checked in source files,
46    fetched externally as with `http_file`, or produced as outputs of other rules.
47
48    It may be used like a `py_library`, in the `deps` of other Python rules.
49
50    This is similar to [java_import](https://docs.bazel.build/versions/master/be/java.html#java_import).
51    """,
52    implementation = _py_import_impl,
53    attrs = {
54        "deps": attr.label_list(
55            doc = "The list of other libraries to be linked in to the " +
56                  "binary target.",
57            providers = [PyInfo],
58        ),
59        "srcs": attr.label_list(
60            doc = "The list of Python package files provided to Python targets " +
61                  "that depend on this target. Note that currently only the .egg " +
62                  "format is accepted. For .whl files, try the whl_library rule. " +
63                  "We accept contributions to extend py_import to handle .whl.",
64            allow_files = [".egg"],
65        ),
66    },
67)
68