1"""Bootstrap rustc process wrapper"""
2
3load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo")
4
5def _bootstrap_process_wrapper_impl_unix(ctx):
6    output = ctx.actions.declare_file("{}.sh".format(ctx.label.name))
7
8    setting = ctx.attr._use_sh_toolchain_for_bootstrap_process_wrapper[BuildSettingInfo].value
9    sh_toolchain = ctx.toolchains["@bazel_tools//tools/sh:toolchain_type"]
10    if setting and sh_toolchain:
11        shebang = "#!{}".format(sh_toolchain.path)
12        ctx.actions.expand_template(
13            output = output,
14            template = ctx.file._bash,
15            substitutions = {
16                # Replace the shebang with one constructed from the configured
17                # shell toolchain.
18                "#!/usr/bin/env bash": shebang,
19            },
20        )
21    else:
22        ctx.actions.symlink(
23            output = output,
24            target_file = ctx.file._bash,
25            is_executable = True,
26        )
27
28    return [DefaultInfo(
29        files = depset([output]),
30        executable = output,
31    )]
32
33def _bootstrap_process_wrapper_impl_windows(ctx):
34    output = ctx.actions.declare_file("{}.bat".format(ctx.label.name))
35    ctx.actions.symlink(
36        output = output,
37        target_file = ctx.file._batch,
38        is_executable = True,
39    )
40
41    return [DefaultInfo(
42        files = depset([output]),
43        executable = output,
44    )]
45
46def _bootstrap_process_wrapper_impl(ctx):
47    if ctx.attr.is_windows:
48        return _bootstrap_process_wrapper_impl_windows(ctx)
49    return _bootstrap_process_wrapper_impl_unix(ctx)
50
51bootstrap_process_wrapper = rule(
52    doc = "A rule which produces a bootstrapping script for the rustc process wrapper.",
53    implementation = _bootstrap_process_wrapper_impl,
54    attrs = {
55        "is_windows": attr.bool(
56            doc = "Indicate whether or not the target platform is windows.",
57            mandatory = True,
58        ),
59        "_bash": attr.label(
60            allow_single_file = True,
61            default = Label("//util/process_wrapper/private:process_wrapper.sh"),
62        ),
63        "_batch": attr.label(
64            allow_single_file = True,
65            default = Label("//util/process_wrapper/private:process_wrapper.bat"),
66        ),
67        "_use_sh_toolchain_for_bootstrap_process_wrapper": attr.label(
68            default = Label("//rust/settings:experimental_use_sh_toolchain_for_bootstrap_process_wrapper"),
69        ),
70    },
71    toolchains = [config_common.toolchain_type("@bazel_tools//tools/sh:toolchain_type", mandatory = False)],
72    executable = True,
73)
74