blob: efd98a488dc8d8aa5f17c620e581e74584f8f999 [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
Serge Bazanskiab4ef132021-09-24 13:58:13 +020013 out = go.declare_file(go, ext = ".go")
14 ctx.actions.expand_template(
15 template = ctx.file._template,
16 output = out,
17 substitutions = {
Leopoldbc93c2b2023-01-14 13:12:23 +010018 "GOROOT": go.sdk.root_file.dirname,
Tim Windelschmidteda1e122025-01-09 05:42:53 +010019 "GOTOOL": go.sdk.go.path,
Serge Bazanskiab4ef132021-09-24 13:58:13 +020020 },
21 )
22
23 library = go.new_library(go)
24 source = go.library_to_source(go, struct(
25 srcs = [struct(files = [out])],
26 deps = ctx.attr.deps,
27 ), library, ctx.coverage_instrumented())
28
29 # Hack: we want to inject runfiles into the generated GoSource, because
30 # there's no other way to make rules_go pick up runfiles otherwise.
Tim Windelschmidteda1e122025-01-09 05:42:53 +010031 runfiles = ctx.runfiles(
32 [
33 go.sdk.go,
34 go.sdk.root_file,
35 ],
36 transitive_files = depset(transitive = [go.sdk.headers, go.sdk.srcs, go.sdk.libs, go.sdk.tools]),
37 )
Serge Bazanskiab4ef132021-09-24 13:58:13 +020038 source = {
39 key: getattr(source, key)
40 for key in dir(source)
Serge Bazanskia1a96b42021-10-06 19:29:57 +020041 if key not in ["to_json", "to_proto"]
Serge Bazanskiab4ef132021-09-24 13:58:13 +020042 }
Serge Bazanskia1a96b42021-10-06 19:29:57 +020043 source["runfiles"] = runfiles
Serge Bazanskiab4ef132021-09-24 13:58:13 +020044 source = GoSource(**source)
Serge Bazanskiab4ef132021-09-24 13:58:13 +020045
46 return [
47 library,
48 source,
Serge Bazanskiab4ef132021-09-24 13:58:13 +020049 OutputGroupInfo(
Serge Bazanskia1a96b42021-10-06 19:29:57 +020050 go_generated_srcs = depset([out]),
Serge Bazanskiab4ef132021-09-24 13:58:13 +020051 ),
52 ]
53
Serge Bazanskiab4ef132021-09-24 13:58:13 +020054toolchain_library = rule(
55 implementation = _toolchain_library_impl,
56 attrs = {
57 "importpath": attr.string(
58 mandatory = True,
59 ),
60 "deps": attr.label_list(),
61 "_template": attr.label(
62 allow_single_file = True,
63 default = ":toolchain.go.in",
64 ),
65 "_go_context_data": attr.label(
66 default = "@io_bazel_rules_go//:go_context_data",
67 ),
68 },
69 toolchains = ["@io_bazel_rules_go//go:toolchain"],
70)