Skip to content

bazelbuild/bazel-gazelle

Repository files navigation

Gazelle build file generator

Gazelle is a build file generator for Bazel projects. It can create new BUILD.bazel files for a project that follows language conventions, and it can update existing build files to include new sources, dependencies, and options. Gazelle natively supports Go and protobuf, and it may be extended to support new languages and custom rule sets.

Gazelle may be run by Bazel using the gazelle rule, or it may be installed and run as a command line tool. Gazelle can also generate build files for external repositories as part of the go_repository rule.

Gazelle is under active development. Its interface and the rules it generates may change. Gazelle is not an official Google product.

Mailing list: bazel-go-discuss

Slack: #go on Bazel Slack, #bazel on Go Slack

rules_go and Gazelle are getting community maintainers! If you are a regular user of either project and are interested in helping out with development, code reviews, and issue triage, please drop by our Slack channels (linked above) and say hello!

Contents

See also:

Supported languages

Gazelle can generate Bazel BUILD files for many languages:

  • Go

    Go supported is included here in bazel-gazelle, see below.

  • Haskell

    Tweag's rules_haskell has two extensions: gazelle_cabal, for generating rules from Cabal files and gazelle_haskell_modules for even more fine-grained build definitions.

  • Java

    bazel-contrib's rules_jvm extensions include a gazelle extension for generating java_library, java_binary, java_test, and java_test_suite rules.

  • JavaScript / TypeScript

    Aspect provides JavaScript and TypeScript Support in aspect-cli (also usable separately).

    BenchSci's rules_nodejs_gazelle supports generating ts_project, js_library, jest_test, and web_asset rules, and is able to support module bundlers like Webpack and Next.js

  • Kotlin

    Aspect Build provides some Kotlin Support in the repo of their aspect-cli (also usable separately). Still under development, please check the README for currently available features.

  • Protocol Buffers

    Support for the proto_library rule, as well as go_proto_library is in this repository, see below. Other language-specific proto rules are not supported here. stackb/rules_proto is a good resource for these rules.

  • Python

    rules_python has an extension for generating py_library, py_binary, and py_test rules.

  • R

    rules_r has an extension for generating rules for R package builds and tests.

  • Rust

    gazelle_rust is an extension for generating rules_rust targets.

  • Starlark

    bazel-skylib has an extension for generating bzl_library rules. See bazel_skylib//gazelle/bzl.

  • Swift

    rules_swift_package_manager has an extension for generating swift_library, swift_binary, and swift_test rules. It also includes facilities for resolving, downloading and building external Swift packages for a Bazel workspace.

If you know of an extension which could be linked here, please open a PR!

More languages can be added by Extending Gazelle. Chat with us in the #gazelle channel on Bazel Slack if you'd like to discuss your design.

If you've written your own extension, please consider open-sourcing it for use by the rest of the community. Note that such extensions belong in a language-specific repository, not in bazel-gazelle. See discussion in #1030.

Setup

Running Gazelle with Bazel

To use Gazelle in a new project, add the bazel_gazelle repository and its dependencies to your WORKSPACE file and call gazelle_dependencies. It should look like this:

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "io_bazel_rules_go",
    sha256 = "80a98277ad1311dacd837f9b16db62887702e9f1d1c4c9f796d0121a46c8e184",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.46.0/rules_go-v0.46.0.zip",
        "https://github.com/bazelbuild/rules_go/releases/download/v0.46.0/rules_go-v0.46.0.zip",
    ],
)

http_archive(
    name = "bazel_gazelle",
    integrity = "sha256-MpOL2hbmcABjA1R5Bj2dJMYO2o15/Uc5Vj9Q0zHLMgk=",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.35.0/bazel-gazelle-v0.35.0.tar.gz",
        "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.35.0/bazel-gazelle-v0.35.0.tar.gz",
    ],
)


load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")
load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies", "go_repository")

############################################################
# Define your own dependencies here using go_repository.
# Else, dependencies declared by rules_go/gazelle will be used.
# The first declaration of an external repository "wins".
############################################################

go_rules_dependencies()

go_register_toolchains(version = "1.20.5")

gazelle_dependencies()

gazelle_dependencies supports optional argument go_env (dict-mapping) to set project specific go environment variables. If you are using a WORKSPACE.bazel file, you will need to specify that using:

gazelle_dependencies(go_repository_default_config = "//:WORKSPACE.bazel")

Add the code below to the BUILD or BUILD.bazel file in the root directory of your repository.

Important: For Go projects, replace the string after prefix with the portion of your import path that corresponds to your repository.

