xref: /aosp_15_r20/external/bazelbuild-platforms/experimental/platform_data/defs.bzl (revision ef3a692c0746f7dadd4fb3b5728d17696f151f9c)
1"""
2The platform_data rule can be used to change the target platform of a target,
3and then depend on that elsewhere in the build tree. For example:
4load("@platforms//experimental/platform_data:defs.bzl", "platform_data")
5
6cc_binary(name = "foo")
7
8platform_data(
9    name = "foo_embedded",
10    target = ":foo",
11    platform = "//my/new:platform",
12)
13
14py_binary(
15    name = "flasher",
16    srcs = ...,
17    data = [
18        ":foo_embedded",
19    ],
20)
21
22Regardless of what platform the top-level :flasher binary is built for,
23the :foo_embedded target will be built for //my/new:platform.
24
25Note that if you depend on :foo_embedded it's not exactly the same as depending on :foo, since it won't forward all the same providers. In the future, we can extend this to add some common providers as needed."""
26
27def _target_platform_transition_impl(attr):
28    return {
29        "//command_line_option:platforms": str(attr.platform),
30    }
31
32_target_platform_transition = transition(
33    implementation = _target_platform_transition_impl,
34    inputs = [],
35    outputs = [
36        "//command_line_option:platforms",
37    ],
38)
39
40def _platform_data_impl(ctx):
41    target = ctx.attr.target
42
43    default_info = target[DefaultInfo]
44    files = default_info.files
45    original_executable = default_info.files_to_run.executable
46    runfiles = default_info.default_runfiles
47
48    new_executable = ctx.actions.declare_file(ctx.attr.name)
49
50    ctx.actions.symlink(
51        output = new_executable,
52        target_file = original_executable,
53        is_executable = True,
54    )
55
56    files = depset(direct = [new_executable], transitive = [files])
57    runfiles = runfiles.merge(ctx.runfiles([new_executable]))
58
59    return [
60	DefaultInfo(
61            files = files,
62            runfiles = runfiles,
63            executable = new_executable,
64	)
65    ]
66
67platform_data = rule(
68    implementation = _platform_data_impl,
69    attrs = {
70        "target": attr.label(
71            allow_files = False,
72            executable = True,
73            mandatory = True,
74            cfg = _target_platform_transition,
75        ),
76        "platform": attr.label(
77            mandatory = True,
78        ),
79        "_allowlist_function_transition": attr.label(
80            default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
81        ),
82    },
83    executable = True,
84)
85
86