• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright (C) 2022 The Android Open Source Project
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"""Impl of `embedded_exec`."""
16
17load("@bazel_skylib//lib:shell.bzl", "shell")
18load(":exec_aspect.bzl", "ExecAspectInfo", "exec_aspect")
19
20visibility([
21    "//build/bazel_common_rules/exec/...",
22    "//build/bazel_common_rules/dist/...",
23])
24
25def _impl(ctx):
26    target = ctx.attr.actual
27    files_to_run = target[DefaultInfo].files_to_run
28    if not files_to_run or not files_to_run.executable:
29        fail("{}: {} is not an executable".format(ctx.label, target))
30
31    out_file = ctx.actions.declare_file(ctx.label.name)
32
33    content = "#!{}\n".format(ctx.attr.hashbang)
34
35    expand_location_targets = []
36    for dependant_attr in ("data", "srcs", "deps"):
37        dependants = getattr(target[ExecAspectInfo], dependant_attr)
38        if dependants:
39            expand_location_targets += dependants
40
41    args = target[ExecAspectInfo].args
42    if not args:
43        args = []
44    quoted_args = " ".join([shell.quote(ctx.expand_location(arg, expand_location_targets)) for arg in args])
45
46    env = target[ExecAspectInfo].env
47    if not env:
48        env = {}
49
50    quoted_env = " ".join(["{}={}".format(k, shell.quote(ctx.expand_location(v, expand_location_targets))) for k, v in env.items()])
51
52    content += '{} {} {} "$@"'.format(quoted_env, target[DefaultInfo].files_to_run.executable.short_path, quoted_args)
53
54    ctx.actions.write(out_file, content, is_executable = True)
55
56    runfiles = ctx.runfiles(files = ctx.files.actual)
57    runfiles = runfiles.merge_all([target[DefaultInfo].default_runfiles])
58
59    return DefaultInfo(
60        files = depset([out_file]),
61        executable = out_file,
62        runfiles = runfiles,
63    )
64
65embedded_exec = rule(
66    implementation = _impl,
67    attrs = {
68        "actual": attr.label(doc = "The actual executable.", aspects = [exec_aspect]),
69        "hashbang": attr.string(doc = "The hashbang of the script", default = "/bin/bash -e"),
70    },
71    executable = True,
72)
73