load("@bazel_gazelle//:def.bzl", "gazelle")

# gazelle:prefix github.com/example/project
gazelle(name = "gazelle")

After adding this code, you can run Gazelle with Bazel.

$ bazel run //:gazelle

This will generate new BUILD.bazel files for your project. You can run the same command in the future to update existing BUILD.bazel files to include new source files or options.

You can write other gazelle rules to run alternate commands like update-repos.

gazelle(
    name = "gazelle-update-repos",
    args = [
        "-from_file=go.mod",
        "-to_macro=deps.bzl%go_dependencies",
        "-prune",
    ],
    command = "update-repos",
)

You can also pass additional arguments to Gazelle after a -- argument.

$ bazel run //:gazelle -- update-repos -from_file=go.mod -to_macro=deps.bzl%go_dependencies

After running update-repos, you might want to run bazel run //:gazelle again, as the update-repos command can affect the output of a normal run of Gazelle.

Running Gazelle with Go

If you have a Go toolchain installed, you can install Gazelle with the command below:

go install github.com/bazelbuild/bazel-gazelle/cmd/gazelle@latest

Make sure to re-run this command to upgrade Gazelle whenever you upgrade rules_go in your repository.

To generate BUILD.bazel files in a new project, run the command below, replacing the prefix with the portion of your import path that corresponds to your repository.

gazelle -go_prefix github.com/example/project

Most of Gazelle's command-line arguments can be expressed as special comments in build files. See Directives below. You may want to copy this line into your root build files to avoid having to type -go_prefix every time.

# gazelle:prefix github.com/example/project

Compatibility with Go

Gazelle is compatible with supported releases of Go, per the Go Release Policy. The Go Team officially supports the current and previous minor releases. Older releases are not supported and don't receive bug fixes or security updates.

Gazelle may use language and library features from the oldest supported release.

Compatibility with rules_go

Gazelle generates build files that use features in newer versions of rules_go. Newer versions of Gazelle may generate build files that work with older versions of rules_go, but check the table below to ensure you're using a compatible version.

Gazelle version Minimum rules_go version Maximum rules_go version
0.8 0.8 n/a
0.9 0.9 n/a
0.10 0.9 0.11
0.11 0.11 0.24
0.12 0.11 0.24
0.13 0.13 0.24
0.14 0.13 0.24
0.15 0.13 0.24
0.16 0.13 0.24
0.17 0.13 0.24
0.18 0.19 0.24
0.19 0.19 0.24
0.20 0.20 0.24
0.21 0.20 0.24
0.22 0.20 0.24
0.23 0.26 0.28
0.24 0.29 0.40
0.25 0.29 0.40
0.26 0.29 0.40
0.27 0.29 0.40
0.28 0.35 0.40
0.29 0.35 0.40
0.30 0.35 0.40
0.31 0.35 0.40
0.32 0.41 n/a
0.33 0.41 n/a
0.34 0.41 n/a
0.35 0.41 n/a

Usage

Command line

gazelle <command> [flags...] [package-dirs...]

The first argument to Gazelle may be one of the commands below. If no command is specified, update is assumed. The remaining arguments are specific to each command and are documented below.

update

Scans sources files, then generates and updates build files.

fix

Same as the update command, but it also fixes deprecated usage of rules.

update-repos

Adds and updates repository rules in the WORKSPACE file.

Bazel rule

Gazelle may be run via a rule. See Running Gazelle with Bazel for setup instructions. This rule builds Gazelle and generates a wrapper script that executes Gazelle with baked-in set of arguments. You can run this script with bazel run, or you can copy it into your workspace and run it directly.

The following attributes are available on the gazelle rule.

Name Type Default value
gazelle label @bazel_gazelle//cmd/gazelle
The gazelle_binary version of Gazelle wit rule that builds Gazel h this. See `Extending
le. You can substitute a modified

Gazelle`_.

external string external
The method for resolvi external, :va See `Dependency resolu ng unknown imports to lue:static or :value tion`_. Bazel dependencies. May be :vendored.
build_tags string_list []
The list of Go build t ags that Gazelle shoul d consider to always be true.
prefix string ""

The import path that c

Note: It's usually bet ``# gazelle:prefix exa this attribute.

orresponds to the repo

ter to write a directi mple.com/repo`` in you

sitory root directory.

ve like r build file instead of setting

extra_args string_list []
A list of extra comman extra_args are sup ``bazel run //:gazelle See https://github.com d line arguments passe pressed by extra comma -- subdir``). /bazelbuild/bazel-gaze

