blob: c8247a65ca83d8eb12587639b9a15944050d74cf [file] [view]
# Basic Gazelle
[Gazelle](https://github.com/bazel-contrib/bazel-gazelle) is a tool that generates and updates Bazel build files. You can use it to generate build files when migrating to Bazel, to maintain existing build files, and to import external Go modules that have not been migrated to Bazel.
This example shows how to use Gazelle to generate build files for a small Go program with an external dependency.
To understand how this project works, read these files:
- `MODULE.bazel`: declares dependencies on Bazel modules, including rules_go and Gazelle.
- `go.mod`: declares dependencies on Go modules. Maintained outside of Bazel with normal Go commands like `go mod tidy`.
- `BUILD.bazel`: contains some boilerplate for running Gazelle, as well as targets generated by Gazelle.
To update generated build files, run the command below. This should be done after you add, remove, or rename source files or when you change imports.
```bash
bazel run //:gazelle
```
For example, rename `printlinks.go` to `print_links.go`, run Gazelle, and observe the change in `BUILD.bazel`.
To add a new external dependency:
1. Import the external package from any `.go` file.
1. Run `bazel run @rules_go//go -- mod tidy`. This command runs `go mod tidy` to update `go.mod` using the toolchain downloaded by `rules_go`. This command also runs `bazel mod tidy` to update `MODULE.bazel` .
1. Run `bazel run //:gazelle` again to update dependencies in `BUILD.bazel` files.