fork/rules_rust

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

Parker Timmermancargo: Allow disabling the `default_shell_env` for build scripts (#3020)d58a8e77

main
26.0 KiB689 linesraw
1"""Rules for Cargo build scripts (`build.rs` files)"""
2
3load("@bazel_skylib//lib:paths.bzl", "paths")
4load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo")
5load("@bazel_tools//tools/cpp:toolchain_utils.bzl", "find_cpp_toolchain")
6load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES")
7load("//rust:defs.bzl", "rust_common")
8load("//rust:rust_common.bzl", "BuildInfo")
9
10# buildifier: disable=bzl-visibility
11load(
12    "//rust/private:rustc.bzl",
13    "get_compilation_mode_opts",
14    "get_linker_and_args",
15)
16
17# buildifier: disable=bzl-visibility
18load(
19    "//rust/private:utils.bzl",
20    "dedent",
21    "expand_dict_value_locations",
22    "find_cc_toolchain",
23    "find_toolchain",
24    _name_to_crate_name = "name_to_crate_name",
25)
26
27# Reexport for cargo_build_script_wrapper.bzl
28name_to_crate_name = _name_to_crate_name
29
30CargoBuildScriptRunfilesInfo = provider(
31    doc = "Info about a `cargo_build_script.script` target.",
32    fields = {
33        "data": "List[Target]: The raw `cargo_build_script_runfiles.data` attribute.",
34        "tools": "List[Target]: The raw `cargo_build_script_runfiles.tools` attribute.",
35    },
36)
37
38def _cargo_build_script_runfiles_impl(ctx):
39    script = ctx.executable.script
40
41    is_windows = script.extension == "exe"
42    exe = ctx.actions.declare_file("{}{}".format(ctx.label.name, ".exe" if is_windows else ""))
43
44    # Avoid the following issue on Windows when using builds-without-the-bytes.
45    # https://github.com/bazelbuild/bazel/issues/21747
46    if is_windows:
47        args = ctx.actions.args()
48        args.add(script)
49        args.add(exe)
50
51        ctx.actions.run(
52            executable = ctx.executable._copy_file,
53            arguments = [args],
54            inputs = [script],
55            outputs = [exe],
56        )
57    else:
58        ctx.actions.symlink(
59            output = exe,
60            target_file = script,
61            is_executable = True,
62        )
63
64    # Tools are ommitted here because they should be within the `script`
65    # attribute's runfiles.
66    runfiles = ctx.runfiles(files = ctx.files.data)
67
68    return [
69        DefaultInfo(
70            files = depset([exe]),
71            runfiles = runfiles.merge(ctx.attr.script[DefaultInfo].default_runfiles),
72            executable = exe,
73        ),
74        CargoBuildScriptRunfilesInfo(
75            data = ctx.attr.data,
76            tools = ctx.attr.tools,
77        ),
78    ]
79
80cargo_build_script_runfiles = rule(
81    doc = """\
82A rule for producing `cargo_build_script.script` with proper runfiles.
83
84This rule ensure's the executable for `cargo_build_script` has properly formed runfiles with `cfg=target` and
85`cfg=exec` files. This is a challenge becuase had the script binary been directly consumed, it would have been
86in either configuration which would have been incorrect for either the `tools` (exec) or `data` (target) attributes.
87This is solved here by consuming the script as exec and creating a symlink to consumers of this rule can consume
88with `cfg=target` and still get an exec compatible binary.
89
90This rule may not be necessary if it becomes possible to construct runfiles trees within a rule for an action as
91we'd be able to build the correct runfiles tree and configure the script runner to run the script in the new runfiles
92directory:
93https://github.com/bazelbuild/bazel/issues/15486
94""",
95    implementation = _cargo_build_script_runfiles_impl,
96    attrs = {
97        "data": attr.label_list(
98            doc = "Data required by the build script.",
99            allow_files = True,
100        ),
101        "script": attr.label(
102            doc = "The binary script to run, generally a `rust_binary` target.",
103            executable = True,
104            mandatory = True,
105            providers = [rust_common.crate_info],
106            cfg = "exec",
107        ),
108        "tools": attr.label_list(
109            doc = "Tools required by the build script.",
110            allow_files = True,
111            cfg = "exec",
112        ),
113        "_copy_file": attr.label(
114            cfg = "exec",
115            executable = True,
116            default = Label("//cargo/private:copy_file"),
117        ),
118    },
119    executable = True,
120)
121
122def get_cc_compile_args_and_env(cc_toolchain, feature_configuration):
123    """Gather cc environment variables from the given `cc_toolchain`
124
125    Args:
126        cc_toolchain (cc_toolchain): The current rule's `cc_toolchain`.
127        feature_configuration (FeatureConfiguration): Class used to construct command lines from CROSSTOOL features.
128
129    Returns:
130        tuple: A tuple of the following items:
131            - (sequence): A flattened C command line flags for given action.
132            - (sequence): A flattened CXX command line flags for given action.
133            - (dict): C environment variables to be set for given action.
134    """
135    compile_variables = cc_common.create_compile_variables(
136        feature_configuration = feature_configuration,
137        cc_toolchain = cc_toolchain,
138    )
139    cc_c_args = cc_common.get_memory_inefficient_command_line(
140        feature_configuration = feature_configuration,
141        action_name = ACTION_NAMES.c_compile,
142        variables = compile_variables,
143    )
144    cc_cxx_args = cc_common.get_memory_inefficient_command_line(
145        feature_configuration = feature_configuration,
146        action_name = ACTION_NAMES.cpp_compile,
147        variables = compile_variables,
148    )
149    cc_env = cc_common.get_environment_variables(
150        feature_configuration = feature_configuration,
151        action_name = ACTION_NAMES.c_compile,
152        variables = compile_variables,
153    )
154    return cc_c_args, cc_cxx_args, cc_env
155
156def _pwd_flags_sysroot(args):
157    """Prefix execroot-relative paths of known arguments with ${pwd}.
158
159    Args:
160        args (list): List of tool arguments.
161
162    Returns:
163        list: The modified argument list.
164    """
165    res = []
166    for arg in args:
167        s, opt, path = arg.partition("--sysroot=")
168        if s == "" and not paths.is_absolute(path):
169            res.append("{}${{pwd}}/{}".format(opt, path))
170        else:
171            res.append(arg)
172    return res
173
174def _pwd_flags_isystem(args):
175    """Prefix execroot-relative paths of known arguments with ${pwd}.
176
177    Args:
178        args (list): List of tool arguments.
179
180    Returns:
181        list: The modified argument list.
182    """
183    res = []
184    fix_next_arg = False
185    for arg in args:
186        if fix_next_arg and not paths.is_absolute(arg):
187            res.append("${{pwd}}/{}".format(arg))
188        else:
189            res.append(arg)
190
191        fix_next_arg = arg == "-isystem"
192
193    return res
194
195def _pwd_flags_fsanitize_ignorelist(args):
196    """Prefix execroot-relative paths of known arguments with ${pwd}.
197
198    Args:
199        args (list): List of tool arguments.
200
201    Returns:
202        list: The modified argument list.
203    """
204    res = []
205    for arg in args:
206        s, opt, path = arg.partition("-fsanitize-ignorelist=")
207        if s == "" and not paths.is_absolute(path):
208            res.append("{}${{pwd}}/{}".format(opt, path))
209        else:
210            res.append(arg)
211    return res
212
213def _pwd_flags(args):
214    return _pwd_flags_fsanitize_ignorelist(_pwd_flags_isystem(_pwd_flags_sysroot(args)))
215
216def _feature_enabled(ctx, feature_name, default = False):
217    """Check if a feature is enabled.
218
219    If the feature is explicitly enabled or disabled, return accordingly.
220
221    In the case where the feature is not explicitly enabled or disabled, return the default value.
222
223    Args:
224        ctx: The context object.
225        feature_name: The name of the feature.
226        default: The default value to return if the feature is not explicitly enabled or disabled.
227
228    Returns:
229        Boolean defining whether the feature is enabled.
230    """
231    if feature_name in ctx.disabled_features:
232        return False
233
234    if feature_name in ctx.features:
235        return True
236
237    return default
238
239def _rlocationpath(file, workspace_name):
240    if file.short_path.startswith("../"):
241        return file.short_path[len("../"):]
242
243    return "{}/{}".format(workspace_name, file.short_path)
244
245def _create_runfiles_dir(ctx, script, retain_list):
246    """Create a runfiles directory to represent `CARGO_MANIFEST_DIR`.
247
248    Due to the inability to forcibly generate runfiles directories for use as inputs
249    to actions, this function creates a custom runfiles directory that can more
250    consistently be relied upon as an input. For more details see:
251    https://github.com/bazelbuild/bazel/issues/15486
252
253    If runfiles directories can ever be more directly treated as an input this function
254    can be retired.
255
256    Args:
257        ctx (ctx): The rule's context object
258        script (Target): The `cargo_build_script.script` target.
259        retain_list (list): A list of strings to keep in generated runfiles directories.
260
261    Returns:
262        Tuple[File, Depset[File], Args]:
263            - The output directory to be created.
264            - Runfile inputs needed by the action.
265            - The args required to create the directory.
266    """
267    runfiles_dir = ctx.actions.declare_directory("{}.cargo_runfiles".format(ctx.label.name))
268
269    # External repos always fall into the `../` branch of `_rlocationpath`.
270    workspace_name = ctx.workspace_name
271
272    def _runfiles_map(file):
273        return "{}={}".format(file.path, _rlocationpath(file, workspace_name))
274
275    runfiles = script[DefaultInfo].default_runfiles
276
277    args = ctx.actions.args()
278    args.use_param_file("--cargo_manifest_args=@%s", use_always = True)
279    args.add(runfiles_dir.path)
280    args.add(",".join(retain_list))
281    args.add_all(runfiles.files, map_each = _runfiles_map, allow_closure = True)
282
283    return runfiles_dir, runfiles.files, args
284
285def _cargo_build_script_impl(ctx):
286    """The implementation for the `cargo_build_script` rule.
287
288    Args:
289        ctx (ctx): The rules context object
290
291    Returns:
292        list: A list containing a BuildInfo provider
293    """
294    script = ctx.executable.script
295    script_info = ctx.attr.script[CargoBuildScriptRunfilesInfo]
296    toolchain = find_toolchain(ctx)
297    out_dir = ctx.actions.declare_directory(ctx.label.name + ".out_dir")
298    env_out = ctx.actions.declare_file(ctx.label.name + ".env")
299    dep_env_out = ctx.actions.declare_file(ctx.label.name + ".depenv")
300    flags_out = ctx.actions.declare_file(ctx.label.name + ".flags")
301    link_flags = ctx.actions.declare_file(ctx.label.name + ".linkflags")
302    link_search_paths = ctx.actions.declare_file(ctx.label.name + ".linksearchpaths")  # rustc-link-search, propagated from transitive dependencies
303    compilation_mode_opt_level = get_compilation_mode_opts(ctx, toolchain).opt_level
304
305    script_tools = []
306    script_data = []
307    for target in script_info.data:
308        script_data.append(target[DefaultInfo].files)
309        script_data.append(target[DefaultInfo].default_runfiles.files)
310    for target in script_info.tools:
311        script_tools.append(target[DefaultInfo].files)
312        script_tools.append(target[DefaultInfo].default_runfiles.files)
313
314    workspace_name = ctx.label.workspace_name
315    if not workspace_name:
316        workspace_name = ctx.workspace_name
317
318    extra_args = []
319    extra_inputs = []
320    extra_output = []
321
322    # Relying on runfiles directories is unreliable when passing data to
323    # dependent actions. Instead, an explicit directory should be created
324    # until more reliable functionality is implemented in Bazel:
325    # https://github.com/bazelbuild/bazel/issues/15486
326    incompatible_runfiles_cargo_manifest_dir = ctx.attr._incompatible_runfiles_cargo_manifest_dir[BuildSettingInfo].value
327    if not incompatible_runfiles_cargo_manifest_dir:
328        script_data.append(ctx.attr.script[DefaultInfo].default_runfiles.files)
329        manifest_dir = "{}.runfiles/{}/{}".format(script.path, workspace_name, ctx.label.package)
330    else:
331        runfiles_dir, runfiles_inputs, runfiles_args = _create_runfiles_dir(
332            ctx = ctx,
333            script = ctx.attr.script,
334            retain_list = ctx.attr._cargo_manifest_dir_filename_suffixes_to_retain[BuildSettingInfo].value,
335        )
336        manifest_dir = "{}/{}/{}".format(runfiles_dir.path, workspace_name, ctx.label.package)
337        extra_args.append(runfiles_args)
338        extra_inputs.append(runfiles_inputs)
339        extra_output = [runfiles_dir]
340
341    pkg_name = ctx.attr.pkg_name
342    if pkg_name == "":
343        pkg_name = name_to_pkg_name(ctx.label.name)
344
345    toolchain_tools = [toolchain.all_files]
346
347    cc_toolchain = find_cpp_toolchain(ctx)
348
349    env = dict({})
350
351    # If enabled, start with the default shell env, which contains any --action_env
352    # settings passed in on the command line and defaults like $PATH.
353    if ctx.attr.use_default_shell_env:
354        env.update(ctx.configuration.default_shell_env)
355
356    env.update({
357        "CARGO_CRATE_NAME": name_to_crate_name(pkg_name),
358        "CARGO_MANIFEST_DIR": manifest_dir,
359        "CARGO_PKG_NAME": pkg_name,
360        "HOST": toolchain.exec_triple.str,
361        "NUM_JOBS": "1",
362        "OPT_LEVEL": compilation_mode_opt_level,
363        "RUSTC": toolchain.rustc.path,
364        "TARGET": toolchain.target_flag_value,
365        # OUT_DIR is set by the runner itself, rather than on the action.
366    })
367
368    # This isn't exactly right, but Bazel doesn't have exact views of "debug" and "release", so...
369    env.update({
370        "DEBUG": {"dbg": "true", "fastbuild": "true", "opt": "false"}.get(ctx.var["COMPILATION_MODE"], "true"),
371        "PROFILE": {"dbg": "debug", "fastbuild": "debug", "opt": "release"}.get(ctx.var["COMPILATION_MODE"], "unknown"),
372    })
373
374    if ctx.attr.version:
375        version = ctx.attr.version.split("+")[0].split(".")
376        patch = version[2].split("-") if len(version) > 2 else [""]
377        env["CARGO_PKG_VERSION_MAJOR"] = version[0]
378        env["CARGO_PKG_VERSION_MINOR"] = version[1] if len(version) > 1 else ""
379        env["CARGO_PKG_VERSION_PATCH"] = patch[0]
380        env["CARGO_PKG_VERSION_PRE"] = patch[1] if len(patch) > 1 else ""
381        env["CARGO_PKG_VERSION"] = ctx.attr.version
382
383    # Pull in env vars which may be required for the cc_toolchain to work (e.g. on OSX, the SDK version).
384    # We hope that the linker env is sufficient for the whole cc_toolchain.
385    cc_toolchain, feature_configuration = find_cc_toolchain(ctx)
386    linker, link_args, linker_env = get_linker_and_args(ctx, "bin", cc_toolchain, feature_configuration, None)
387    env.update(**linker_env)
388    env["LD"] = linker
389    env["LDFLAGS"] = " ".join(_pwd_flags(link_args))
390
391    # MSVC requires INCLUDE to be set
392    cc_c_args, cc_cxx_args, cc_env = get_cc_compile_args_and_env(cc_toolchain, feature_configuration)
393    include = cc_env.get("INCLUDE")
394    if include:
395        env["INCLUDE"] = include
396
397    if cc_toolchain:
398        toolchain_tools.append(cc_toolchain.all_files)
399
400        env["CC"] = cc_common.get_tool_for_action(
401            feature_configuration = feature_configuration,
402            action_name = ACTION_NAMES.c_compile,
403        )
404        env["CXX"] = cc_common.get_tool_for_action(
405            feature_configuration = feature_configuration,
406            action_name = ACTION_NAMES.cpp_compile,
407        )
408        env["AR"] = cc_common.get_tool_for_action(
409            feature_configuration = feature_configuration,
410            action_name = ACTION_NAMES.cpp_link_static_library,
411        )
412
413        # Populate CFLAGS and CXXFLAGS that cc-rs relies on when building from source, in particular
414        # to determine the deployment target when building for apple platforms (`macosx-version-min`
415        # for example, itself derived from the `macos_minimum_os` Bazel argument).
416        env["CFLAGS"] = " ".join(_pwd_flags(cc_c_args))
417        env["CXXFLAGS"] = " ".join(_pwd_flags(cc_cxx_args))
418
419    # Inform build scripts of rustc flags
420    # https://github.com/rust-lang/cargo/issues/9600
421    env["CARGO_ENCODED_RUSTFLAGS"] = "\\x1f".join([
422        # Allow build scripts to locate the generated sysroot
423        "--sysroot=${{pwd}}/{}".format(toolchain.sysroot),
424    ] + ctx.attr.rustc_flags)
425
426    for f in ctx.attr.crate_features:
427        env["CARGO_FEATURE_" + f.upper().replace("-", "_")] = "1"
428
429    links = ctx.attr.links or ""
430    if links:
431        env["CARGO_MANIFEST_LINKS"] = links
432
433    # Add environment variables from the Rust toolchain.
434    env.update(toolchain.env)
435
436    known_variables = {}
437
438    # Gather data from the `toolchains` attribute.
439    for target in ctx.attr.toolchains:
440        if DefaultInfo in target:
441            toolchain_tools.extend([
442                target[DefaultInfo].files,
443                target[DefaultInfo].default_runfiles.files,
444            ])
445        if platform_common.ToolchainInfo in target:
446            all_files = getattr(target[platform_common.ToolchainInfo], "all_files", depset([]))
447            if type(all_files) == "list":
448                all_files = depset(all_files)
449            toolchain_tools.append(all_files)
450        if platform_common.TemplateVariableInfo in target:
451            variables = getattr(target[platform_common.TemplateVariableInfo], "variables", depset([]))
452            known_variables.update(variables)
453
454    _merge_env_dict(env, expand_dict_value_locations(
455        ctx,
456        ctx.attr.build_script_env,
457        getattr(ctx.attr, "data", []) +
458        getattr(ctx.attr, "compile_data", []) +
459        getattr(ctx.attr, "tools", []) +
460        script_info.data +
461        script_info.tools,
462        known_variables,
463    ))
464
465    tools = depset(
466        direct = [
467            script,
468            ctx.executable._cargo_build_script_runner,
469        ] + ([toolchain.target_json] if toolchain.target_json else []),
470        transitive = script_data + script_tools + toolchain_tools,
471    )
472
473    # dep_env_file contains additional environment variables coming from
474    # direct dependency sys-crates' build scripts. These need to be made
475    # available to the current crate build script.
476    # See https://doc.rust-lang.org/cargo/reference/build-scripts.html#-sys-packages
477    # for details.
478    args = ctx.actions.args()
479    args.add(script, format = "--script=%s")
480    args.add(links, format = "--links=%s")
481    args.add(out_dir.path, format = "--out_dir=%s")
482    args.add(env_out, format = "--env_out=%s")
483    args.add(flags_out, format = "--flags_out=%s")
484    args.add(link_flags, format = "--link_flags=%s")
485    args.add(link_search_paths, format = "--link_search_paths=%s")
486    args.add(dep_env_out, format = "--dep_env_out=%s")
487    args.add(ctx.attr.rundir, format = "--rundir=%s")
488
489    output_groups = {
490        "out_dir": depset([out_dir]),
491    }
492
493    debug_std_streams_output_group = ctx.attr._debug_std_streams_output_group[BuildSettingInfo].value
494    if debug_std_streams_output_group:
495        debug_stdout = ctx.actions.declare_file(ctx.label.name + ".stdout.log")
496        debug_stderr = ctx.actions.declare_file(ctx.label.name + ".stderr.log")
497        args.add(debug_stdout, format = "--stdout=%s")
498        args.add(debug_stderr, format = "--stderr=%s")
499        extra_output.append(debug_stdout)
500        extra_output.append(debug_stderr)
501        output_groups["streams"] = depset([debug_stdout, debug_stderr])
502
503    build_script_inputs = []
504
505    for dep in ctx.attr.link_deps:
506        if rust_common.dep_info in dep and dep[rust_common.dep_info].dep_env:
507            dep_env_file = dep[rust_common.dep_info].dep_env
508            args.add(dep_env_file.path, format = "--input_dep_env_path=%s")
509            build_script_inputs.append(dep_env_file)
510            for dep_build_info in dep[rust_common.dep_info].transitive_build_infos.to_list():
511                build_script_inputs.append(dep_build_info.out_dir)
512
513    for dep in ctx.attr.deps:
514        for dep_build_info in dep[rust_common.dep_info].transitive_build_infos.to_list():
515            build_script_inputs.append(dep_build_info.out_dir)
516
517    experimental_symlink_execroot = ctx.attr._experimental_symlink_execroot[BuildSettingInfo].value or \
518                                    _feature_enabled(ctx, "symlink-exec-root")
519
520    if experimental_symlink_execroot:
521        env["RULES_RUST_SYMLINK_EXEC_ROOT"] = "1"
522
523    ctx.actions.run(
524        executable = ctx.executable._cargo_build_script_runner,
525        arguments = [args] + extra_args,
526        outputs = [
527            out_dir,
528            env_out,
529            flags_out,
530            link_flags,
531            link_search_paths,
532            dep_env_out,
533        ] + extra_output,
534        tools = tools,
535        inputs = depset(build_script_inputs, transitive = extra_inputs),
536        mnemonic = "CargoBuildScriptRun",
537        progress_message = "Running Cargo build script {}".format(pkg_name),
538        env = env,
539        toolchain = None,
540        # If enabled, sets the $PATH environment variable so tools like `cmake`
541        # can probe $PATH for helper tools. Defaults to `True`.
542        use_default_shell_env = ctx.attr.use_default_shell_env,
543    )
544
545    return [
546        # Although this isn't used anywhere, without this, `bazel build`'ing
547        # the cargo_build_script label won't actually run the build script
548        # since bazel is lazy.
549        DefaultInfo(files = depset([out_dir])),
550        BuildInfo(
551            out_dir = out_dir,
552            rustc_env = env_out,
553            dep_env = dep_env_out,
554            flags = flags_out,
555            linker_flags = link_flags,
556            link_search_paths = link_search_paths,
557            compile_data = depset(extra_output, transitive = script_data),
558        ),
559        OutputGroupInfo(
560            **output_groups
561        ),
562    ]
563
564cargo_build_script = rule(
565    doc = (
566        "A rule for running a crate's `build.rs` files to generate build information " +
567        "which is then used to determine how to compile said crate."
568    ),
569    implementation = _cargo_build_script_impl,
570    attrs = {
571        "build_script_env": attr.string_dict(
572            doc = "Environment variables for build scripts.",
573        ),
574        "crate_features": attr.string_list(
575            doc = "The list of rust features that the build script should consider activated.",
576        ),
577        "deps": attr.label_list(
578            doc = "The Rust build-dependencies of the crate",
579            providers = [rust_common.dep_info],
580            cfg = "exec",
581        ),
582        "link_deps": attr.label_list(
583            doc = dedent("""\
584                The subset of the Rust (normal) dependencies of the crate that
585                have the links attribute and therefore provide environment
586                variables to this build script.
587            """),
588            providers = [rust_common.dep_info],
589        ),
590        "links": attr.string(
591            doc = "The name of the native library this crate links against.",
592        ),
593        "pkg_name": attr.string(
594            doc = "The name of package being compiled, if not derived from `name`.",
595        ),
596        "rundir": attr.string(
597            default = "",
598            doc = dedent("""\
599                A directory to cd to before the cargo_build_script is run.
600
601                This should be a pathrelative to the exec root. The default behaviour (and the
602                behaviour if rundir is set to the empty string) is to change to the relative
603                path corresponding to the cargo manifest directory, which replicates the
604                normal behaviour of cargo so it is easy to write compatible build scripts.
605
606                If set to `.`, the cargo build script will run in the exec root.
607            """),
608        ),
609        "rustc_flags": attr.string_list(
610            doc = dedent("""\
611                List of compiler flags passed to `rustc`.
612
613                These strings are subject to Make variable expansion for predefined
614                source/output path variables like `$location`, `$execpath`, and
615                `$rootpath`. This expansion is useful if you wish to pass a generated
616                file of arguments to rustc: `@$(location //package:target)`.
617            """),
618        ),
619        "script": attr.label(
620            doc = "The binary script to run, generally a `rust_binary` target.",
621            executable = True,
622            mandatory = True,
623            cfg = "target",
624            providers = [CargoBuildScriptRunfilesInfo],
625        ),
626        "tools": attr.label_list(
627            doc = "Tools required by the build script.",
628            allow_files = True,
629            cfg = "exec",
630        ),
631        "use_default_shell_env": attr.bool(
632            doc = dedent("""\
633                Whether or not to include the default shell environment for the build
634                script action. By default Bazel's `default_shell_env` is set for build
635                script actions so crates like `cmake` can probe $PATH to find tools.
636            """),
637            default = True,
638        ),
639        "version": attr.string(
640            doc = "The semantic version (semver) of the crate",
641        ),
642        "_cargo_build_script_runner": attr.label(
643            executable = True,
644            allow_files = True,
645            default = Label("//cargo/cargo_build_script_runner:cargo_build_script_runner"),
646            cfg = "exec",
647        ),
648        "_cargo_manifest_dir_filename_suffixes_to_retain": attr.label(
649            default = Label("//cargo/settings:cargo_manifest_dir_filename_suffixes_to_retain"),
650        ),
651        "_cc_toolchain": attr.label(
652            default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
653        ),
654        "_debug_std_streams_output_group": attr.label(
655            default = Label("//cargo/settings:debug_std_streams_output_group"),
656        ),
657        "_experimental_symlink_execroot": attr.label(
658            default = Label("//cargo/settings:experimental_symlink_execroot"),
659        ),
660        "_incompatible_runfiles_cargo_manifest_dir": attr.label(
661            default = Label("//cargo/settings:incompatible_runfiles_cargo_manifest_dir"),
662        ),
663    },
664    fragments = ["cpp"],
665    toolchains = [
666        str(Label("//rust:toolchain_type")),
667        "@bazel_tools//tools/cpp:toolchain_type",
668    ],
669)
670
671def _merge_env_dict(prefix_dict, suffix_dict):
672    """Merges suffix_dict into prefix_dict, appending rather than replacing certain env vars."""
673    for key in ["CFLAGS", "CXXFLAGS", "LDFLAGS"]:
674        if key in prefix_dict and key in suffix_dict and prefix_dict[key]:
675            prefix_dict[key] += " " + suffix_dict.pop(key)
676    prefix_dict.update(suffix_dict)
677
678def name_to_pkg_name(name):
679    """Sanitize the name of cargo_build_script targets.
680
681    Args:
682        name (str): The name value pass to the `cargo_build_script` wrapper.
683
684    Returns:
685        str: A cleaned up name for a build script target.
686    """
687    if name.endswith("_bs"):
688        return name[:-len("_bs")]
689    return name