1Go rules for Bazel_
2=====================
3
4.. Links to external sites and pages
5.. _//tests/core/cross: https://github.com/bazelbuild/rules_go/blob/master/tests/core/cross/BUILD.bazel
6.. _Avoiding conflicts: proto/core.rst#avoiding-conflicts
7.. _Bazel labels: https://docs.bazel.build/versions/master/build-ref.html#labels
8.. _Bazel: https://bazel.build/
9.. _Build modes: go/modes.rst
10.. _Bzlmod: https://bazel.build/external/overview#bzlmod
11.. _Go with Bzlmod: docs/go/core/bzlmod.md
12.. _Core rules: docs/go/core/rules.md
13.. _Coverage: https://bazel.google.cn/docs/coverage
14.. _Dependencies: go/dependencies.rst
15.. _Deprecation schedule: https://github.com/bazelbuild/rules_go/wiki/Deprecation-schedule
16.. _Gopher Slack: https://invite.slack.golangbridge.org/
17.. _gopls integration: https://github.com/bazelbuild/rules_go/wiki/Editor-setup
18.. _Overriding dependencies: go/dependencies.rst#overriding-dependencies
19.. _Proto dependencies: go/dependencies.rst#proto-dependencies
20.. _Proto rules: proto/core.rst
21.. _Protocol buffers: proto/core.rst
22.. _Running Bazel Tests on Travis CI: https://kev.inburke.com/kevin/bazel-tests-on-travis-ci/
23.. _Toolchains: go/toolchains.rst
24.. _Using rules_go on Windows: windows.rst
25.. _bazel-go-discuss: https://groups.google.com/forum/#!forum/bazel-go-discuss
26.. _configuration transition: https://docs.bazel.build/versions/master/skylark/lib/transition.html
27.. _gRPC dependencies: go/dependencies.rst#grpc-dependencies
28.. _gazelle update-repos: https://github.com/bazelbuild/bazel-gazelle#update-repos
29.. _gazelle: https://github.com/bazelbuild/bazel-gazelle
30.. _github.com/bazelbuild/bazel-gazelle: https://github.com/bazelbuild/bazel-gazelle
31.. _github.com/bazelbuild/rules_go/go/tools/bazel: https://pkg.go.dev/github.com/bazelbuild/rules_go/go/tools/bazel?tab=doc
32.. _korfuri/bazel-travis Use Bazel with Travis CI: https://github.com/korfuri/bazel-travis
33.. _nogo build-time static analysis: go/nogo.rst
34.. _nogo: go/nogo.rst
35.. _rules_go and Gazelle roadmap: https://github.com/bazelbuild/rules_go/wiki/Roadmap
36.. _#bazel on Go Slack: https://gophers.slack.com/archives/C1SCQE54N
37.. _#go on Bazel Slack: https://bazelbuild.slack.com/archives/CDBP88Z0D
38
39.. Go rules
40.. _go_binary: docs/go/core/rules.md#go_binary
41.. _go_context: go/toolchains.rst#go_context
42.. _go_download_sdk: go/toolchains.rst#go_download_sdk
43.. _go_host_sdk: go/toolchains.rst#go_host_sdk
44.. _go_library: docs/go/core/rules.md#go_library
45.. _go_local_sdk: go/toolchains.rst#go_local_sdk
46.. _go_path: docs/go/core/rules.md#go_path
47.. _go_proto_compiler: proto/core.rst#go_proto_compiler
48.. _go_proto_library: proto/core.rst#go_proto_library
49.. _go_register_toolchains: go/toolchains.rst#go_register_toolchains
50.. _go_repository: https://github.com/bazelbuild/bazel-gazelle/blob/master/repository.md#go_repository
51.. _go_rules_dependencies: go/dependencies.rst#go_rules_dependencies
52.. _go_source: docs/go/core/rules.md#go_source
53.. _go_test: docs/go/core/rules.md#go_test
54.. _go_cross_binary: docs/go/core/rules.md#go_cross_binary
55.. _go_toolchain: go/toolchains.rst#go_toolchain
56.. _go_wrap_sdk: go/toolchains.rst#go_wrap_sdk
57.. _gomock: docs/go/extras/extras.md#gomock
58
59.. External rules
60.. _git_repository: https://docs.bazel.build/versions/master/repo/git.html
61.. _http_archive: https://docs.bazel.build/versions/master/repo/http.html#http_archive
62.. _proto_library: https://github.com/bazelbuild/rules_proto
63
64.. Issues
65.. _#265: https://github.com/bazelbuild/rules_go/issues/265
66.. _#721: https://github.com/bazelbuild/rules_go/issues/721
67.. _#889: https://github.com/bazelbuild/rules_go/issues/889
68.. _#1199: https://github.com/bazelbuild/rules_go/issues/1199
69.. _#2775: https://github.com/bazelbuild/rules_go/issues/2775
70
71
72Mailing list: `bazel-go-discuss`_
73
74Slack: `#go on Bazel Slack`_, `#bazel on Go Slack`_
75
76Announcements
77-------------
782024-01-04
79 Release
80 `v0.44.2 <https://github.com/bazelbuild/rules_go/releases/tag/v0.44.2>`_
81 is now available. This includes two bug fixes (https://github.com/bazelbuild/rules_go/pull/3808 and https://github.com/bazelbuild/rules_go/pull/3810) with
82 the test timeout handler.
83
842023-12-29
85 Release
86 `v0.44.1 <https://github.com/bazelbuild/rules_go/releases/tag/v0.43.0>`_
87 is now available. This release reverts a forced upgrade (https://github.com/bazelbuild/rules_go/pull/3803) of genproto from
88 `v0.44.0`.
89
902023-12-15
91 Release
92 `v0.44.0 <https://github.com/bazelbuild/rules_go/releases/tag/v0.43.0>`_
93 is now available. This release adds a stacktrace when a test times out and
94 adds support for nogo in Bzlmod.
95
962023-11-20
97 Release
98 `v0.43.0 <https://github.com/bazelbuild/rules_go/releases/tag/v0.43.0>`_
99 is now available. This release fixes a couple bugs and upgrades `x/tools`
100 to the latest version.
101
1022023-09-28
103 Release
104 `v0.42.0 <https://github.com/bazelbuild/rules_go/releases/tag/v0.42.0>`_
105 is now available. This release fixes a couple bugs and adds support for
106 patching the standard library.
107
1082023-07-10
109 Release
110 `v0.41.0 <https://github.com/bazelbuild/rules_go/releases/tag/v0.41.0>`_
111 is now available. rules_go no longer ship with `@go_googleapis` repo.
112 It requires Gazelle v0.32.0 or later.
113
1142023-06-28
115 Release
116 `v0.40.1 <https://github.com/bazelbuild/rules_go/releases/tag/v0.40.1>`_
117 is now available. This release fixes a couple bugs in
118 the go packages driver that were introduced in 0.40.0.
119
1202023-06-22
121 Release
122 `v0.40.0 <https://github.com/bazelbuild/rules_go/releases/tag/v0.40.0>`_
123 is now available. This release includes support for `//nolint` parsing,
124 as well as a large set of additional changes. Please check the release notes
125 for details.
126
1272023-03-27
128 Release
129 `v0.39.0 <https://github.com/bazelbuild/rules_go/releases/tag/v0.39.0>`_
130 is now available. This release includes a simpler interface for Bzlmod
131 `go_sdk` registration, makes the `//go` tool available to users, and
132 fixes various bugs.
133
1342022-12-06
135 Release
136 `v0.37.0 <https://github.com/bazelbuild/rules_go/releases/tag/v0.37.0>`_
137 is now available. This release includes support for generated code in
138 the packages driver as well as various bugfixes.
139
1402022-11-22
141 Release
142 `v0.36.0 <https://github.com/bazelbuild/rules_go/releases/tag/v0.36.0>`_
143 is now available. This release adds a Go library to look up runfiles, and
144 two command line flags to pass additional compiler and linker options.
145
1462022-09-11
147 Release
148 `v0.35.0 <https://github.com/bazelbuild/rules_go/releases/tag/v0.35.0>`_
149 is now available. This release supports switching Go SDK version from a
150 build flag. Starting this release, rules_go requires Bazel 5.1.0, because
151 it needs to read CPU architecture from Bazel to better support Apple M1
152 with Rosetta translation.
153
1542022-07-19
155 Release
156 `v0.34.0 <https://github.com/bazelbuild/rules_go/releases/tag/v0.34.0>`_
157 is now available. This release brings very experimental support for bzlmod,
158 several improvements to nogo and gopackagesdriver.
159
1602022-06-06
161 Release
162 `v0.33.0 <https://github.com/bazelbuild/rules_go/releases/tag/v0.33.0>`_
163 is now available. This release consists mostly of bug fixes and deprecates
164 the `asm`, `compile`, `cover`, and `pack` actions on `go_context`.
1652022-05-11
166 Release
167 `v0.32.0 <https://github.com/bazelbuild/rules_go/releases/tag/v0.32.0>`_
168 is now available. This adds `gomock` to rules_go and supports lcov format
169 for code coverage report, as well as a long list of other changes listed
170 in the release notes.
171
172Contents
173--------
174
175* `Overview`_
176* `Setup`_
177* `protobuf and gRPC`_
178* `FAQ`_
179
180Documentation
181~~~~~~~~~~~~~
182
183* `Core rules`_
184
185 * `go_binary`_
186 * `go_library`_
187 * `go_test`_
188 * `go_source`_
189 * `go_path`_
190 * `go_cross_binary`_
191
192* `Proto rules`_
193
194 * `go_proto_library`_
195 * `go_proto_compiler`_
196
197* `Dependencies`_
198
199 * `go_rules_dependencies`_
200 * `go_repository`_ (Gazelle)
201
202* `Toolchains`_
203
204 * `go_register_toolchains`_
205 * `go_download_sdk`_
206 * `go_host_sdk`_
207 * `go_local_sdk`_
208 * `go_wrap_sdk`_
209 * `go_toolchain`_
210 * `go_context`_
211
212* `Extra rules <docs/go/extras/extras.md>`_
213 * `gomock`_
214
215* `nogo build-time static analysis`_
216* `Build modes <go/modes.rst>`_
217
218Quick links
219~~~~~~~~~~~
220
221* `rules_go and Gazelle roadmap`_
222* `Deprecation schedule`_
223* `Using rules_go on Windows`_
224
225Overview
226--------
227
228The rules are in the beta stage of development. They support:
229
230* Building libraries, binaries, and tests (`go_library`_, `go_binary`_,
231 `go_test`_)
232* Vendoring
233* cgo
234* Cross-compilation
235* Generating BUILD files via gazelle_
236* Build-time code analysis via nogo_
237* `Protocol buffers`_
238* Remote execution
239* `Coverage`_
240* `gopls integration`_ for editor support
241* Debugging
242
243They currently do not support or have limited support for:
244
245* C/C++ integration other than cgo (SWIG)
246
247The Go rules are tested and supported on the following host platforms:
248
249* Linux, macOS, Windows
250* amd64
251
252Users have reported success on several other platforms, but the rules are
253only tested on those listed above.
254
255Note: Since version v0.38.0, rules_go requires Bazel ≥ 5.4.0 to work.
256
257The ``master`` branch is only guaranteed to work with the latest version of Bazel.
258
259
260Setup
261-----
262
263System setup
264~~~~~~~~~~~~
265
266To build Go code with Bazel, you will need:
267
268* A recent version of Bazel.
269* A C/C++ toolchain (if using cgo). Bazel will attempt to configure the
270 toolchain automatically.
271* Bash, ``patch``, ``cat``, and a handful of other Unix tools in ``PATH``.
272
273You normally won't need a Go toolchain installed. Bazel will download one.
274
275See `Using rules_go on Windows`_ for Windows-specific setup instructions.
276Several additional tools need to be installed and configured.
277
278Initial project setup
279~~~~~~~~~~~~~~~~~~~~~
280
281If you are using Bazel's new external dependency management system `Bzlmod`_,
282refer to the dedicated `Go with Bzlmod`_ guide instead.
283
284Create a file at the top of your repository named ``WORKSPACE``, and add the
285snippet below (or add to your existing ``WORKSPACE``). This tells Bazel to
286fetch rules_go and its dependencies. Bazel will download a recent supported
287Go toolchain and register it for use.
288
289.. code:: bzl
290
291 load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
292
293 http_archive(
294 name = "io_bazel_rules_go",
295 integrity = "sha256-fHbWI2so/2laoozzX5XeMXqUcv0fsUrHl8m/aE8Js3w=",
296 urls = [
297 "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.44.2/rules_go-v0.44.2.zip",
298 "https://github.com/bazelbuild/rules_go/releases/download/v0.44.2/rules_go-v0.44.2.zip",
299 ],
300 )
301
302 load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")
303
304 go_rules_dependencies()
305
306 go_register_toolchains(version = "1.20.7")
307
308You can use rules_go at ``master`` by using `git_repository`_ instead of
309`http_archive`_ and pointing to a recent commit.
310
311Add a file named ``BUILD.bazel`` in the root directory of your project.
312You'll need a build file in each directory with Go code, but you'll also need
313one in the root directory, even if your project doesn't have Go code there.
314For a "Hello, world" binary, the file should look like this:
315
316.. code:: bzl
317
318 load("@io_bazel_rules_go//go:def.bzl", "go_binary")
319
320 go_binary(
321 name = "hello",
322 srcs = ["hello.go"],
323 )
324
325You can build this target with ``bazel build //:hello``.
326
327Generating build files
328~~~~~~~~~~~~~~~~~~~~~~
329
330If your project can be built with ``go build``, you can generate and update your
331build files automatically using gazelle_.
332
333Add the ``bazel_gazelle`` repository and its dependencies to your
334``WORKSPACE``. It should look like this:
335
336 .. code:: bzl
337
338 load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
339
340 http_archive(
341 name = "io_bazel_rules_go",
342 integrity = "sha256-fHbWI2so/2laoozzX5XeMXqUcv0fsUrHl8m/aE8Js3w=",
343 urls = [
344 "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.44.2/rules_go-v0.44.2.zip",
345 "https://github.com/bazelbuild/rules_go/releases/download/v0.44.2/rules_go-v0.44.2.zip",
346 ],
347 )
348
349 http_archive(
350 name = "bazel_gazelle",
351 integrity = "sha256-MpOL2hbmcABjA1R5Bj2dJMYO2o15/Uc5Vj9Q0zHLMgk=",
352 urls = [
353 "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.35.0/bazel-gazelle-v0.35.0.tar.gz",
354 "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.35.0/bazel-gazelle-v0.35.0.tar.gz",
355 ],
356 )
357
358 load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")
359 load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies")
360
361 go_rules_dependencies()
362
363 go_register_toolchains(version = "1.20.7")
364
365 gazelle_dependencies()
366
367Add the code below to the ``BUILD.bazel`` file in your project's root directory.
368Replace the string after ``prefix`` with an import path prefix that matches your
369project. It should be the same as your module path, if you have a ``go.mod``
370file.
371
372.. code:: bzl
373
374 load("@bazel_gazelle//:def.bzl", "gazelle")
375
376 # gazelle:prefix github.com/example/project
377 gazelle(name = "gazelle")
378
379This declares a ``gazelle`` binary rule, which you can run using the command
380below:
381
382.. code:: bash
383
384 bazel run //:gazelle
385
386This will generate a ``BUILD.bazel`` file with `go_library`_, `go_binary`_, and
387`go_test`_ targets for each package in your project. You can run the same
388command in the future to update existing build files with new source files,
389dependencies, and options.
390
391Writing build files by hand
392~~~~~~~~~~~~~~~~~~~~~~~~~~~
393
394If your project doesn't follow ``go build`` conventions or you prefer not to use
395gazelle_, you can write build files by hand.
396
397In each directory that contains Go code, create a file named ``BUILD.bazel``
398Add a ``load`` statement at the top of the file for the rules you use.
399
400.. code:: bzl
401
402 load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library", "go_test")
403
404For each library, add a `go_library`_ rule like the one below. Source files are
405listed in the ``srcs`` attribute. Imported packages outside the standard library
406are listed in the ``deps`` attribute using `Bazel labels`_ that refer to
407corresponding `go_library`_ rules. The library's import path must be specified
408with the ``importpath`` attribute.
409
410.. code:: bzl
411
412 go_library(
413 name = "foo_library",
414 srcs = [
415 "a.go",
416 "b.go",
417 ],
418 importpath = "github.com/example/project/foo",
419 deps = [
420 "//tools",
421 "@org_golang_x_utils//stuff",
422 ],
423 visibility = ["//visibility:public"],
424 )
425
426For tests, add a `go_test`_ rule like the one below. The library being tested
427should be listed in an ``embed`` attribute.
428
429.. code:: bzl
430
431 go_test(
432 name = "foo_test",
433 srcs = [
434 "a_test.go",
435 "b_test.go",
436 ],
437 embed = [":foo_lib"],
438 deps = [
439 "//testtools",
440 "@org_golang_x_utils//morestuff",
441 ],
442 )
443
444For binaries, add a `go_binary`_ rule like the one below.
445
446.. code:: bzl
447
448 go_binary(
449 name = "foo",
450 srcs = ["main.go"],
451 )
452
453Adding external repositories
454~~~~~~~~~~~~~~~~~~~~~~~~~~~~
455
456For each Go repository, add a `go_repository`_ rule to ``WORKSPACE`` like the
457one below. This rule comes from the Gazelle repository, so you will need to
458load it. `gazelle update-repos`_ can generate or update these rules
459automatically from a go.mod or Gopkg.lock file.
460
461.. code:: bzl
462
463 load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
464
465 # Download the Go rules.
466 http_archive(
467 name = "io_bazel_rules_go",
468 integrity = "sha256-fHbWI2so/2laoozzX5XeMXqUcv0fsUrHl8m/aE8Js3w=",
469 urls = [
470 "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.44.2/rules_go-v0.44.2.zip",
471 "https://github.com/bazelbuild/rules_go/releases/download/v0.44.2/rules_go-v0.44.2.zip",
472 ],
473 )
474
475 # Download Gazelle.
476 http_archive(
477 name = "bazel_gazelle",
478 integrity = "sha256-MpOL2hbmcABjA1R5Bj2dJMYO2o15/Uc5Vj9Q0zHLMgk=",
479 urls = [
480 "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.35.0/bazel-gazelle-v0.35.0.tar.gz",
481 "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.35.0/bazel-gazelle-v0.35.0.tar.gz",
482 ],
483 )
484
485 # Load macros and repository rules.
486 load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")
487 load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies", "go_repository")
488
489 # Declare Go direct dependencies.
490 go_repository(
491 name = "org_golang_x_net",
492 importpath = "golang.org/x/net",
493 sum = "h1:zK/HqS5bZxDptfPJNq8v7vJfXtkU7r9TLIoSr1bXaP4=",
494 version = "v0.0.0-20200813134508-3edf25e44fcc",
495 )
496
497 # Declare indirect dependencies and register toolchains.
498 go_rules_dependencies()
499
500 go_register_toolchains(version = "1.20.7")
501
502 gazelle_dependencies()
503
504
505protobuf and gRPC
506-----------------
507
508To generate code from protocol buffers, you'll need to add a dependency on
509``com_google_protobuf`` to your ``WORKSPACE``.
510
511.. code:: bzl
512
513 load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
514
515 http_archive(
516 name = "com_google_protobuf",
517 sha256 = "d0f5f605d0d656007ce6c8b5a82df3037e1d8fe8b121ed42e536f569dec16113",
518 strip_prefix = "protobuf-3.14.0",
519 urls = [
520 "https://mirror.bazel.build/github.com/protocolbuffers/protobuf/archive/v3.14.0.tar.gz",
521 "https://github.com/protocolbuffers/protobuf/archive/v3.14.0.tar.gz",
522 ],
523 )
524
525 load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps")
526
527 protobuf_deps()
528
529You'll need a C/C++ toolchain registered for the execution platform (the
530platform where Bazel runs actions) to build protoc.
531
532The `proto_library`_ rule is provided by the ``rules_proto`` repository.
533``protoc-gen-go``, the Go proto compiler plugin, is provided by the
534``com_github_golang_protobuf`` repository. Both are declared by
535`go_rules_dependencies`_. You won't need to declare an explicit dependency
536unless you specifically want to use a different version. See `Overriding
537dependencies`_ for instructions on using a different version.
538
539gRPC dependencies are not declared by default (there are too many). You can
540declare them in WORKSPACE using `go_repository`_. You may want to use
541`gazelle update-repos`_ to import them from ``go.mod``.
542
543See `Proto dependencies`_, `gRPC dependencies`_ for more information. See also
544`Avoiding conflicts`_.
545
546Once all dependencies have been registered, you can declare `proto_library`_
547and `go_proto_library`_ rules to generate and compile Go code from .proto
548files.
549
550.. code:: bzl
551
552 load("@rules_proto//proto:defs.bzl", "proto_library")
553 load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
554
555 proto_library(
556 name = "foo_proto",
557 srcs = ["foo.proto"],
558 deps = ["//bar:bar_proto"],
559 visibility = ["//visibility:public"],
560 )
561
562 go_proto_library(
563 name = "foo_go_proto",
564 importpath = "github.com/example/protos/foo_proto",
565 protos = [":foo_proto"],
566 visibility = ["//visibility:public"],
567 )
568
569A ``go_proto_library`` target may be imported and depended on like a normal
570``go_library``.
571
572Note that recent versions of rules_go support both APIv1
573(``github.com/golang/protobuf``) and APIv2 (``google.golang.org/protobuf``).
574By default, code is generated with
575``github.com/golang/protobuf/cmd/protoc-gen-gen`` for compatibility with both
576interfaces. Client code may import use either runtime library or both.
577
578FAQ
579---
580
581**Go**
582
583* `Can I still use the go command?`_
584* `Does this work with Go modules?`_
585* `What's up with the go_default_library name?`_
586* `How do I cross-compile?`_
587* `How do I access testdata?`_
588* `How do I access go_binary executables from go_test?`_
589
590**Protocol buffers**
591
592* `How do I avoid conflicts with protocol buffers?`_
593* `Can I use a vendored gRPC with go_proto_library?`_
594
595**Dependencies and testing**
596
597* `How do I use different versions of dependencies?`_
598* `How do I run Bazel on Travis CI?`_
599* `How do I test a beta version of the Go SDK?`_
600
601Can I still use the go command?
602~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
603
604Yes, but not directly.
605
606rules_go invokes the Go compiler and linker directly, based on the targets
607described with `go_binary`_ and other rules. Bazel and rules_go together
608fill the same role as the ``go`` command, so it's not necessary to use the
609``go`` command in a Bazel workspace.
610
611That said, it's usually still a good idea to follow conventions required by
612the ``go`` command (e.g., one package per directory, package paths match
613directory paths). Tools that aren't compatible with Bazel will still work,
614and your project can be depended on by non-Bazel projects.
615
616If you need to use the ``go`` command to perform tasks that Bazel doesn't cover
617(such as adding a new dependency to ``go.mod``), you can use the following Bazel
618invocation to run the ``go`` binary of the Bazel-configured Go SDK:
619
620.. code:: bash
621
622 bazel run @io_bazel_rules_go//go -- <args>
623
624Prefer this to running ``go`` directly since it ensures that the version of Go
625is identical to the one used by rules_go.
626
627Does this work with Go modules?
628~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
629
630Yes, but not directly. Bazel ignores ``go.mod`` files, and all package
631dependencies must be expressed through ``deps`` attributes in targets
632described with `go_library`_ and other rules.
633
634You can download a Go module at a specific version as an external repository
635using `go_repository`_, a workspace rule provided by gazelle_. This will also
636generate build files using gazelle_.
637
638You can import `go_repository`_ rules from a ``go.mod`` file using
639`gazelle update-repos`_.
640
641What's up with the go_default_library name?
642~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
643
644This was used to keep import paths consistent in libraries that can be built
645with ``go build`` before the ``importpath`` attribute was available.
646
647In order to compile and link correctly, rules_go must know the Go import path
648(the string by which a package can be imported) for each library. This is now
649set explicitly with the ``importpath`` attribute. Before that attribute existed,
650the import path was inferred by concatenating a string from a special
651``go_prefix`` rule and the library's package and label name. For example, if
652``go_prefix`` was ``github.com/example/project``, for a library
653``//foo/bar:bar``, rules_go would infer the import path as
654``github.com/example/project/foo/bar/bar``. The stutter at the end is
655incompatible with ``go build``, so if the label name was ``go_default_library``,
656the import path would not include it. So for the library
657``//foo/bar:go_default_library``, the import path would be
658``github.com/example/project/foo/bar``.
659
660Since ``go_prefix`` was removed and the ``importpath`` attribute became
661mandatory (see `#721`_), the ``go_default_library`` name no longer serves any
662purpose. We may decide to stop using it in the future (see `#265`_).
663
664How do I cross-compile?
665~~~~~~~~~~~~~~~~~~~~~~~
666
667You can cross-compile by setting the ``--platforms`` flag on the command line.
668For example:
669
670.. code::
671
672 $ bazel build --platforms=@io_bazel_rules_go//go/toolchain:linux_amd64 //cmd
673
674By default, cgo is disabled when cross-compiling. To cross-compile with cgo,
675add a ``_cgo`` suffix to the target platform. You must register a
676cross-compiling C/C++ toolchain with Bazel for this to work.
677
678.. code::
679
680 $ bazel build --platforms=@io_bazel_rules_go//go/toolchain:linux_amd64_cgo //cmd
681
682Platform-specific sources with build tags or filename suffixes are filtered
683automatically at compile time. You can selectively include platform-specific
684dependencies with ``select`` expressions (Gazelle does this automatically).
685
686.. code:: bzl
687
688 go_library(
689 name = "foo",
690 srcs = [
691 "foo_linux.go",
692 "foo_windows.go",
693 ],
694 deps = select({
695 "@io_bazel_rules_go//go/platform:linux_amd64": [
696 "//bar_linux",
697 ],
698 "@io_bazel_rules_go//go/platform:windows_amd64": [
699 "//bar_windows",
700 ],
701 "//conditions:default": [],
702 }),
703 )
704
705To build a specific `go_binary`_ target for a target platform or using a
706specific golang SDK version, use the `go_cross_binary`_ rule. This is useful
707for producing multiple binaries for different platforms in a single build.
708
709To build a specific `go_test`_ target for a target platform, set the
710``goos`` and ``goarch`` attributes on that rule.
711
712You can equivalently depend on a `go_binary`_ or `go_test`_ rule through
713a Bazel `configuration transition`_ on ``//command_line_option:platforms``
714(there are problems with this approach prior to rules_go 0.23.0).
715
716How do I access testdata?
717~~~~~~~~~~~~~~~~~~~~~~~~~
718
719Bazel executes tests in a sandbox, which means tests don't automatically have
720access to files. You must include test files using the ``data`` attribute.
721For example, if you want to include everything in the ``testdata`` directory:
722
723.. code:: bzl
724
725 go_test(
726 name = "foo_test",
727 srcs = ["foo_test.go"],
728 data = glob(["testdata/**"]),
729 importpath = "github.com/example/project/foo",
730 )
731
732By default, tests are run in the directory of the build file that defined them.
733Note that this follows the Go testing convention, not the Bazel convention
734followed by other languages, which run in the repository root. This means
735that you can access test files using relative paths. You can change the test
736directory using the ``rundir`` attribute. See go_test_.
737
738Gazelle will automatically add a ``data`` attribute like the one above if you
739have a ``testdata`` directory *unless* it contains buildable .go files or
740build files, in which case, ``testdata`` is treated as a normal package.
741
742Note that on Windows, data files are not directly available to tests, since test
743data files rely on symbolic links, and by default, Windows doesn't let
744unprivileged users create symbolic links. You can use the
745`github.com/bazelbuild/rules_go/go/tools/bazel`_ library to access data files.
746
747How do I access go_binary executables from go_test?
748~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
749
750The location where ``go_binary`` writes its executable file is not stable across
751rules_go versions and should not be depended upon. The parent directory includes
752some configuration data in its name. This prevents Bazel's cache from being
753poisoned when the same binary is built in different configurations. The binary
754basename may also be platform-dependent: on Windows, we add an .exe extension.
755
756To depend on an executable in a ``go_test`` rule, reference the executable
757in the ``data`` attribute (to make it visible), then expand the location
758in ``args``. The real location will be passed to the test on the command line.
759For example:
760
761.. code:: bzl
762
763 go_binary(
764 name = "cmd",
765 srcs = ["cmd.go"],
766 )
767
768 go_test(
769 name = "cmd_test",
770 srcs = ["cmd_test.go"],
771 args = ["$(location :cmd)"],
772 data = [":cmd"],
773 )
774
775See `//tests/core/cross`_ for a full example of a test that
776accesses a binary.
777
778Alternatively, you can set the ``out`` attribute of `go_binary`_ to a specific
779filename. Note that when ``out`` is set, the binary won't be cached when
780changing configurations.
781
782.. code:: bzl
783
784 go_binary(
785 name = "cmd",
786 srcs = ["cmd.go"],
787 out = "cmd",
788 )
789
790 go_test(
791 name = "cmd_test",
792 srcs = ["cmd_test.go"],
793 data = [":cmd"],
794 )
795
796How do I avoid conflicts with protocol buffers?
797~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
798
799See `Avoiding conflicts`_ in the proto documentation.
800
801Can I use a vendored gRPC with go_proto_library?
802~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
803
804This is not supported. When using `go_proto_library`_ with the
805``@io_bazel_rules_go//proto:go_grpc`` compiler, an implicit dependency is added
806on ``@org_golang_google_grpc//:go_default_library``. If you link another copy of
807the same package from ``//vendor/google.golang.org/grpc:go_default_library``
808or anywhere else, you may experience conflicts at compile or run-time.
809
810If you're using Gazelle with proto rule generation enabled, imports of
811``google.golang.org/grpc`` will be automatically resolved to
812``@org_golang_google_grpc//:go_default_library`` to avoid conflicts. The
813vendored gRPC should be ignored in this case.
814
815If you specifically need to use a vendored gRPC package, it's best to avoid
816using ``go_proto_library`` altogether. You can check in pre-generated .pb.go
817files and build them with ``go_library`` rules. Gazelle will generate these
818rules when proto rule generation is disabled (add ``# gazelle:proto
819disable_global`` to your root build file).
820
821How do I use different versions of dependencies?
822~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
823
824See `Overriding dependencies`_ for instructions on overriding repositories
825declared in `go_rules_dependencies`_.
826
827
828How do I run Bazel on Travis CI?
829~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
830
831References:
832
833* `Running Bazel Tests on Travis CI`_ by Kevin Burke
834* `korfuri/bazel-travis Use Bazel with Travis CI`_
835
836In order to run Bazel tests on Travis CI, you'll need to install Bazel in the
837``before_install`` script. See our configuration file linked above.
838
839You'll want to run Bazel with a number of flags to prevent it from consuming
840a huge amount of memory in the test environment.
841
842* ``--host_jvm_args=-Xmx500m --host_jvm_args=-Xms500m``: Set the maximum and
843 initial JVM heap size. Keeping the same means the JVM won't spend time
844 growing the heap. The choice of heap size is somewhat arbitrary; other
845 configuration files recommend limits as high as 2500m. Higher values mean
846 a faster build, but higher risk of OOM kill.
847* ``--bazelrc=.test-bazelrc``: Use a Bazel configuration file specific to
848 Travis CI. You can put most of the remaining options in here.
849* ``build --spawn_strategy=standalone --genrule_strategy=standalone``: Disable
850 sandboxing for the build. Sandboxing may fail inside of Travis's containers
851 because the ``mount`` system call is not permitted.
852* ``test --test_strategy=standalone``: Disable sandboxing for tests as well.
853* ``--local_resources=1536,1.5,0.5``: Set Bazel limits on available RAM in MB,
854 available cores for compute, and available cores for I/O. Higher values
855 mean a faster build, but higher contention and risk of OOM kill.
856* ``--noshow_progress``: Suppress progress messages in output for cleaner logs.
857* ``--verbose_failures``: Get more detailed failure messages.
858* ``--test_output=errors``: Show test stderr in the Travis log. Normally,
859 test output is written log files which Travis does not save or report.
860
861Downloads on Travis are relatively slow (the network is heavily
862contended), so you'll want to minimize the amount of network I/O in
863your build. Downloading Bazel and a Go SDK is a huge part of that. To
864avoid downloading a Go SDK, you may request a container with a
865preinstalled version of Go in your ``.travis.yml`` file, then call
866``go_register_toolchains(go_version = "host")`` in a Travis-specific
867``WORKSPACE`` file.
868
869You may be tempted to put Bazel's cache in your Travis cache. Although this
870can speed up your build significantly, Travis stores its cache on Amazon, and
871it takes a very long time to transfer. Clean builds seem faster in practice.
872
873How do I test a beta version of the Go SDK?
874~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
875
876rules_go only supports official releases of the Go SDK. However, you can still
877test beta and RC versions by passing a ``version`` like ``"1.16beta1"`` to
878`go_register_toolchains`_. See also `go_download_sdk`_.
879
880.. code:: bzl
881
882 load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")
883
884 go_rules_dependencies()
885
886 go_register_toolchains(version = "1.17beta1")
View as plain text