xref: /aosp_15_r20/build/bazel/rules/sh_binary.bzl (revision 7594170e27e0732bc44b93d1440d87a54b6ffe7c)
1ShBinaryInfo = provider(
2    "Info needed for sh_binary modules",
3    fields = {
4        "sub_dir": "Optional subdirectory to install into",
5        "filename": "Optional name for the installed file",
6    },
7)
8
9def sh_binary(
10        name,
11        srcs,
12        sub_dir = None,
13        filename = None,
14        tags = [],
15        **kwargs):
16    "Bazel macro to correspond with the sh_binary Soong module."
17
18    internal_name = name + "_internal"
19    native.sh_binary(
20        name = internal_name,
21        srcs = srcs,
22        tags = ["manual"],
23        **kwargs
24    )
25
26    # We need this wrapper rule around native.sh_binary in order to provide extra
27    # attributes such as filename and sub_dir that are useful when building apex.
28    _sh_binary_combiner(
29        name = name,
30        sub_dir = sub_dir,
31        filename = filename,
32        dep = internal_name,
33        tags = tags,
34    )
35
36def _sh_binary_combiner_impl(ctx):
37    dep = ctx.attr.dep[DefaultInfo]
38    output = ctx.outputs.executable
39
40    ctx.actions.run_shell(
41        outputs = [output],
42        inputs = [dep.files_to_run.executable],
43        command = "cp %s %s" % (dep.files_to_run.executable.path, output.path),
44        mnemonic = "CopyNativeShBinary",
45    )
46
47    files = depset(direct = [output], transitive = [dep.files])
48
49    return [
50        DefaultInfo(
51            files = files,
52            runfiles = ctx.runfiles().merge(dep.data_runfiles).merge(dep.default_runfiles),
53            executable = output,
54        ),
55        ShBinaryInfo(
56            sub_dir = ctx.attr.sub_dir,
57            filename = ctx.attr.filename,
58        ),
59    ]
60
61_sh_binary_combiner = rule(
62    implementation = _sh_binary_combiner_impl,
63    attrs = {
64        "sub_dir": attr.string(),
65        "filename": attr.string(),
66        "dep": attr.label(mandatory = True),
67    },
68    provides = [ShBinaryInfo],
69    executable = True,
70    doc = "Wrapper rule around native.sh_binary to provide extra attributes",
71)
72