xref: /aosp_15_r20/external/bazelbuild-rules_rust/rust/private/stamp.bzl (revision d4726bddaa87cc4778e7472feed243fa4b6c267f)
1"""A small utility module dedicated to detecting whether or not the `--stamp` flag is enabled
2
3This module can be removed likely after the following PRs ar addressed:
4- https://github.com/bazelbuild/bazel/issues/11164
5"""
6
7load("//rust/private:utils.bzl", "dedent")
8
9StampSettingInfo = provider(
10    doc = "Information about the `--stamp` command line flag",
11    fields = {
12        "value": "bool: Whether or not the `--stamp` flag was enabled",
13    },
14)
15
16def _stamp_build_setting_impl(ctx):
17    return StampSettingInfo(value = ctx.attr.value)
18
19_stamp_build_setting = rule(
20    doc = dedent("""\
21        Whether to encode build information into the binary. Possible values:
22
23        - stamp = 1: Always stamp the build information into the binary, even in [--nostamp][stamp] builds. \
24        This setting should be avoided, since it potentially kills remote caching for the binary and \
25        any downstream actions that depend on it.
26        - stamp = 0: Always replace build information by constant values. This gives good build result caching.
27        - stamp = -1: Embedding of build information is controlled by the [--[no]stamp][stamp] flag.
28
29        Stamped binaries are not rebuilt unless their dependencies change.
30        [stamp]: https://docs.bazel.build/versions/main/user-manual.html#flag--stamp
31    """),
32    implementation = _stamp_build_setting_impl,
33    attrs = {
34        "value": attr.bool(
35            doc = "The default value of the stamp build flag",
36            mandatory = True,
37        ),
38    },
39)
40
41def stamp_build_setting(name, visibility = ["//visibility:public"]):
42    native.config_setting(
43        name = "stamp_detect",
44        values = {"stamp": "1"},
45        visibility = visibility,
46    )
47
48    _stamp_build_setting(
49        name = name,
50        value = select({
51            ":stamp_detect": True,
52            "//conditions:default": False,
53        }),
54        visibility = visibility,
55    )
56
57def is_stamping_enabled(attr):
58    """Determine whether or not build stamping is enabled
59
60    Args:
61        attr (struct): A rule's struct of attributes (`ctx.attr`)
62
63    Returns:
64        bool: The stamp value
65    """
66    stamp_num = getattr(attr, "stamp", -1)
67    if stamp_num == 1:
68        return True
69    elif stamp_num == 0:
70        return False
71    elif stamp_num == -1:
72        stamp_flag = getattr(attr, "_stamp_flag", None)
73        return stamp_flag[StampSettingInfo].value if stamp_flag else False
74    else:
75        fail("Unexpected `stamp` value: {}".format(stamp_num))
76