fork/rules_rust

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

UebelAndreUpdated `attr.label` attribute defaults to use `Label` constructor (#1422)5a9d999d

0.8.0
8.9 KiB252 linesraw
1# Copyright 2018 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"""Rules for performing `rustdoc --test` on Bazel built crates"""
16
17load("//rust/private:common.bzl", "rust_common")
18load("//rust/private:providers.bzl", "CrateInfo")
19load("//rust/private:rustdoc.bzl", "rustdoc_compile_action")
20load("//rust/private:utils.bzl", "dedent", "find_toolchain", "transform_deps")
21
22def _construct_writer_arguments(ctx, test_runner, action, crate_info):
23    """Construct arguments and environment variables specific to `rustdoc_test_writer`.
24
25    This is largely solving for the fact that tests run from a runfiles directory
26    where actions run in an execroot. But it also tracks what environment variables
27    were explicitly added to the action.
28
29    Args:
30        ctx (ctx): The rule's context object.
31        test_runner (File): The test_runner output file declared by `rustdoc_test`.
32        action (struct): Action arguments generated by `rustdoc_compile_action`.
33        crate_info (CrateInfo): The provider of the crate who's docs are being tested.
34
35    Returns:
36        tuple: A tuple of `rustdoc_test_writer` specific inputs
37            - Args: Arguments for the test writer
38            - dict: Required environment variables
39    """
40
41    writer_args = ctx.actions.args()
42
43    # Track the output path where the test writer should write the test
44    writer_args.add("--output={}".format(test_runner.path))
45
46    # Track what environment variables should be written to the test runner
47    writer_args.add("--action_env=DEVELOPER_DIR")
48    writer_args.add("--action_env=PATHEXT")
49    writer_args.add("--action_env=SDKROOT")
50    writer_args.add("--action_env=SYSROOT")
51    for var in action.env.keys():
52        writer_args.add("--action_env={}".format(var))
53
54    # Since the test runner will be running from a runfiles directory, the
55    # paths originally generated for the build action will not map to any
56    # files. To ensure rustdoc can find the appropriate dependencies, the
57    # file roots are identified and tracked for each dependency so it can be
58    # stripped from the test runner.
59    for dep in crate_info.deps.to_list():
60        dep_crate_info = getattr(dep, "crate_info", None)
61        dep_dep_info = getattr(dep, "dep_info", None)
62        if dep_crate_info:
63            root = dep_crate_info.output.root.path
64            writer_args.add("--strip_substring={}/".format(root))
65        if dep_dep_info:
66            for direct_dep in dep_dep_info.direct_crates.to_list():
67                root = direct_dep.dep.output.root.path
68                writer_args.add("--strip_substring={}/".format(root))
69            for transitive_dep in dep_dep_info.transitive_crates.to_list():
70                root = transitive_dep.output.root.path
71                writer_args.add("--strip_substring={}/".format(root))
72
73    # Indicate that the rustdoc_test args are over.
74    writer_args.add("--")
75
76    # Prepare for the process runner to ingest the rest of the arguments
77    # to match the expectations of `rustc_compile_action`.
78    writer_args.add(ctx.executable._process_wrapper.short_path)
79
80    return (writer_args, action.env)
81
82def _rust_doc_test_impl(ctx):
83    """The implementation for the `rust_doc_test` rule
84
85    Args:
86        ctx (ctx): The rule's context object
87
88    Returns:
89        list: A list containing a DefaultInfo provider
90    """
91
92    toolchain = find_toolchain(ctx)
93
94    crate = ctx.attr.crate[rust_common.crate_info]
95    deps = transform_deps(ctx.attr.deps)
96
97    crate_info = rust_common.create_crate_info(
98        name = crate.name,
99        type = crate.type,
100        root = crate.root,
101        srcs = crate.srcs,
102        deps = depset(deps, transitive = [crate.deps]),
103        proc_macro_deps = crate.proc_macro_deps,
104        aliases = {},
105        output = crate.output,
106        edition = crate.edition,
107        rustc_env = crate.rustc_env,
108        is_test = True,
109        compile_data = crate.compile_data,
110        wrapped_crate_type = crate.type,
111        owner = ctx.label,
112    )
113
114    if toolchain.os == "windows":
115        test_runner = ctx.actions.declare_file(ctx.label.name + ".rustdoc_test.bat")
116    else:
117        test_runner = ctx.actions.declare_file(ctx.label.name + ".rustdoc_test.sh")
118
119    # Add the current crate as an extern for the compile action
120    rustdoc_flags = [
121        "--extern",
122        "{}={}".format(crate_info.name, crate_info.output.short_path),
123        "--test",
124    ]
125
126    action = rustdoc_compile_action(
127        ctx = ctx,
128        toolchain = toolchain,
129        crate_info = crate_info,
130        rustdoc_flags = rustdoc_flags,
131        is_test = True,
132    )
133
134    tools = action.tools + [ctx.executable._process_wrapper]
135
136    writer_args, env = _construct_writer_arguments(
137        ctx = ctx,
138        test_runner = test_runner,
139        action = action,
140        crate_info = crate_info,
141    )
142
143    # Allow writer environment variables to override those from the action.
144    action.env.update(env)
145
146    ctx.actions.run(
147        mnemonic = "RustdocTestWriter",
148        progress_message = "Generating Rustdoc test runner for {}".format(ctx.attr.crate.label),
149        executable = ctx.executable._test_writer,
150        inputs = action.inputs,
151        tools = tools,
152        arguments = [writer_args] + action.arguments,
153        env = action.env,
154        outputs = [test_runner],
155    )
156
157    return [DefaultInfo(
158        files = depset([test_runner]),
159        runfiles = ctx.runfiles(files = tools, transitive_files = action.inputs),
160        executable = test_runner,
161    )]
162
163rust_doc_test = rule(
164    implementation = _rust_doc_test_impl,
165    attrs = {
166        "crate": attr.label(
167            doc = (
168                "The label of the target to generate code documentation for. " +
169                "`rust_doc_test` can generate HTML code documentation for the " +
170                "source files of `rust_library` or `rust_binary` targets."
171            ),
172            providers = [rust_common.crate_info],
173            mandatory = True,
174        ),
175        "deps": attr.label_list(
176            doc = dedent("""\
177                List of other libraries to be linked to this library target.
178
179                These can be either other `rust_library` targets or `cc_library` targets if
180                linking a native library.
181            """),
182            providers = [CrateInfo, CcInfo],
183        ),
184        "_cc_toolchain": attr.label(
185            doc = (
186                "In order to use find_cc_toolchain, your rule has to depend " +
187                "on C++ toolchain. See @rules_cc//cc:find_cc_toolchain.bzl " +
188                "docs for details."
189            ),
190            default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
191        ),
192        "_process_wrapper": attr.label(
193            doc = "A process wrapper for running rustdoc on all platforms",
194            cfg = "exec",
195            default = Label("//util/process_wrapper"),
196            executable = True,
197        ),
198        "_test_writer": attr.label(
199            doc = "A binary used for writing script for use as the test executable.",
200            cfg = "exec",
201            default = Label("//tools/rustdoc:rustdoc_test_writer"),
202            executable = True,
203        ),
204    },
205    test = True,
206    fragments = ["cpp"],
207    host_fragments = ["cpp"],
208    toolchains = [
209        str(Label("//rust:toolchain")),
210        "@bazel_tools//tools/cpp:toolchain_type",
211    ],
212    incompatible_use_toolchain_transition = True,
213    doc = dedent("""\
214        Runs Rust documentation tests.
215
216        Example:
217
218        Suppose you have the following directory structure for a Rust library crate:
219
220        ```output
221        [workspace]/
222        WORKSPACE
223        hello_lib/
224            BUILD
225            src/
226                lib.rs
227        ```
228
229        To run [documentation tests][doc-test] for the `hello_lib` crate, define a `rust_doc_test` \
230        target that depends on the `hello_lib` `rust_library` target:
231
232        [doc-test]: https://doc.rust-lang.org/book/documentation.html#documentation-as-tests
233
234        ```python
235        package(default_visibility = ["//visibility:public"])
236
237        load("@rules_rust//rust:defs.bzl", "rust_library", "rust_doc_test")
238
239        rust_library(
240            name = "hello_lib",
241            srcs = ["src/lib.rs"],
242        )
243
244        rust_doc_test(
245            name = "hello_lib_doc_test",
246            crate = ":hello_lib",
247        )
248        ```
249
250        Running `bazel test //hello_lib:hello_lib_doc_test` will run all documentation tests for the `hello_lib` library crate.
251    """),
252)