• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2025 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://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, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""Copies a source file to bazel-bin at the same workspace-relative path."""
15
16# buildifier: disable=bzl-visibility
17load("@bazel_skylib//rules/private:copy_file_private.bzl", "copy_bash", "copy_cmd")
18
19def _copy_to_bin_impl(ctx):
20    all_dst = []
21    for src in ctx.files.srcs:
22        dst = ctx.actions.declare_file(src.basename, sibling = src)
23        if ctx.attr.is_windows:
24            copy_cmd(ctx, src, dst)
25        else:
26            copy_bash(ctx, src, dst)
27        all_dst.append(dst)
28    return DefaultInfo(files = depset(all_dst), runfiles = ctx.runfiles(files = all_dst))
29
30_copy_to_bin = rule(
31    implementation = _copy_to_bin_impl,
32    attrs = {
33        "is_windows": attr.bool(mandatory = True, doc = "Automatically set by macro"),
34        "srcs": attr.label_list(mandatory = True, allow_files = True),
35    },
36)
37
38def copy_to_bin(name, srcs, **kwargs):
39    """Copies a source file to bazel-bin at the same workspace-relative path.
40
41    Although aspect_bazel_libs includes a copy_to_bin but we cannot use
42    it for now since some downstream projects don't use bzlmods and don't
43    load aspect libs at all. Until then, we keep a local copy of this here.
44    We only need copy_to_bin due to unusual limitations of rules_js and Node,
45    see https://github.com/aspect-build/rules_js/blob/main/docs/README.md#javascript
46
47    e.g. `<workspace_root>/pw_web/main.ts -> <bazel-bin>/pw_web/main.ts`
48
49    Args:
50        name: Name of the rule.
51        srcs: A List of Labels. File(s) to to copy.
52        **kwargs: further keyword arguments, e.g. `visibility`
53    """
54    _copy_to_bin(
55        name = name,
56        srcs = srcs,
57        is_windows = select({
58            "@bazel_tools//src/conditions:host_windows": True,
59            "//conditions:default": False,
60        }),
61        **kwargs
62    )
63