3.4.2 Gazelle (BUILD File Generation)
Gazelle is a BUILD-file generator. Once its rule is wired into the repo, the daily loop becomes: edit a source file, add or remove an import, run bazel run //:gazelle, commit the refreshed BUILD.bazel alongside the code change. You stop hand-maintaining srcs and deps. The tool infers them from what the source actually imports.1,2 Custom extensions and directive-level configuration are covered in T4 Gazelle. To maintain the repository, you first need to understand what Gazelle updates, which edits it preserves, and how to run it consistently.
Bootstrap the repository target
Choose and review a Gazelle release in the Bazel Central Registry, then pin it in MODULE.bazel. For example, the pin used here is:3
bazel_dep(name = "gazelle", version = "0.51.3")
Expose the binary through a checked-in target (the exact macro and extensions depend on the languages in the repo), then make bazel run //:gazelle the documented update command. Commit the resulting BUILD.bazel diff with the source change and run the same command in CI to detect drift. The pin, target, and command are the reproducible contract. A globally installed gazelle binary is useful for evaluation but should not be the team's source of truth.
Why generate BUILD files at all
Most of a BUILD file is a restatement of facts that already exist in source. The srcs list mirrors files on disk. The deps list mirrors import, include, or require statements in those files. Roughly 80% of a typical BUILD file is information a tool can extract from the source with no guesswork — leaving about 20% (deployment metadata, visibility, hand-tuned attributes) that a human genuinely has to write.1
Hand-writing that 80% is Bazel's phase zero: the step you have to do before Bazel even begins its own loading, analysis, and execution phases.1 New developers land on it immediately ("why do I have to repeat my imports in a separate file?"), and in a large repo it becomes the dominant source of stale deps, forgotten srcs entries, and merge conflicts on generated-looking files. Gazelle answers that friction: developers write code, the tool turns it into BUILD structure.
How Gazelle updates a BUILD file
Gazelle processes updates in four ordered stages. Names below such as Gen and Empty come from Gazelle's original (v1) extension API, which the upstream description uses.2
- Load. Gazelle walks the directory tree, parses existing
BUILD/BUILD.bazelfiles, and lists the files and subdirectories in each directory. Entries matched by# gazelle:excludedirectives or.bazelignoreare skipped during this walk.2 - Generate. In each directory Gazelle has been asked to update, a language extension reads the source files and returns the rules the BUILD file should contain (a
Genlist) plus rules that should no longer exist (anEmptylist).2 - Resolve. Gazelle maps every import string it saw in sources to a Bazel label and fills in
depson the generated rules. Cross-directory resolution uses an in-memory index built from library rules elsewhere in the repo.2 - Write. The in-memory edits are formatted (the same machinery buildifier uses) and written back to disk.2
The upstream repository keeps the supported orientation path explicit: how-gazelle-works.md explains this pipeline, while extend.md moves from the user workflow to the Language interface and extension tests.4 That separation is useful during diagnosis — verify generator behavior in the workflow document before escalating into a particular language implementation.
Generation and resolution both produce structured rule objects, and both call into the same merge machinery (merger.MergeFile) to reconcile those objects with the rules already present in the file.2 That merge is what makes Gazelle safe to re-run over a hand-edited repo.
Merging without overwriting
Gazelle merges, it does not overwrite.1,2 An existing rule with the same kind and name as a generated rule (e.g., both are a go_library named lib) keeps its position and its hand-written surroundings. Only its machine-managed attributes get refreshed.2
Attributes are classified per rule kind as mergeable or not:2
- Mergeable attributes — typically
srcs,deps. Gazelle may overwrite these, because they are meant to be derived from source. - Non-mergeable attributes — typically
visibility. If the attribute is missing, Gazelle may add a default value. If a human has set one, Gazelle leaves it alone.
The explicit escape hatch is the # keep comment. It can be placed on a rule, on an attribute, or on an individual list value. Gazelle leaves anything marked # keep alone:2
go_library(
name = "lib",
srcs = [
"lib.go",
"generated.go", # keep
],
visibility = ["//visibility:public"],
)
Two useful corollaries follow from the merge contract:
- When every real source for a rule disappears, the language extension returns the rule in its
Emptylist and Gazelle deletes it.2 - The
BUILDfile itself is never deleted, even when it ends up empty, because removing it could silently let a parent package'sglob()match files it previously could not.2
Languages and the extension model
Gazelle's lineage is Go-specific. Inside Google, a tool named Glaze generated BUILD files for Go packages fast enough — around 50ms — that developers ran it on every editor save. Outside Google, Gazelle was created in 2016 and grew a generic extension interface in 2018 so other languages could plug in.5 Go and Protocol Buffers ship built in. Everything else is a plugin.
In the v1 extension API, each plugin implements Gazelle's Language interface — with a GenerateRules method that turns a directory of source files into rules, plus an Imports / Resolve pair that maps language-specific import specs to Bazel labels.6 Common extensions in the open-source ecosystem include plugins for Python, JavaScript/TypeScript, Java, Kotlin, C/C++, Scala, and Haskell, with maintainers spread across bazel-contrib, Aspect, EngFlow, and VirtusLab.1,6
For a concrete non-Go contract, gazelle_rust pairs a runnable Rust workspace
with checked-in BUILD.in → BUILD.out cases for Cargo aliases, build scripts,
features, tests, and examples.7 Those golden pairs define the expected
end-to-end output and provide small reproductions. Locating a discrepancy in
generation, dependency resolution, or merge behavior still requires a narrower
test or inspection of that stage. Rust-specific directives are not part of
Gazelle's universal API.
Adding a plugin can produce BUILD files that load but do nothing useful. This
happens when the plugin's generated rule kinds are not the rules your repository
should load. gazelle_ts emits abstract kinds such as ts_library and
ts_test. Until you map them to real rules, it falls back to filegroups that
keep BUILD files loadable but do not typecheck, test, or bundle anything.8
The mapping is a directive in the root BUILD.bazel. Each line names the
generated kind, the kind to write instead, and the file that defines it:
# gazelle:map_kind ts_library ts_library //tools:ts.bzl
# gazelle:map_kind ts_test ts_test //tools:ts.bzl
Here //tools:ts.bzl holds your own macros, often wrappers around Aspect's
ts_project and js_* rules. Gazelle then writes
load("//tools:ts.bzl", "ts_library") into generated files, so the macro, not
the plugin, decides what a ts_library actually builds.8
Version and extension boundaries
Gazelle v2 changes the extension API on purpose, so that new features can be
added without breaking every plugin each time.9 Your daily loop stays the
same: edit source, regenerate, review the diff. The risk sits in the binary,
which combines plugins from different authors that will not all move to v2 at
once. A v1/v2 compatibility layer lets one binary run plugins written against
either API, so each plugin can migrate on its own schedule.9 That layer is
not in the 0.51.3 pinned above. It first appears in 0.52.0, so check the
release you choose before adding a v2 plugin.4
T4.5 Extension Architecture explains the v2 interfaces for extension authors.
Sometimes no plugin generates what your repository needs, such as a Jest test
target for every group of test files. map_kind cannot express that, because
it only renames kinds that a plugin already emits. The classic answer is a Go
extension compiled into gazelle_binary, which brings a Go toolchain into the
repository and a rebuild with every change. Aspect's Orion extension instead
loads generators written in Starlark at runtime, so editing one needs no
recompilation.10,11,12 Choose a maintained language plugin first.
T4.7 Language Extensions compares Orion with compiled extensions.
Where Gazelle fits in the workflow
Gazelle modifies the source tree. A normal Bazel action is not allowed to do that — sandboxing, caching, and hermeticity all assume actions write only into their declared outputs under bazel-out/. So Gazelle runs outside the build graph, as a pre-build step that mutates the checkout before bazel build reads it. This is the same boundary described in 3.7.1 Bazel's Output Boundary and picked up again in 3.7.2 Workflows Outside Bazel: Gazelle is task-runner territory, not a build action.
Two integration patterns follow from that positioning:
- Locally.
bazel run //:gazelleafter touching imports, or wire it into an editor save hook for languages where it is fast enough.5 - In CI. Run Gazelle against the clean checkout and fail the job if any BUILD file changed. That enforces "no hand-edited BUILD files drift from source" without relying on every developer to remember the command. The pattern holds up at scale: one ~1M-file monorepo with more than 10,000 commits per week runs it on every change.13
The build-maintenance Gazelle plan helper is a reviewable sketch of that workflow — it does not invoke Gazelle (the example is intentionally lightweight and standalone on Bazel 9.0.0), but it prints the literal gazelle -build_file_name=BUILD.bazel ./... step plus the git diff and buildozer cleanup that a real ruleset's bazel run //:gazelle invocation would feed into.
For sibling tooling that complements Gazelle, 3.4.3 Buildozer is the CLI for scripted BUILD edits — useful when you want to script a change across many existing targets rather than regenerate them from source.
Lazy indexing and version defaults
Speed decides how Gazelle gets used. At around 50ms it can run on every file save. At 10 seconds it becomes a manual step, and at 100 seconds teams drift back to hand-editing BUILD files.5 In a large repository the slow part is usually indexing. With eager indexing, Gazelle reads BUILD files across the whole repository even for a one-directory edit, because an import string alone does not say which directory holds the target that provides it.
Lazy indexing (-index=lazy) lets each language extension name the directories
it needs for resolution, based on the imports it saw. Gazelle indexes those
directories, the ones you asked it to update, and their parents for
configuration. Add -r=false when you also want Gazelle to update only the
directory you name:5,4
bazel run //:gazelle -- -index=lazy -r=false path/to/pkg
When libraries live somewhere an extension cannot guess from the import path,
such as a vendor directory named third_party/go, a search directive tells it
where to look. For Go, that is # gazelle:go_search third_party/go. In one
large Go monorepo, lazy indexing cut a run from 25s to 352ms. Go, proto, and
C/C++ extensions support lazy indexing. Other plugins may not, or may need their
own search directives.5
The default depends on the release: 0.51.3 indexes eagerly, while
2.0.0-beta.2 indexes lazily.4 Before upgrading, check in each plugin's
documentation that it supports lazy search. T4.6 Scaling Dependency Resolution covers
measuring, profiling, and choosing an index mode in large repositories.
Gazelle loads BUILD files, generates rules from source, resolves imports to
labels, and merges the result back into the checkout. Go and Protocol Buffers
are built in. Other languages need a plugin, and the active plugins decide which
rule kinds and attributes Gazelle manages. Use # gazelle:map_kind when a
plugin's kinds must become your own macros. Use # keep to protect manual
values, review the generated diff, and check for drift in CI. Because it edits
source files, Gazelle runs before the build, not as a build action.
When you upgrade, check two things separately: which extension API each plugin uses, and which index mode the new release uses by default. A binary with the v1/v2 compatibility layer lets plugins migrate one at a time. Lazy indexing makes one-directory runs fast enough for everyday use, but only with plugins that support it.
Check your understanding · 3 questions
1.What does Gazelle's '# keep' comment do, and where can it be placed?
Select one answer
2.True or false about Gazelle's behavior:
Choose True or False for each sentence
3.What is lazy indexing in Gazelle and why does it matter for developer experience?
Select one answer
Footnotes
-
Mastering Bazel Build File Automation with Aspect CLI and Gazelle — Alex Eagle's "~80% of a BUILD file is inferable from source" framing, the "phase zero" argument, Gazelle's merge-not-overwrite contract, the list of supported languages, the Go-only extension API and Starlark alternative ↩1 ↩2 ↩3 ↩4 ↩5
-
How Gazelle Works — upstream description of the Load / Generate / Resolve / Write pipeline,
# gazelle:excludeand.bazelignorebehavior during Load, theGen/Emptylists, mergeable vs non-mergeable attributes,# keepcomments, empty-rule deletion, and why empty BUILD files are preserved ↩1 ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 ↩9 ↩10 ↩11 ↩12 ↩13 -
Gazelle 0.51.3 in the Bazel Central Registry — release page for the example pin. Check the registry for newer releases before choosing yours. ↩
-
Gazelle — BUILD-file generation and language-extension framework —
how-gazelle-works.mddocuments the generator pipeline andextend.mddefines the language-extension route. The repository'sv2.mdandextend.mddistinguish v2 optional interfaces, mixed v1/v2 extensions, and the lazy-indexing default from planned features.v2/config/config.gosetsindexLazytotruewhen registering flags. Thev2/compatpackage that adapts v1 and v2 extensions is absent atv0.51.3and present fromv0.52.0. ↩1 ↩2 ↩3 ↩4 -
Lightning-fast BUILD file generation with Gazelle lazy indexing — Glaze-to-Gazelle history and timeline, the "speed is the killer feature" thresholds (50ms / 10s / 100s), lazy indexing design (
-index=lazy,-r=false), per-repo measurements, extension coverage as reported in 2025 ↩1 ↩2 ↩3 ↩4 ↩5 -
Gazelle Across the Stack: Same Tool, Different Problems - Wojciech Mazur, VirtusLab — Gazelle's
Languageinterface,GenerateRules/Imports/Resolvecontract, file-based vs symbol-based resolution, and the cross-language extension ecosystem (C/C++, JVM, Scala) ↩1 ↩2 -
gazelle_rust — Gazelle language plugin for Rust — its runnable
example/shows adoption, whilegeneration_tests/cargo/records focused generator inputs and expected BUILD output. ↩ -
gazelle_ts — Gazelle language extension for TypeScript — README sections on generated kinds, the
map_kindcontract, and fallbackfilegroupbehavior. ↩1 ↩2 -
Generate build files for new rule sets with Gazelle v2 - Jay Conrod, Software Engineer, EngFlow — why v2 changes the extension API, and two-way compatibility between v1 and v2 extensions. ↩1 ↩2
-
Extend Gazelle in Starlark, not Go - Jason Bedard, Software Engineer, Aspect Build — runtime Starlark generation through Orion, with
prepareanddeclarecallbacks rather than a rebuilt Go plugin. ↩ -
Build File Generation Using AXL - Jason Bedard, Aspect Build — Orion as a Go host for Starlark generators, and why a compiled Go extension otherwise needs a rebuild. ↩
-
Aspect Gazelle — prebuilt, polyglot BUILD generation and Starlark extensions —
language/orion/README.mddocuments the hosted Starlark model and the boundary between prebuilt use and source-build setup. ↩ -
Optimizing Gazelle for Scale and Performance in Uber's Monorepo - Tyler French, Uber — the "run Gazelle, reject if BUILD files changed" CI pattern, Uber's monorepo scale (~1M files, >10K commits/week), and the run-on-save local workflow ↩