• 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_cargo_bazel_runner(module_ctx):
19    """A helper function to allow executing cargo_bazel in module extensions.
20
21    Args:
22        module_ctx: The module extension's context.
23
24    Returns:
25        A function that can be called to execute cargo_bazel.
26    """
27
28    host_triple = get_host_triple(module_ctx)
29    binary_ext = system_to_binary_ext(host_triple.system)
30
31    cargo_path = str(module_ctx.path(Label("@rust_host_tools//:bin/cargo{}".format(binary_ext))))
32    rustc_path = str(module_ctx.path(Label("@rust_host_tools//:bin/rustc{}".format(binary_ext))))
33    cargo_bazel = module_ctx.path(Label("@cargo_bazel_bootstrap//:cargo-bazel"))
34
35    # Placing this as a nested function allows users to call this right at the
36    # start of a module extension, thus triggering any restarts as early as
37    # possible (since module_ctx.path triggers restarts).
38    def run(args, env = {}, timeout = 600):
39        final_args = [cargo_bazel]
40        final_args.extend(args)
41        final_args.extend([
42            "--cargo",
43            cargo_path,
44            "--rustc",
45            rustc_path,
46        ])
47        result = module_ctx.execute(
48            final_args,
49            environment = dict(CARGO = cargo_path, RUSTC = rustc_path, **env),
50            timeout = timeout,
51        )
52        if result.return_code != 0:
53            if result.stdout:
54                print("Stdout:", result.stdout)  # buildifier: disable=print
55            pretty_args = " ".join([str(arg) for arg in final_args])
56            fail("%s returned with exit code %d:\n%s" % (pretty_args, result.return_code, result.stderr))
57        return result
58
59    return run
60