> ## Documentation Index
> Fetch the complete documentation index at: https://aspect.build/llms.txt
> Use this file to discover all available pages before exploring further.

# aspect gazelle

> Keep Bazel BUILD files in sync with aspect gazelle, covering incremental scope, smart escalation, diff-mode detection, and Aspect CLI CI examples.

`aspect gazelle` runs [Gazelle](https://registry.bazel.build/modules/gazelle) (or [`aspect_gazelle_prebuilt`](https://registry.bazel.build/modules/aspect_gazelle_prebuilt), for Starlark-defined extensions) to generate and synchronize your repository's BUILD files. On CI it detects whether BUILD files are out of sync with the source and fails the step if they are.

Run locally, `aspect gazelle` applies the fixes in place. `--check-only` defaults to `auto`: detect-only on CI, apply locally.

## Setup: choosing a gazelle binary

`aspect gazelle` drives a Gazelle binary that you point it at with [`--gazelle-target`](#gazelle-target) (default `//tools/gazelle:gazelle`). Provide the binary either way below.

### Prebuilt binary (recommended)

[`aspect_gazelle_prebuilt`](https://registry.bazel.build/modules/aspect_gazelle_prebuilt) fetches a precompiled Gazelle binary from the [aspect-gazelle](https://github.com/aspect-build/aspect-gazelle) releases. It needs no Go toolchain and no compile step, and it's the only binary that can run [Starlark/AXL extensions](https://aspect.build/docs/cli/guides/gazelle.md).

```python title="MODULE.bazel" theme={null}
# See https://github.com/aspect-build/aspect-gazelle/releases for the latest version.
bazel_dep(name = "aspect_gazelle_prebuilt", version = "0.0.26")
```

```python title="tools/gazelle/BUILD.bazel" theme={null}
load("@aspect_gazelle_prebuilt//:def.bzl", "aspect_gazelle")

aspect_gazelle(
    name = "gazelle",
    languages = ["go", "proto", "python"],  # whichever fit your repo
    extensions = ["//tools/gazelle:shell.axl"],
)
```

**Advantages:**

* No Go toolchain download and no first-run compile of the gazelle binary: developers fetch a cached prebuilt artifact instead.
* Runs [Starlark/AXL extensions](https://aspect.build/docs/cli/guides/gazelle.md), so you can write generators without the Go extension API.
* Exposes prebuilt-only flags like `-progress` and `-cache` (see [Additional Gazelle flags](#additional-gazelle-flags)).
* Avoids the bootstrapping trap where a broken `BUILD` file referenced by your gazelle binary's `load` statements stops gazelle from compiling, and so from fixing that file.

### Building from source

Build Gazelle with the upstream `gazelle_binary` macro from [`bazel-contrib/bazel-gazelle`](https://github.com/bazel-contrib/bazel-gazelle), composing whatever language extensions you need (including custom first-party Go extensions). This requires a Go toolchain.

```python title="tools/gazelle/BUILD.bazel" theme={null}
load("@bazel_gazelle//:def.bzl", "gazelle", "gazelle_binary")

gazelle_binary(
    name = "gazelle_binary",
    languages = [
        "@bazel_gazelle//language/proto",
        "@bazel_gazelle//language/go",
        "@rules_python//gazelle",
        "//tools/gazelle/my_extension",  # a custom first-party go_library
    ],
)

gazelle(
    name = "gazelle",
    gazelle = ":gazelle_binary",
)
```

**Advantages:**

* Full control: compose any language extension and write custom generators against Gazelle's Go [`Language` interface](https://pkg.go.dev/github.com/bazel-contrib/bazel-gazelle/language#Language).
* No dependency on which extensions ship in the prebuilt binary.

The tradeoff is build cost and complexity: a Go (and sometimes cgo) toolchain, a recompile whenever an extension changes, and the bootstrapping trap noted above.

## Incremental mode: only touch changed directories

On a large repo, running Gazelle over the whole tree on every change is slow. `--scope=changed` restricts it to directories that contain changed files:

```shell theme={null}
aspect gazelle --scope=changed   # only directories with changed files
aspect gazelle --scope=all       # full workspace (default)
```

The changed files are found the same way as for [`aspect format`](https://aspect.build/docs/cli/tasks/format#how-change-detection-works), with the same `--base-ref` and `--merge-base` flags. `--changed-file-pattern` narrows which changed files count, for example to the languages your Gazelle plugins cover.

**Escalation:** some changes need a whole-repo run, and two things trigger one. By default a change to `BUILD.bazel` or `MODULE.bazel` escalates to `--scope=all`, because those files can affect dependency resolution across the repo. Change detection failing to resolve a base escalates too, with the same `--merge-base=<sha>` / `--base-ref` advice `aspect format` gives. Setting the patterns replaces the defaults, so include them if you want to keep them:

```python title=".aspect/config.axl" theme={null}
def config(ctx: ConfigContext):
    ctx.tasks["gazelle"].args.scope_all_on_change = [
        "BUILD.bazel",
        "MODULE.bazel",
        "go.sum",           # Go module changes require a full re-index
    ]
```

## Watch mode

Pass `--watch` to keep BUILD files in sync while you edit. After the first run the task stays running, watches the Bazel workspace, and reruns Gazelle after each settled batch of file changes:

```shell theme={null}
aspect gazelle --watch
aspect gazelle --watch --scope=changed
```

A failed run doesn't stop the task. It waits for the next change. Changes under `.git`, `.jj` and Bazel's convenience symlinks don't trigger a rerun. Stop the task with Ctrl-C.

Without `--watch`, `aspect gazelle` runs once and exits.

## How drift detection works

`aspect gazelle` always runs Gazelle with `-mode=diff`, whatever other flags you pass:

1. Gazelle runs once with `-mode=diff` and produces a unified diff without writing any files.
2. The task reads the diff to decide whether BUILD files are out of sync. It uses the diff output, not Gazelle's exit code.
3. With `--check-only=true` (the `auto` result on CI), a non-empty diff raises the `--severity` verdict.
4. With `--check-only=false` (the `auto` result locally), the task applies the diff with `git apply -p0`.

One Gazelle run gives both the verdict and the patch, and applying the captured diff is faster than running Gazelle a second time.

## Configuration

### Gazelle target

```shell theme={null}
aspect gazelle --gazelle-target=//tools/gazelle:gazelle
```

```python title=".aspect/config.axl" theme={null}
def config(ctx: ConfigContext):
    ctx.tasks["gazelle"].args.gazelle_target = "//tools/gazelle:gazelle"
```

### Reacting to drift

```shell theme={null}
aspect gazelle --severity=fail    # exits 1 when BUILD files need updating
aspect gazelle --severity=warn    # status is a warning, exits 0
aspect gazelle --severity=info    # detect only, status passes
```

`auto`, the default, is `fail` on a recognized CI host and `info` off it.

### Additional Gazelle flags

Pass extra flags to the Gazelle binary. Any `-mode` flag is dropped, since the task controls the mode:

```shell theme={null}
aspect gazelle --gazelle-flag=-index=lazy
```

Flags specific to `aspect_gazelle_prebuilt`, such as `-progress` and `-cache`, fail against a from-source Gazelle binary.

To run a Gazelle subcommand, pass `--gazelle-command=update` or `--gazelle-command=fix`. With neither, Gazelle uses its own default. `update-repos` isn't supported; run it with `bazel run`.

`-index=lazy` pairs well with `--scope=changed` for the best incremental performance: Gazelle only indexes the packages it visits rather than the whole repo.

### Patch upload

When BUILD files are out of date on CI, the task uploads the diff as a `gazelle.patch` artifact so developers can apply it locally. It's on by default. To turn it off:

```python title=".aspect/config.axl" theme={null}
def config(ctx: ConfigContext):
    ctx.tasks["gazelle"].args.upload_gazelle_diff = False
```

## Options

| Flag | Default | What it does |
| - | - | - |
| positional directories | the whole workspace | Directories to update. Combined with `--scope=changed`, only changed directories under these roots are updated |
| `--check-only` | `auto` | `true` detects only, `false` applies the patch, `auto` is `true` on CI and `false` locally |
| `--severity` | `auto` | `auto`, `info`, `warn` or `fail`. See [above](#reacting-to-drift) |
| `--scope` | `all` | `all` or `changed` |
| `--scope-all-on-change <glob>` | `BUILD.bazel`, `MODULE.bazel` | Changed files that escalate `--scope=changed` to a whole-repo run. Repeatable; replaces the defaults |
| `--changed-file-pattern <glob>` | none | Only changed files matching a pattern count toward `--scope=changed`. Repeatable |
| `--base-ref <ref>` | auto-detected | The ref whose merge base the change is diffed against |
| `--merge-base <sha>` | none | An explicit merge-base commit, skipping `--base-ref` |
| `--gazelle-target <label>` | `//tools/gazelle:gazelle` | The Gazelle target to run |
| `--gazelle-command` | none | `update` or `fix` |
| `--gazelle-flag <flag>` | none | An extra flag for the Gazelle binary. Repeatable |
| `--watch` | `false` | Stay running and rerun Gazelle after each settled batch of workspace changes. See [Watch mode](#watch-mode) |
| `--upload-gazelle-diff` | `true` | Upload `gazelle.patch` on CI when BUILD files are out of date |
| `--repro-flavor`, `--fix-flavor` | `aspect`, `bazel` | Which reproduce and fix commands to show: `aspect`, `bazel` or both. Repeatable |

It also takes the Bazel flag options common to every task that runs Bazel (`--bazel-flag`, `--bazel-startup-flag`, `--announce-bazel-*`, `--bes-backend`, `--bes-header`); see [`aspect run`](https://aspect.build/docs/cli/tasks/run#options).

## CI example

```yaml title=.github/workflows/gazelle.yaml theme={null}
on:
  pull_request:
  push:
    branches: [main]

permissions:
  contents: read    # actions/checkout
  id-token: write   # artifact uploads and the PR summary comment

jobs:
  gazelle:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: aspect-build/setup-aspect@ebca96eb49ef58c00d4226de8bd3a0813507dd87 # v2026.38.3
        with:
          aspect-api-token: ${{ secrets.ASPECT_API_TOKEN }}
      - run: aspect gazelle --task:name gazelle
```

[Complete pipeline examples](https://aspect.build/docs/cli/tasks-ci.md#complete-pipeline-examples) shows the same setup on Buildkite, GitLab CI and CircleCI, and on Aspect Workflows CI runners.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.