|
| 1 | +# Copyright 2019 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 | +"""Implementation of copy_to_bin macro and underlying rules.""" |
| 16 | + |
| 17 | +load(":copy_file.bzl", "copy_file_action") |
| 18 | + |
| 19 | +def _impl(ctx): |
| 20 | + all_dst = [] |
| 21 | + for src in ctx.files.srcs: |
| 22 | + if not src.is_source: |
| 23 | + fail("A source file must be specified in copy_to_bin rule, %s is not a source file." % src.path) |
| 24 | + dst = ctx.actions.declare_file(src.basename, sibling = src) |
| 25 | + copy_file_action(ctx, src, dst, is_windows = ctx.attr.is_windows) |
| 26 | + all_dst.append(dst) |
| 27 | + return DefaultInfo( |
| 28 | + files = depset(all_dst), |
| 29 | + runfiles = ctx.runfiles(files = all_dst), |
| 30 | + ) |
| 31 | + |
| 32 | +_copy_to_bin = rule( |
| 33 | + implementation = _impl, |
| 34 | + provides = [DefaultInfo], |
| 35 | + attrs = { |
| 36 | + "is_windows": attr.bool(mandatory = True), |
| 37 | + "srcs": attr.label_list(mandatory = True, allow_files = True), |
| 38 | + }, |
| 39 | +) |
| 40 | + |
| 41 | +def copy_to_bin(name, srcs, **kwargs): |
| 42 | + """Copies a source file to output tree at the same workspace-relative path. |
| 43 | +
|
| 44 | + e.g. `<execroot>/path/to/file -> <execroot>/bazel-out/<platform>/bin/path/to/file` |
| 45 | +
|
| 46 | + This is useful to populate the output folder with all files needed at runtime, even |
| 47 | + those which aren't outputs of a Bazel rule. |
| 48 | +
|
| 49 | + This way you can run a binary in the output folder (execroot or runfiles_root) |
| 50 | + without that program needing to rely on a runfiles helper library or be aware that |
| 51 | + files are divided between the source tree and the output tree. |
| 52 | +
|
| 53 | + Args: |
| 54 | + name: Name of the rule. |
| 55 | + srcs: A list of labels. File(s) to copy. |
| 56 | + **kwargs: further keyword arguments, e.g. `visibility` |
| 57 | + """ |
| 58 | + _copy_to_bin( |
| 59 | + name = name, |
| 60 | + srcs = srcs, |
| 61 | + is_windows = select({ |
| 62 | + "@bazel_tools//src/conditions:host_windows": True, |
| 63 | + "//conditions:default": False, |
| 64 | + }), |
| 65 | + **kwargs |
| 66 | + ) |
0 commit comments