blob: c696564e5189461f32467a8ba23701be27d3ffa7 [file] [log] [blame]
Tim Windelschmidt25e0d8f2024-12-02 23:46:24 +01001load("@bazel_skylib//lib:paths.bzl", "paths")
2
3def _build_with_tag_transition_impl(settings, attr):
4 """
5 Transition that enables pure, static build of Go binaries.
6 """
7 tags = settings["@io_bazel_rules_go//go/config:tags"]
8
9 return {
10 "@io_bazel_rules_go//go/config:tags": tags + attr.gotags,
11 }
12
13build_with_tag_transition = transition(
14 implementation = _build_with_tag_transition_impl,
15 inputs = [
16 "@io_bazel_rules_go//go/config:tags",
17 ],
18 outputs = [
19 "@io_bazel_rules_go//go/config:tags",
20 ],
21)
22
23def _go_binary_with_tag_impl(ctx):
24 # We need to forward the DefaultInfo provider from the underlying rule.
25 # Unfortunately, we can't do this directly, because Bazel requires that the executable to run
26 # is actually generated by this rule, so we need to symlink to it, and generate a synthetic
27 # forwarding DefaultInfo.
28
29 result = []
30 binary = ctx.attr.binary[0]
31
32 default_info = binary[DefaultInfo]
33 new_executable = None
34 original_executable = default_info.files_to_run.executable
35
36 if not original_executable:
37 fail("Cannot transition a 'binary' that is not executable")
38
39 # In order for the symlink to have the same basename as the original
40 # executable (important in the case of proto plugins), put it in a
41 # subdirectory named after the label to prevent collisions.
42 new_executable = ctx.actions.declare_file(paths.join(ctx.label.name, original_executable.basename))
43 ctx.actions.symlink(
44 output = new_executable,
45 target_file = original_executable,
46 is_executable = True,
47 )
48
49 result.append(
50 DefaultInfo(
51 files = depset(direct = [new_executable]),
52 executable = new_executable,
53 ),
54 )
55
56 return result
57
58go_binary_with_tag = rule(
59 implementation = _go_binary_with_tag_impl,
60 attrs = {
61 "binary": attr.label(
62 mandatory = True,
63 cfg = build_with_tag_transition,
64 ),
65 "gotags": attr.string_list(),
66 },
67)