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