blob: 5c421e6f29cd1d1a780c851cb87aea328ac98a1c [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 = {
Serge Bazanskia1a96b42021-10-06 19:29:57 +020020 "GOROOT": go.root,
21 "GOTOOL": go.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.
33 runfiles = ctx.runfiles(files = [
34 go.go,
35 go.sdk_root,
36 ] + go.sdk_files)
37 source = {
38 key: getattr(source, key)
39 for key in dir(source)
Serge Bazanskia1a96b42021-10-06 19:29:57 +020040 if key not in ["to_json", "to_proto"]
Serge Bazanskiab4ef132021-09-24 13:58:13 +020041 }
Serge Bazanskia1a96b42021-10-06 19:29:57 +020042 source["runfiles"] = runfiles
Serge Bazanskiab4ef132021-09-24 13:58:13 +020043 source = GoSource(**source)
Serge Bazanskiab4ef132021-09-24 13:58:13 +020044
45 return [
46 library,
47 source,
Serge Bazanskiab4ef132021-09-24 13:58:13 +020048 OutputGroupInfo(
Serge Bazanskia1a96b42021-10-06 19:29:57 +020049 go_generated_srcs = depset([out]),
Serge Bazanskiab4ef132021-09-24 13:58:13 +020050 ),
51 ]
52
Serge Bazanskiab4ef132021-09-24 13:58:13 +020053toolchain_library = rule(
54 implementation = _toolchain_library_impl,
55 attrs = {
56 "importpath": attr.string(
57 mandatory = True,
58 ),
59 "deps": attr.label_list(),
60 "_template": attr.label(
61 allow_single_file = True,
62 default = ":toolchain.go.in",
63 ),
64 "_go_context_data": attr.label(
65 default = "@io_bazel_rules_go//:go_context_data",
66 ),
67 },
68 toolchains = ["@io_bazel_rules_go//go:toolchain"],
69)