Basics
BUILD files are “bare facts” that describe the source code and its dependencies. These facts are mostly trivial to derive from the source code itself. So why force engineers to write these by hand? At a high level, it operates following the Visitor pattern:- Walk the source tree like Bazel does, respecting
.bazelignoreand similar config. - When descending into a directory, read any
BUILDfile’s “directive” comments for configuration. - Locate source files of interest, typically by file extension.
- Declare Bazel targets and their import/export edges.
- Which targets to generate is determined by the source files found and language configuration.
- Imports are found by parsing import statements — similar to how an IDE’s language server works.
- Exports are usually inferred from file paths or package declarations in source files.
- After the walk, resolve target imports to Bazel labels and write them into attributes like
deps. - Merge updates into the
BUILDfile, or create one if the directory had none.
BUILD file are preserved.
To opt-out of Gazelle managing a syntax element, use the #keep comment, for example:
The bazel-gazelle repo also has some Go-specifics, like the
go_repository rule, which runs Gazelle on third-party Go packages to generate their BUILD files dynamically.
