• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""Module extension for bootstrapping cargo-bazel."""
2
3load("//crate_universe:deps_bootstrap.bzl", _cargo_bazel_bootstrap_repo_rule = "cargo_bazel_bootstrap")
4load("//rust/platform:triple.bzl", "get_host_triple")
5load("//rust/platform:triple_mappings.bzl", "system_to_binary_ext")
6
7def _cargo_bazel_bootstrap_impl(_):
8    _cargo_bazel_bootstrap_repo_rule(
9        rust_toolchain_cargo_template = "@rust_host_tools//:bin/{tool}",
10        rust_toolchain_rustc_template = "@rust_host_tools//:bin/{tool}",
11    )
12
13cargo_bazel_bootstrap = module_extension(
14    implementation = _cargo_bazel_bootstrap_impl,
15    doc = """Module extension to generate the cargo_bazel binary.""",
16)
17
18def get_host_cargo_rustc(module_ctx):
19    """A helper function to get the path to the host cargo and rustc binaries.
20
21    Args:
22        module_ctx: The module extension's context.
23    Returns:
24        A tuple of path to cargo, path to rustc.
25
26    """
27    host_triple = get_host_triple(module_ctx)
28    binary_ext = system_to_binary_ext(host_triple.system)
29
30    cargo_path = str(module_ctx.path(Label("@rust_host_tools//:bin/cargo{}".format(binary_ext))))
31    rustc_path = str(module_ctx.path(Label("@rust_host_tools//:bin/rustc{}".format(binary_ext))))
32    return cargo_path, rustc_path
33
34def get_cargo_bazel_runner(module_ctx, cargo_bazel):
35    """A helper function to allow executing cargo_bazel in module extensions.
36
37    Args:
38        module_ctx: The module extension's context.
39        cargo_bazel: Path The path to a `cargo-bazel` binary
40    Returns:
41        A function that can be called to execute cargo_bazel.
42    """
43    cargo_path, rustc_path = get_host_cargo_rustc(module_ctx)
44
45    # Placing this as a nested function allows users to call this right at the
46    # start of a module extension, thus triggering any restarts as early as
47    # possible (since module_ctx.path triggers restarts).
48    def run(args, env = {}, timeout = 600):
49        final_args = [cargo_bazel]
50        final_args.extend(args)
51        final_args.extend([
52            "--cargo",
53            cargo_path,
54            "--rustc",
55            rustc_path,
56        ])
57        result = module_ctx.execute(
58            final_args,
59            environment = dict(CARGO = cargo_path, RUSTC = rustc_path, **env),
60            timeout = timeout,
61        )
62        if result.return_code != 0:
63            if result.stdout:
64                print("Stdout:", result.stdout)  # buildifier: disable=print
65            pretty_args = " ".join([str(arg) for arg in final_args])
66            fail("%s returned with exit code %d:\n%s" % (pretty_args, result.return_code, result.stderr))
67        return result
68
69    return run
70