|
| 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 | +"copy_to_bin() rule" |
| 16 | + |
| 17 | +load("//third_party/github.com/bazelbuild/bazel-skylib:rules/private/copy_file_private.bzl", "copy_bash", "copy_cmd") |
| 18 | + |
| 19 | +def _copy_to_bin_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 | + if ctx.attr.is_windows: |
| 26 | + copy_cmd(ctx, src, dst) |
| 27 | + else: |
| 28 | + copy_bash(ctx, src, dst) |
| 29 | + all_dst.append(dst) |
| 30 | + return DefaultInfo(files = depset(all_dst), runfiles = ctx.runfiles(files = all_dst)) |
| 31 | + |
| 32 | +_copy_to_bin = rule( |
| 33 | + implementation = _copy_to_bin_impl, |
| 34 | + attrs = { |
| 35 | + "srcs": attr.label_list(mandatory = True, allow_files = True), |
| 36 | + "is_windows": attr.bool(mandatory = True, doc = "Automatically set by macro"), |
| 37 | + }, |
| 38 | +) |
| 39 | + |
| 40 | +def copy_to_bin(name, srcs, **kwargs): |
| 41 | + """Copies a source file to bazel-bin at the same workspace-relative path path. |
| 42 | +
|
| 43 | + e.g. `<workspace_root>/foo/bar/a.txt -> <bazel-bin>/foo/bar/a.txt` |
| 44 | +
|
| 45 | + This is useful to populate the output folder with all files needed at runtime, even |
| 46 | + those which aren't outputs of a Bazel rule. |
| 47 | +
|
| 48 | + This way you can run a binary in the output folder (execroot or runfiles_root) |
| 49 | + without that program needing to rely on a runfiles helper library or be aware that |
| 50 | + files are divided between the source tree and the output tree. |
| 51 | +
|
| 52 | + Args: |
| 53 | + name: Name of the rule. |
| 54 | + srcs: A List of Labels. File(s) to to copy. |
| 55 | + **kwargs: further keyword arguments, e.g. `visibility` |
| 56 | + """ |
| 57 | + _copy_to_bin( |
| 58 | + name = name, |
| 59 | + srcs = srcs, |
| 60 | + is_windows = select({ |
| 61 | + "@bazel_tools//src/conditions:host_windows": True, |
| 62 | + "//conditions:default": False, |
| 63 | + }), |
| 64 | + **kwargs |
| 65 | + ) |
0 commit comments