blob: dbbba729b1a2ead7af9790241ab0df4c6ceb36f6 [file] [log] [blame]
Serge Bazanskia1a96b42021-10-06 19:29:57 +02001load("@io_bazel_rules_go//go:def.bzl", "GoSource", "go_context")
Serge Bazanskiab4ef132021-09-24 13:58:13 +02002
3# This implements the toolchain_library rule, which is used to generate a
4# rules_go compatible go_library-style target which contains toolchain.go.in
5# augmented with information about the Go SDK's toolchain used by Bazel.
6#
7# The library can then be used to build tools that call the `go` tool, for
8# example to perform static analysis or dependency management.
9
10def _toolchain_library_impl(ctx):
11 go = go_context(ctx)
12
13 importpath = ctx.attr.importpath
14
15 out = go.declare_file(go, ext = ".go")
16 ctx.actions.expand_template(
17 template = ctx.file._template,
18 output = out,
19 substitutions = {
Leopoldbc93c2b2023-01-14 13:12:23 +010020 "GOROOT": go.sdk.root_file.dirname,
Tim Windelschmidteda1e122025-01-09 05:42:53 +010021 "GOTOOL": go.sdk.go.path,
Serge Bazanskiab4ef132021-09-24 13:58:13 +020022 },
23 )
24
25 library = go.new_library(go)
26 source = go.library_to_source(go, struct(
27 srcs = [struct(files = [out])],
28 deps = ctx.attr.deps,
29 ), library, ctx.coverage_instrumented())
30
31 # Hack: we want to inject runfiles into the generated GoSource, because
32 # there's no other way to make rules_go pick up runfiles otherwise.
Tim Windelschmidteda1e122025-01-09 05:42:53 +010033 runfiles = ctx.runfiles(
34 [
35 go.sdk.go,
36 go.sdk.root_file,
37 ],
38 transitive_files = depset(transitive = [go.sdk.headers, go.sdk.srcs, go.sdk.libs, go.sdk.tools]),
39 )
Serge Bazanskiab4ef132021-09-24 13:58:13 +020040 source = {
41 key: getattr(source, key)
42 for key in dir(source)
Serge Bazanskia1a96b42021-10-06 19:29:57 +020043 if key not in ["to_json", "to_proto"]
Serge Bazanskiab4ef132021-09-24 13:58:13 +020044 }
Serge Bazanskia1a96b42021-10-06 19:29:57 +020045 source["runfiles"] = runfiles
Serge Bazanskiab4ef132021-09-24 13:58:13 +020046 source = GoSource(**source)
Serge Bazanskiab4ef132021-09-24 13:58:13 +020047
48 return [
49 library,
50 source,
Serge Bazanskiab4ef132021-09-24 13:58:13 +020051 OutputGroupInfo(
Serge Bazanskia1a96b42021-10-06 19:29:57 +020052 go_generated_srcs = depset([out]),
Serge Bazanskiab4ef132021-09-24 13:58:13 +020053 ),
54 ]
55
Serge Bazanskiab4ef132021-09-24 13:58:13 +020056toolchain_library = rule(
57 implementation = _toolchain_library_impl,
58 attrs = {
59 "importpath": attr.string(
60 mandatory = True,
61 ),
62 "deps": attr.label_list(),
63 "_template": attr.label(
64 allow_single_file = True,
65 default = ":toolchain.go.in",
66 ),
67 "_go_context_data": attr.label(
68 default = "@io_bazel_rules_go//:go_context_data",
69 ),
70 },
71 toolchains = ["@io_bazel_rules_go//go:toolchain"],
72)