blob: 1722cc4e6ac970cf71d926a2e7218f1a5b06cd50 [file] [log] [blame]
Serge Bazanskiab4ef132021-09-24 13:58:13 +02001load("@io_bazel_rules_go//go:def.bzl", "go_context", "GoSource")
2
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 = {
20 'GOROOT': go.root,
21 'GOTOOL': go.go.path,
22 },
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)
40 if key not in ['to_json', 'to_proto']
41 }
42 source['runfiles'] = runfiles
43 source = GoSource(**source)
44 archive = go.archive(go, source)
45
46
47 return [
48 library,
49 source,
50 archive,
51 DefaultInfo(
52 files = depset([archive.data.file]),
53 runfiles = runfiles,
54 ),
55 OutputGroupInfo(
56 cgo_exports = archive.cgo_exports,
57 compilation_outputs = [archive.data.file],
58 ),
59 ]
60
61
62toolchain_library = rule(
63 implementation = _toolchain_library_impl,
64 attrs = {
65 "importpath": attr.string(
66 mandatory = True,
67 ),
68 "deps": attr.label_list(),
69 "_template": attr.label(
70 allow_single_file = True,
71 default = ":toolchain.go.in",
72 ),
73 "_go_context_data": attr.label(
74 default = "@io_bazel_rules_go//:go_context_data",
75 ),
76 },
77 toolchains = ["@io_bazel_rules_go//go:toolchain"],
78)