d to Gazelle. Note that nd line args (e.g.

lle/issues/536 for explanation.

command string update
The Gazelle command to update-repos. use. May be :value:`f ix`, update or

fix and update

The update command is the most common way of running Gazelle. Gazelle scans sources in directories throughout the repository, then creates and updates build files.

The fix command does everything update does, but it also fixes deprecated usage of rules, analogous to go fix. For example, cgo_library will be consolidated with go_library. This command may delete or rename rules, so it's not on by default. See Fix command transformations for details.

Both commands accept a list of directories to process as positional arguments. If no directories are specified, Gazelle will process the current directory. Subdirectories will be processed recursively.

The following flags are accepted:

Name Default value
-build_file_name file1,file2,... BUILD.bazel,BUILD
Comma-separated list of file names. Gazelle recognizes these files build files. New files will use the first name in this list. Use th your project contains non-Bazel files named BUILD (or build case-insensitive file systems). as Bazel is if on
-build_tags tag1,tag2

List of Go build tags Gazelle will consider to be true. Gazelle app constraints when generating Go rules. It assumes certain tags are t certain platforms (for example, amd64,linux). It assumes all Go tags are true (for example, go1.8). It considers other tags to (for example, ignore). This flag overrides that behavior.

Bazel may still filter sources with these tags. Use bazel build --define gotags=foo,bar to set tags at build time.

lies rue on release be false
-exclude pattern

Prevents Gazelle from processing a file or directory if the given doublestar.Match pattern matches. If the pattern refers to a sou Gazelle won't include it in any rules. If the pattern refers to a d Gazelle won't recurse into it.

This option may be repeated. Patterns must be slash-separated, rela repository root. This is equivalent to the ``# gazelle:exclude patt directive.

rce file, irectory,

tive to the ern``

-external external|static|vendored external
Determines how Gazelle resolves import paths that cannot be resolve current repository. May be external, static or :v Dependency resolution.

in the

alue:vendored. See
-index true|false true
Determines whether Gazelle should index the libraries in the curren should use the index to resolve dependencies. If this is switched o # gazelle:prefix directive or -go_prefix flag to resolve de t repository and whether it ff, Gazelle would rely on pendencies.
-go_grpc_compiler @io_bazel_rules_go//proto:go_grpc

The protocol buffers compiler to use for building go bindings for g

See Predefined plugins for available options; commonly used opti @io_bazel_rules_go//proto:gofast_grpc and ``@io_bazel_rules_go/

RPC. May be repeated.

ons include /proto:gogofaster_grpc``.

-go_naming_convention
Controls the names of generated Go targets. Equivalent to the # gazelle:go_naming_convention directive. See details in Directives below.
-go_naming_convention_external
Controls the default naming convention used when resolving librarie external repositories with unknown naming conventions. Equivalent t # gazelle:go_naming_convention_external directive. s in o the
-go_prefix example.com/repo

A prefix of import paths for libraries in the repository that corre the repository root. Equivalent to setting the # gazelle:prefix in the root BUILD.bazel file or the prefix attribute of the ``g neither of those are set, this option is mandatory.

This prefix is used to determine whether an import path refers to a in the current repository or an external dependency.

sponds to

directive

azelle`` rule. If

library

-go_proto_compiler @io_bazel_rules_go//proto:go_proto

The protocol buffers compiler to use for building go bindings. May

See Predefined plugins for available options; commonly used opti @io_bazel_rules_go//proto:gofast_proto and ``@io_bazel_rules_go

be repeated.

ons include //proto:gogofaster_proto``.

-known_import example.com

Skips import path resolution for a known domain. May be repeated.

When Gazelle resolves an import path to an external dependency, it to discover the remote repository root over HTTP. Gazelle skips thi discovery step for a few well-known domains with predictable struct golang.org and github.com. This flag specifies additional domains t which is useful in situations where the lookup would fail for some

attempts s ure, like o skip, reason.
-mode fix|print|diff fix

Method for emitting merged build files.

In fix mode, Gazelle writes generated and merged files to disk. print mode, it prints them to stdout. In diff mode, it prin unified diff.

In

ts a
-proto default|file|package|legacy|disable|disable_global default
Determines how Gazelle should generate rules for .proto files. See in Directives below. details
-proto_group group :value:""
Determines the proto option Gazelle uses to group .proto files into when in package mode. See details in Directives below. rules
-proto_import_prefix path
Sets the import_prefix attribute of generated proto_library This adds a prefix to the string used to import .proto files li the srcs attribute of generated rules. Equivalent to the # gazelle:proto_import_prefix directive. See details in `Direct

rules. sted in

ives`_ below.

-repo_root dir

The root directory of the repository. Gazelle normally infers this directory containing the WORKSPACE file.

Gazelle will not process packages outside this directory.

to be the
-lang lang1,lang2,... ""

Selects languages for which to compose and index rules.

By default, all languages that this Gazelle was built with are proc

essed.
-cpuprofile filename ""

If specified, gazelle uses [runtime/pprof](https://pkg.go.dev/runti CPU profiling information from the command and save it to the given

By default, this is disabled

me/pprof#StartCPUProfile) to collect

file.

-memprofile filename ""

If specified, gazelle uses [runtime/pprof](https://pkg.go.dev/runti memory a profile information from the command and save it to a file

By default, this is disabled

me/pprof#WriteHeapProfile) to collect .

update-repos

The update-repos command updates repository rules. It can write the rules to either the WORKSPACE (by default) or a .bzl file macro function. It can be used to add new repository rules or update existing rules to the specified version. It can also import repository rules from a go.mod or a go.work file.

WARNING: This command is mainly used for managing external Go dependencies in Bazel's WORKSPACE mode. For managing external Go dependencies in Bazel's BzlMod mode, please check: https://github.com/bazelbuild/rules_go/blob/master/docs/go/core/bzlmod.md#external-dependencies

# Add or update a repository to latest version by import path
$ gazelle update-repos example.com/new/repo

# Add or update a repository to specified version/commit by import path
$ gazelle update-repos example.com/new/repo@v1.3.1

# Import repositories from go.mod
$ gazelle update-repos -from_file=go.mod

# Import repositories from go.work
$ gazelle update-repos -from_file=go.work

# Import repositories from go.mod and update macro
$ gazelle update-repos -from_file=go.mod -to_macro=repositories.bzl%go_repositories

# Import repositories from go.work and update macro
$ gazelle update-repos -from_file=go.work -to_macro=repositories.bzl%go_repositories

The following flags are accepted:

Name Default value
-from_file lock-file

Import repositories from a file as go_repository rules. These rules will be added to the bottom of the

The lock file format is inferred from the file name. go.mod and `go.work are all supported.

WORKSPACE file or merged with existing rules.
-repo_root dir

The root directory of the repository. Gazelle normally infers this to be the directory containing the WORK

Gazelle will not process packages outside this directory.

SPACE file.
-to_macro macroFile%defName

Tells Gazelle to write new repository rules into a .bzl macro function rather than the WORKSPACE file.

The repository_macro directive should be added to the WORKSPACE in order for future Gazelle calls to r

ecognize the repos defined in the macro file.
-prune true|false false
When true, Gazelle will remove go_repository rules that no longer have equivalent repos in the go.mod This flag can only be used with-from_file``. `` file.
-build_directives arg1,arg2,...
Sets the build_directives attribute for the generated go_repository rule(s).
-build_external external|vendored
Sets the build_external attribute for the generated go_repository rule(s).
-build_extra_args arg1,arg2,...
Sets the build_extra_args attribute for the generated go_repository rule(s).
-build_file_generation auto|on|off
Sets the build_file_generation attribute for the generated go_repository rule(s).
-build_file_names file1,file2,...
Sets the build_file_name attribute for the generated go_repository rule(s).
-build_file_proto_mode default|package|legacy|disable|disable_global
Sets the build_file_proto_mode attribute for the generated go_repository rule(s).
-build_tags tag1,tag2,...
Sets the build_tags attribute for the generated go_repository rule(s).

Directives

Gazelle can be configured with directives, which are written as top-level comments in build files. Most options that can be set on the command line can also be set using directives. Some options can only be set with directives.

Directive comments have the form # gazelle:key value. For example:

load("@io_bazel_rules_go//go:def.bzl", "go_library")

# gazelle:prefix github.com/example/project
# gazelle:build_file_name BUILD,BUILD.bazel

go_library(
    name = "go_default_library",
    srcs = ["example.go"],
    importpath = "github.com/example/project",
    visibility = ["//visibility:public"],
)

Directives apply in the directory where they are set and in subdirectories. This means, for example, if you set # gazelle:prefix in the build file in your project's root directory, it affects your whole project. If you set it in a subdirectory, it only affects rules in that subtree.

The following directives are recognized:

Directive Default value
# gazelle:build_file_name names BUILD.bazel,BUILD
Comma-separated list of file names. Gazelle recogni build files. New files will use the first name in t your project contains non-Bazel files named ``BUILD case-insensitive file systems). zes these files as Bazel his list. Use this if (orbuild`` on
# gazelle:build_tags foo,bar none

List of Go build tags Gazelle will consider to be t constraints when generating Go rules. It assumes ce certain platforms (for example, amd64,linux). I tags are true (for example, go1.8). It consider (for example, ignore). This flag overrides that

Bazel may still filter sources with these tags. Use bazel build --define gotags=foo,bar to set tags

rue. Gazelle applies rtain tags are true on t assumes all Go release s other tags to be false behavior.

at build time.

# gazelle:exclude pattern n/a
Prevents Gazelle from processing a file or director doublestar.Match pattern matches. If the pattern Gazelle won't include it in any rules. If the patte Gazelle won't recurse into it. This directive may b multiple patterns, one per line.
y if the given

refers to a source file,

rn refers to a directory, e repeated to exclude
# gazelle:follow pattern n/a

Instructs Gazelle to follow a symbolic link to a di given doublestar.Match pattern matches. Normally links unless they point outside of the repository r

Care must be taken to avoid visiting a directory mo The # gazelle:exclude directive may be used to recursing into a directory.

rectory within the repository if the , Gazelle does not follow symbolic oot.

re than once. prevent Gazelle from

# gazelle:go_generate_proto true
Instructs Gazelle's Go extension whether to generat proto_library rules generated by the Proto exte Gazelle will generate go_proto_library and go# gazelle:proto. When this directive isfalse proto_library rules. If there are any pre-gener regular Go files. e go_proto_library rules for nsion. When this directive is true _libraryaccording to, the Go extension will ignore any ated Go files, they will be treated as
# gazelle:go_test mode default

Tells Gazelle how to generate rules for _test.go fi

  • default: One go_test rule will be generat all _test.go files in the directory.
  • file: A distinct go_test rule will be gen package directory.

les. Valid values are:

ed whose srcs includes

erated for each _test.go file in the

# gazelle:go_grpc_compilers @io_bazel_rules_go//proto:go_grpc
The protocol buffers compiler(s) to use for buildin Multiple compilers, separated by commas, may be spe Omit the directive value to reset go_grpc_compile See `Predefined plugins`_ for available options; co@io_bazel_rules_go//proto:gofast_grpcand@io_bazel_rules_go//proto:gogofaster_grpc``.

g go bindings for gRPC. cified. rs`` back to the default.

mmonly used options include

# gazelle:go_naming_convention inferred automatically

Controls the names of generated Go targets.

Valid values are:

  • go_default_library: Library targets are named are named go_default_test.
  • import: Library and test targets are named af path. For example, example.repo/foo is named foo` Major version suffixes like/v2are dropped. For a main package with a binaryfoobin, thefoobin_test``.
  • import_alias: Same as import, but an algo_default_library`` to ensure backwards compat

If no naming convention is set, Gazelle attempts to use by reading the root build file and build files subdirectories. If no Go targets are found, Gazelle

go_default_library, test targets

ter the last segment of their import

, and the test target is foo_test`.

names are instead foobin_lib and

iastarget is generated named ibility. infer the convention in in immediate defaults toimport``.

# gazelle:go_naming_convention_external n/a
Controls the default naming convention used when re external repositories with unknown naming conventio as go_naming_convention. solving libraries in ns. Accepts the same values
# gazelle:go_proto_compilers @io_bazel_rules_go//proto:go_proto
The protocol buffers compiler(s) to use for buildin Multiple compilers, separated by commas, may be spe Omit the directive value to reset go_proto_compil See `Predefined plugins`_ for available options; co@io_bazel_rules_go//proto:gofast_protoand@io_bazel_rules_go//proto:gogofaster_proto``.

g go bindings. cified. ers`` back to the default.

mmonly used options include

# gazelle:ignore n/a
Prevents Gazelle from modifying the build file. Gaz rules in the build file and may modify build files elle will still read in subdirectories.
# gazelle:importmap_prefix path See below

A prefix for importmap attributes in library ru an importmap on a go_library or go_proto_ concatenating this with the relative path from the prefix is set to the library. For example, ifimp to "x/example.com/repo" in the build file //f then a library infoo/bar/bazwill have thei "x/example.com/repo/baz".

importmap is not set when it matches importpa As a special case, when Gazelle enters a directory setsimportmap_prefixto a string based on the location of the vendor directory. If you wish to ov to setimportmap_prefix`` explicitly in the vendo

les. Gazelle will set libraryby directory where the ortmap_prefix is set oo/bar:BUILD.bazel, mportmap of

th. namedvendor``, it repository name and the erride this, you'll need r directory.

:direc:`# gazelle:map_kind from_kind to_kind to_kin d_load` | n/a

Customizes the kind of rules generated by Gazelle.

As a separate step after generating rules, any new kind replaced with to_kind. This means that t parameters and behave similarly. Most commonly, this would be used to replace the ru custom macros. For example,gazelle:map_kind go_binary go_deployable //tools/ produce rules of kind go_deployable as loaded f go_binary, for this directory or within.

Existing rules of the old kind will be ignored. To kind to a mapped kind, use buildozer.

rules of kind from_kind have their o_kindmust accept the same les provided byrules_gowith go:def.bzl would configure Gazelle to rom //tools/go:def.bzl instead of

switch your codebase from a builtin

# gazelle:prefix path n/a
A prefix for importpath attributes on library r an importpath on a go_library or go_proto concatenating this with the relative path from the prefix is set to the library. Most commonly,pref name of a repository in the root directory of a rep in this repository, prefix is set in //:BUILDgithub.com/bazelbuild/bazel-gazelle. Thego_l //cmd/gazelle is assigned the importpath "github.com/bazelbuild/bazel-gazelle/cmd/gazelle" As a special case, when Gazelle enters a directoryprefixto the empty string. This automatically an intuitiveimportpath``.

ules. Gazelle will set _libraryby directory where the ix is set to the ository. For example, .bazelto ibrary in

. namedvendor``, it sets gives vendored libraries

# gazelle:proto mode default

Tells Gazelle how to generate rules for .proto file

  • default: proto_library, go_proto_librar rules are generated using@io_bazel_rules_go//p of each rule may be generated per directory. This
  • file: a proto_library rule is generated f
  • package: multiple proto_library and ``go may be generated in the same directory. .proto fi rules based on their package name or another opti
  • legacy: filegroup rules are generated for @io_bazel_rules_go//proto:go_proto_library.bzl` rules must be written by hand. Gazelle will run i ifgo_proto_library.bzl`` is loaded to avoid di projects, but this can be overridden with a direc
  • disable: .proto files are ignored. Gazelle wi automatically if go_proto_library is loaded f but this can be overridden with a directive.
  • disable_global: like disable mode, but al using any special cases in dependency resolution Google APIs. Useful for avoiding build-time depen

This directive applies to the current directory and special case, when Gazelle enters a directory named mode isn't set explicitly in a parent directory or Gazelle will run in disable mode. Additionally, @io_bazel_rules_go//proto:go_proto_library.bzl will run in legacy mode.

  1. Valid values are:
y, andgo_libraryroto:def.bzl. Only one

is the default mode.

or every .proto file. proto_libraryrules les are grouped into on (seeproto_group). use by `.go_proto_libraryn this mode automatically srupting existing tive. ll run in this mode rom any other source, so prevents Gazelle from for Well Known Types and dencies on protoc. subdirectories. As avendor``, if the proto on the command line, if the file is loaded, Gazelle
# gazelle:proto_group option ""

This directive is only effective in package *

Specifies an option that Gazelle can use to group . For example, when set to go_package, .proto fil option go_package will be grouped together.

When this directive is set to the empty string, Gaz by their proto package statement.

Rule names are generated based on the last run of i in the package name. For example, if the package is proto_library rule will be named baz_proto.

mode (see above).*

proto files into rules. es with the same

elle will group packages

dentifier characters

"foo/bar/baz", the

# gazelle:proto_import_prefix path n/a

Sets the import_prefix attribute of generated This adds a prefix to the string used to import. the srcs attribute of generated rules.

For example, if the target //a:b_proto has srimport_prefix = "github.com/x/y", thenb.prot with the string "github.com/x/y/a/b.proto".

proto_libraryrules. proto files listed in

cs = ["b.proto"]and o should be imported

# gazelle:proto_strip_import_prefix path n/a

Sets the strip_import_prefix attribute of genera This is a prefix to strip from the strings used to

If the prefix starts with a slash, it's intepreted root. Otherwise, it's relative to the directory con The package-relative form is only useful when a sin .proto files in subdirectories. Gazelle doesn't this, so only paths with a leading slash should be a warning when the package-relative form is used.

For example, if the target //proto/a:b_proto ha and strip_import_prefix = "/proto", then b.pr with the string"a/b.proto"``.

ted proto_library rules. import .proto files.

relative to the repository taining the build file. gle build file covers generate build files like used. Gazelle will print

s srcs = ["b.proto"] oto`` should be imported

# gazelle:resolve ... n/a

Specifies an explicit mapping from an import string Dependency resolution. The format for a resolve

# gazelle:resolve source-lang import-lang import- *source-langis the language of the source cod *import-langis the language importing the lib the same assource-langbut may differ with g example, when resolving dependencies for ago_p

source-lang would be "proto" and importimport-lang`` may be omitted if it is the same

  • import-string is the string used in source co
  • label is the Bazel label that Gazelle should

For example:

# gazelle:resolve go example.com/foo //foo:go_def
# gazelle:resolve proto go foo/foo.proto //foo:fo

to a label for

directive is:

string labele being imported. rary. This is usually enerated code. For roto_library, -langwould be"go". assource-lang. de to import a library. write indeps``.

ault_library o_go_proto

# gazelle:resolve_regexp ... n/a

Specifies an explicit mapping from an import regex Dependency resolution. The format for a resolve

# gazelle:resolve_regexp source-lang import-lang *source-langis the language of the source cod *import-langis the language importing the lib the same assource-langbut may differ with g example, when resolving dependencies for ago_p

source-lang would be "proto" and importimport-lang`` may be omitted if it is the same

* import-string-regex is the regex applied to t

If it matches, that import will be resolved to th

  • label is the Bazel label that Gazelle should

For example:

# gazelle:resolve_regexp go example.com/.* //foo:
# gazelle:resolve_regexp proto go foo/.*\.proto /

to a label for directive is:

import-string-regex labele being imported. rary. This is usually enerated code. For roto_library, -langwould be"go". assource-lang. he import in the source code. e label specified below. write indeps``.

go_default_library /foo:foo_go_proto

# gazelle:go_visibility label n/a
By default, internal packages are only visible to i internal packages should be visible to additionally times, adding a list of labels. ts siblings. This directive adds a label . This directive can be used several
# gazelle:lang lang1,lang2,... n/a
Sets the language selection flag for this and desce index and generate rules for only the languages nam ndent packages, which causes gazelle to ed in this directive.
# gazelle:default_visibility visibility n/a

Comma-separated list of visibility specifications. This directive adds the visibility specifications f

For example:

# gazelle:default_visibility //foo:__subpackages_

or this and descendant packages.

_,//src:__subpackages__

Gazelle also reads directives from the WORKSPACE file. They may be used to discover custom repository names and known prefixes. The fix and update commands use these directives for dependency resolution. update-repos uses them to learn about repository rules defined in alternate locations.

WORKSPACE Directive Default value
# gazelle:repository_macro [+]macroFile%defName n/a

Tells Gazelle to look for repository rules in a macro in a .bzl file repeated multiple times. The macro can be generated by calling update-repos with the ``to

The directive can be prepended with a "+", which will tell Gazelle t within any macros called by the specified macro.

. The directive can be

_macro`` flag.

o also look for repositories

# gazelle:repository rule_kind attr1_name=attr1_value ... n/a

Specifies a repository rule that Gazelle should know about. The dire and can be declared from within a macro definition that Gazelle know directive must define a rule kind and a name attribute, but it can d

This is useful for teaching Gazelle about repos declared in external to override an actual repository rule. For example, a git_reposito could be overriden with the directive: .. code:: bzl # gazelle:repository go_repository name=org_golang_x_tools importp Gazelle would then proceed as iforg_golang_x_tools`` was declared

ctive can be repeated multiple times, s about. At the very least the efine extra attributes after that.

macros. The directive can also be used

ryrule fororg_golang_x_toolsath=golang.org/x/tools as ago_repository`` rule.

Keep comments

In addition to directives, Gazelle supports # keep comments that protect parts of build files from being modified. # keep may be written before a rule, before an attribute, or after a string within a list.

# keep comments might take one of 2 forms; the # keep literal or a description prefixed by # keep:.

Example

Suppose you have a library that includes a generated .go file. Gazelle won't know what imports to resolve, so you may need to add dependencies manually with # keep comments.

load("@io_bazel_rules_go//go:def.bzl", "go_library")
load("@com_github_example_gen//:gen.bzl", "gen_go_file")

gen_go_file(
    name = "magic",
    srcs = ["magic.go.in"],
    outs = ["magic.go"],
)

go_library(
    name = "go_default_library",
    srcs = ["magic.go"],
    visibility = ["//visibility:public"],
    deps = [
        "@com_github_example_gen//:go_default_library",  # keep
        "@com_github_example_gen//a/b/c:go_default_library",  # keep: this is also important
    ],
)

Dependency resolution

One of Gazelle's most important jobs is resolving library import strings (like import "golang.org/x/sys/unix") to Bazel labels (like @org_golang_x_sys//unix:go_default_library). Gazelle follows the rules below to resolve dependencies:

  1. If the import to be resolved is part of a standard library, no explicit dependency is written. For example, in Go, you don't need to declare that you depend on "fmt".
  2. If a # gazelle:resolve directive matches the import to be resolved, the label at the end of the directive will be used.
  3. If proto rule generation is enabled, special rules will be used when importing certain libraries. These rules may be disabled by adding # gazelle:proto disable_global to a build file (this will affect subdirectories, too) or by passing -proto disable_global on the command line.
    1. Imports of Well Known Types are mapped to rules in @io_bazel_rules_go//proto/wkt.
    2. Imports of Google APIs are mapped to @go_googleapis.
    3. Imports of github.com/golang/protobuf/ptypes, descriptor, and jsonpb are mapped to special rules in @com_github_golang_protobuf. See Avoiding conflicts with proto rules.
  4. If the import to be resolved is in the library index, the import will be resolved to that library. If -index=true, Gazelle builds an index of library rules in the current repository before starting dependency resolution, and this is how most dependencies are resolved.
    1. For Go, the match is based on the importpath attribute.
    2. For proto, the match is based on the srcs attribute.
  5. If -index=false and a package is imported that has the current go_prefix as a prefix, Gazelle generates a label following a convention. For example, if the build file in //src set the prefix with # gazelle:prefix example.com/repo/foo, and you import the library "example.com/repo/foo/bar, the dependency will be "//src/foo/bar:go_default_library".
  6. Otherwise, Gazelle will use the current external mode to resolve the dependency.
    1. In external mode (the default), Gazelle will transform the import string into an external repository label. For example, "golang.org/x/sys/unix" would be resolved to "@org_golang_x_sys//unix:go_default_library". Gazelle does not confirm whether the external repository is actually declared in WORKSPACE, but if there is a go_repository in WORKSPACE with a matching importpath, Gazelle will use its name. Gazelle does not index rules in external repositories, so it's possible the resolved dependency does not exist.
    2. In static mode, Gazelle has the same behavior as external mode, except that it will not call out to the network for resolution when no matching import is found within WORKSPACE. Instead, it will skip the unknown import. This is the default mode for go_repository rules.
    3. In vendored mode, Gazelle will transform the import string into a label in the vendor directory. For example, "golang.org/x/sys/unix" would be resolved to "//vendor/golang.org/x/sys/unix:go_default_library". This mode is usually not necessary, since vendored libraries will be indexed and resolved using rule 4.

Fix command transformations

Gazelle will generate and update build files when invoked with either gazelle update or gazelle fix (update is the default). Both commands perform several transformations to fix deprecated usage of the Go rules. update performs a safe set of tranformations, while fix performs some additional transformations that may delete or rename rules.

The following transformations are performed:

Migrate library to embed (fix and update): Gazelle replaces library attributes with embed attributes.

Migrate gRPC compilers (fix and update): Gazelle converts go_grpc_library rules to go_proto_library rules with compilers = ["@io_bazel_rules_go//proto:go_grpc"].

Flatten srcs (fix and update): Gazelle converts srcs attributes that use OS and architecture-specific select expressions to flat lists. rules_go filters these sources anyway.

Squash cgo libraries (fix only): Gazelle will remove cgo_library rules named cgo_default_library and merge their attributes with a go_library rule in the same package named go_default_library. If no such go_library rule exists, a new one will be created. Other cgo_library rules will not be removed.

Squash external tests (fix only): Gazelle will squash go_test rules named go_default_xtest into go_default_test. Earlier versions of rules_go required internal and external tests to be built separately, but this is no longer needed.

Remove legacy protos (fix only): Gazelle will remove usage of go_proto_library rules loaded from @io_bazel_rules_go//proto:go_proto_library.bzl and filegroup rules named go_default_library_protos. Newly generated proto rules will take their place. Since filegroup isn't needed anymore and go_proto_library has different attributes and was always written by hand, Gazelle will not attempt to merge anything from these rules with the newly generated rules.

This transformation is only applied in the default proto mode. Since Gazelle will run in legacy proto mode if go_proto_library.bzl is loaded, this transformation is not usually applied. You can set the proto mode explicitly using the directive # gazelle:proto default.

Update loads of gazelle rule (fix and update): Gazelle will remove loads of gazelle from @io_bazel_rules_go//go:def.bzl. It will automatically add a load from @bazel_gazelle//:def.bzl if gazelle is not loaded from another location.

About

Gazelle is a Bazel build file generator for Bazel projects. It natively supports Go and protobuf, and it may be extended to support new languages and custom rule sets.

Resources

License

Security policy

Stars

Watchers

Forks

Packages

No packages published