Name Date Size #Lines LOC

..--

.bazelci/H25-Apr-2025-378347

.bcr/H25-Apr-2025-5854

.github/H25-Apr-2025-6920

.vscode/H25-Apr-2025-4240

docs/H25-Apr-2025-3,7303,388

examples/basic-gazelle/H25-Apr-2025-432288

extras/H25-Apr-2025-728660

go/H25-Apr-2025-27,14521,901

proto/H25-Apr-2025-1,4381,251

tests/H25-Apr-2025-19,92814,654

third_party/H25-Apr-2025-317,717317,676

tools/H25-Apr-2025-31

.bazelignoreH A D25-Apr-202519 32

.bazelrcH A D25-Apr-20251.9 KiB3530

.gitignoreH A D25-Apr-2025135 87

AUTHORSH A D25-Apr-2025494 1512

BUILD.bazelH A D25-Apr-20255 KiB179164

CODEOWNERSH A D25-Apr-202518 21

CONTRIBUTING.mdH A D25-Apr-20252 KiB4034

CONTRIBUTORSH A D25-Apr-20251,015 2725

LICENSEH A D25-Apr-202511.1 KiB203169

LICENSE.txtH A D25-Apr-202511.1 KiB203169

METADATAH A D25-Apr-2025349 1816

MODULE.bazelH A D25-Apr-20251.3 KiB4841

OWNERSH A D25-Apr-202537 21

README.rstH A D25-Apr-202529.3 KiB833633

WORKSPACEH A D25-Apr-20256 KiB182142

go.modH A D25-Apr-2025462 1814

go.sumH A D25-Apr-202510.6 KiB109108

windows.rstH A D25-Apr-20254.7 KiB137103

README.rst

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