fork/rules_rust

git clone https://git.julia.blue/fork/rules_rust

UebelAndreAvoid double building `cargo_build_script.data` targets (#2826)cbdf5400

main
8.4 KiB210 linesraw
1"""Rules for Cargo build scripts (`build.rs` files)"""
2
3load(
4    "//cargo/private:cargo_build_script.bzl",
5    "cargo_build_script_runfiles",
6    "name_to_crate_name",
7    "name_to_pkg_name",
8    _build_script_run = "cargo_build_script",
9)
10load("//rust:defs.bzl", "rust_binary")
11
12def cargo_build_script(
13        name,
14        edition = None,
15        crate_name = None,
16        crate_root = None,
17        srcs = [],
18        crate_features = [],
19        version = None,
20        deps = [],
21        link_deps = [],
22        proc_macro_deps = [],
23        build_script_env = {},
24        data = [],
25        compile_data = [],
26        tools = [],
27        links = None,
28        rundir = None,
29        rustc_env = {},
30        rustc_env_files = [],
31        rustc_flags = [],
32        visibility = None,
33        tags = None,
34        aliases = None,
35        pkg_name = None,
36        **kwargs):
37    """Compile and execute a rust build script to generate build attributes
38
39    This rules take the same arguments as rust_binary.
40
41    Example:
42
43    Suppose you have a crate with a cargo build script `build.rs`:
44
45    ```output
46    [workspace]/
47        hello_lib/
48            BUILD
49            build.rs
50            src/
51                lib.rs
52    ```
53
54    Then you want to use the build script in the following:
55
56    `hello_lib/BUILD`:
57    ```python
58    package(default_visibility = ["//visibility:public"])
59
60    load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_library")
61    load("@rules_rust//cargo:defs.bzl", "cargo_build_script")
62
63    # This will run the build script from the root of the workspace, and
64    # collect the outputs.
65    cargo_build_script(
66        name = "build_script",
67        srcs = ["build.rs"],
68        # Optional environment variables passed during build.rs compilation
69        rustc_env = {
70           "CARGO_PKG_VERSION": "0.1.2",
71        },
72        # Optional environment variables passed during build.rs execution.
73        # Note that as the build script's working directory is not execroot,
74        # execpath/location will return an absolute path, instead of a relative
75        # one.
76        build_script_env = {
77            "SOME_TOOL_OR_FILE": "$(execpath @tool//:binary)"
78        },
79        # Optional data/tool dependencies
80        data = ["@tool//:binary"],
81    )
82
83    rust_library(
84        name = "hello_lib",
85        srcs = [
86            "src/lib.rs",
87        ],
88        deps = [":build_script"],
89    )
90    ```
91
92    The `hello_lib` target will be build with the flags and the environment variables declared by the \
93    build script in addition to the file generated by it.
94
95    Args:
96        name (str): The name for the underlying rule. This should be the name of the package
97            being compiled, optionally with a suffix of `_bs`. Otherwise, you can set the package name via `pkg_name`.
98        edition (str): The rust edition to use for the internal binary crate.
99        crate_name (str): Crate name to use for build script.
100        crate_root (label): The file that will be passed to rustc to be used for building this crate.
101        srcs (list of label): Souce files of the crate to build. Passing source files here can be used to trigger rebuilds when changes are made.
102        crate_features (list, optional): A list of features to enable for the build script.
103        version (str, optional): The semantic version (semver) of the crate.
104        deps (list, optional): The build-dependencies of the crate.
105        pkg_name (string, optional): Override the package name used for the build script. This is useful if the build target name gets too long otherwise.
106        link_deps (list, optional): The subset of the (normal) dependencies of the crate that have the
107            links attribute and therefore provide environment variables to this build script.
108        proc_macro_deps (list of label, optional): List of rust_proc_macro targets used to build the script.
109        build_script_env (dict, optional): Environment variables for build scripts.
110        data (list, optional): Files needed by the build script.
111        compile_data (list, optional): Files needed for the compilation of the build script.
112        tools (list, optional): Tools (executables) needed by the build script.
113        links (str, optional): Name of the native library this crate links against.
114        rundir (str, optional): A directory to `cd` to before the cargo_build_script is run. This should be a path relative to the exec root.
115
116            The default behaviour (and the behaviour if rundir is set to the empty string) is to change to the relative path corresponding to the cargo manifest directory, which replicates the normal behaviour of cargo so it is easy to write compatible build scripts.
117
118            If set to `.`, the cargo build script will run in the exec root.
119        rustc_env (dict, optional): Environment variables to set in rustc when compiling the build script.
120        rustc_env_files (list of label, optional): Files containing additional environment variables to set for rustc
121            when building the build script.
122        rustc_flags (list, optional): List of compiler flags passed to `rustc`.
123        visibility (list of label, optional): Visibility to apply to the generated build script output.
124        tags: (list of str, optional): Tags to apply to the generated build script output.
125        aliases (dict, optional): Remap crates to a new name or moniker for linkage to this target. \
126            These are other `rust_library` targets and will be presented as the new name given.
127        **kwargs: Forwards to the underlying `rust_binary` rule. An exception is the `compatible_with`
128            attribute, which shouldn't be forwarded to the `rust_binary`, as the `rust_binary` is only
129            built and used in `exec` mode. We propagate the `compatible_with` attribute to the `_build_scirpt_run`
130            target.
131    """
132
133    # This duplicates the code in _cargo_build_script_impl because we need to make these
134    # available both when we invoke rustc (this code) and when we run the compiled build
135    # script (_cargo_build_script_impl). https://github.com/bazelbuild/rules_rust/issues/661
136    # will hopefully remove this duplication.
137    if pkg_name == None:
138        pkg_name = name_to_pkg_name(name)
139
140    rustc_env = dict(rustc_env)
141    if "CARGO_PKG_NAME" not in rustc_env:
142        rustc_env["CARGO_PKG_NAME"] = pkg_name
143    if "CARGO_CRATE_NAME" not in rustc_env:
144        rustc_env["CARGO_CRATE_NAME"] = name_to_crate_name(name_to_pkg_name(name))
145
146    script_kwargs = {}
147    for arg in ("exec_compatible_with", "testonly"):
148        if arg in kwargs:
149            script_kwargs[arg] = kwargs[arg]
150
151    wrapper_kwargs = dict(script_kwargs)
152    for arg in ("compatible_with", "target_compatible_with"):
153        if arg in kwargs:
154            wrapper_kwargs[arg] = kwargs[arg]
155
156    binary_tags = depset(
157        (tags if tags else []) + ["manual"],
158    ).to_list()
159
160    # This target exists as the actual build script.
161    rust_binary(
162        name = name + "_",
163        crate_name = crate_name,
164        srcs = srcs,
165        crate_root = crate_root,
166        crate_features = crate_features,
167        deps = deps,
168        proc_macro_deps = proc_macro_deps,
169        data = tools,
170        compile_data = compile_data,
171        rustc_env = rustc_env,
172        rustc_env_files = rustc_env_files,
173        rustc_flags = rustc_flags,
174        edition = edition,
175        tags = binary_tags,
176        aliases = aliases,
177        **script_kwargs
178    )
179
180    # Because the build script is expected to be run on the exec host, the
181    # script above needs to be in the exec configuration but the script may
182    # need data files that are in the target configuration. This rule wraps
183    # the script above so the `cfg=exec` target can be run without issue in
184    # a `cfg=target` environment. More details can be found on the rule.
185    cargo_build_script_runfiles(
186        name = name + "-",
187        script = ":{}_".format(name),
188        data = data,
189        tools = tools,
190        tags = binary_tags,
191        **wrapper_kwargs
192    )
193
194    # This target executes the build script.
195    _build_script_run(
196        name = name,
197        script = ":{}-".format(name),
198        crate_features = crate_features,
199        version = version,
200        build_script_env = build_script_env,
201        links = links,
202        deps = deps,
203        link_deps = link_deps,
204        rundir = rundir,
205        rustc_flags = rustc_flags,
206        visibility = visibility,
207        tags = tags,
208        pkg_name = pkg_name,
209        **kwargs
210    )