TExcelTAD
Home › Monorepo Builds: Bazel (+ Buck2 & Pants) › Migrating Gradle/Maven & Go (Gazelle)

Migrating Gradle/Maven & Go (Gazelle)

JVM and Go repositories are the other big sources of Bazel migrations. Both have a well-defined module structure, so the conversion is mostly mechanical, and for Go a tool, Gazelle, does most of it. Java Builds: Maven & Gradle and Go Modules in Depth cover the source systems.

Gradle and Maven → Bazel

Gradle / Maven Bazel
a module / subproject (:core, <module>core</module>) one or more java_library targets (a common start: one per module, later one per Java package)
implementation(project(":core")) deps = ["//core"]
api(...) (java-library plugin) exports = [...] on the java_library
implementation("com.google.guava:guava:33.5.0-jre") rules_jvm_external maven.install + deps = ["@maven//:com_google_guava_guava"]
version catalog / BOM the artifacts list (with boms = [...]) in maven.install, plus maven_install.json as lockfile
testImplementation + JUnit java_test with JUnit from @maven
application { mainClass = … } java_binary(main_class = …) (+ _deploy.jar)
src/main/resources resources = glob(["src/main/resources/**"])
annotation processors (Lombok, AutoValue, Dagger) java_plugin targets in plugins = [...]
Gradle plugins with custom tasks macros, genrules or custom rules (the expensive part of a migration)

Strict deps is the first surprise: Gradle's implementation puts transitive dependencies on the compile classpath, Bazel doesn't. Code that uses Guava because a dependency happened to bring it in must list Guava itself. Bazel's error message prints the buildozer command that adds the missing dependency, and teams usually script that loop.

A two-module Gradle build, converted

The original (not run here):

kotlin
// settings.gradle.kts
include("core", "app")

// core/build.gradle.kts
plugins { `java-library` }

// app/build.gradle.kts
plugins { application }
dependencies { implementation(project(":core")) }
application { mainClass = "com.example.app.Main" }

Bazel keeps the Maven directory layout (src/main/java, which rules_java recognises as a Java root) so the move can happen without moving files:

bash · try it yourself
mkdir -p shop/core/src/main/java/com/example/core shop/core/src/test/java/com/example/core shop/app/src/main/java/com/example/app && cd shop
echo 'bazel_dep(name = "rules_java", version = "9.9.0")' > MODULE.bazel
cat > core/BUILD.bazel <<'EOF'
load("@rules_java//java:defs.bzl", "java_library", "java_test")

java_library(
    name = "core",
    srcs = glob(["src/main/java/**/*.java"]),
    visibility = ["//app:__pkg__"],                  # Gradle has no equivalent
)

java_test(
    name = "PriceTest",
    size = "small",
    srcs = ["src/test/java/com/example/core/PriceTest.java"],
    use_testrunner = False,                          # JUnit isn't in the course image
    main_class = "com.example.core.PriceTest",
    deps = [":core"],
)
EOF
cat > core/src/main/java/com/example/core/Price.java <<'EOF'
package com.example.core;

public record Price(long cents) {
  public Price plusTax(int percent) { return new Price(cents + cents * percent / 100); }
  @Override public String toString() { return String.format("%d.%02d EUR", cents / 100, cents % 100); }
}
EOF
cat > core/src/test/java/com/example/core/PriceTest.java <<'EOF'
package com.example.core;

public class PriceTest {
  public static void main(String[] args) {
    if (new Price(1000).plusTax(20).cents() != 1200) throw new AssertionError("tax");
    System.out.println("PriceTest ok");
  }
}
EOF
cat > app/BUILD.bazel <<'EOF'
load("@rules_java//java:defs.bzl", "java_binary")
java_binary(
    name = "app",
    srcs = glob(["src/main/java/**/*.java"]),
    main_class = "com.example.app.Main",
    deps = ["//core"],
)
EOF
cat > app/src/main/java/com/example/app/Main.java <<'EOF'
package com.example.app;

import com.example.core.Price;

public class Main {
  public static void main(String[] args) {
    System.out.println("Total: " + new Price(1999).plusTax(20));
  }
}
EOF
bazel run //app 2>/dev/null
bazel test //... 2>&1 | grep -E 'PASSED|FAILED'
echo "== change a method body in core: what recompiles?"
sed -i 's/cents \* percent \/ 100/(cents * percent) \/ 100/' core/src/main/java/com/example/core/Price.java
bazel build //app --explain=why.log 2>&1 | grep -E 'process'
grep -o "Executing action '[^']*'" why.log | sort
Total: 23.98 EUR
//core:PriceTest                                                         PASSED in 0.1s
== change a method body in core: what recompiles?
INFO: 3 processes: 2 action cache hit, 1 internal, 1 processwrapper-sandbox, 1 worker.
Executing action 'BazelWorkspaceStatusAction stable-status.txt'
Executing action 'Building core/libcore.jar (1 source file)'
Executing action 'Compiling Java headers core/libcore-hjar.jar (1 source file)'

The last build shows Java's interface-jar advantage: after a change inside a method body, Bazel recompiled core's jar (in the javac worker) and regenerated its header jar, which came out identical. app compiles against that header jar, so none of its actions ran (the --explain log lists only core's two actions and the workspace status, which always runs). Gradle reaches a similar result through its ABI tracking; in Bazel it falls out of content hashing.

Go: Gazelle (not run here)

Go code already declares its dependencies in import statements and go.mod, so writing BUILD files by hand would be pure duplication. Gazelle generates and updates them:

python
# MODULE.bazel
bazel_dep(name = "rules_go", version = "0.65.0")
bazel_dep(name = "gazelle", version = "0.51.3")

go_deps = use_extension("@gazelle//:extensions.bzl", "go_deps")
go_deps.from_file(go_mod = "//:go.mod")
use_repo(go_deps, "com_github_google_uuid", "org_golang_x_sync")
python
# BUILD.bazel at the root
load("@gazelle//:def.bzl", "gazelle")

# gazelle:prefix example.com/shop
# gazelle:exclude vendor
gazelle(name = "gazelle")
bash
bazel run //:gazelle            # create/update BUILD.bazel files for every Go package
bazel mod tidy                  # fix use_repo after go.mod changes

For a package example.com/shop/pricing with a test, Gazelle writes exactly the go_library/go_test pair you wrote by hand in the Go rules lesson, including importpath and deps derived from the imports. It keeps your manual edits (it only rewrites attributes it owns) and is controlled with # gazelle: directives (resolve, exclude, proto, naming conventions). Gazelle can't run in the course image because neither its archive nor the Go modules it depends on are in the offline cache.

Gazelle has extensions for other languages: rules_python's Gazelle plugin generates py_library/py_binary targets from imports, and community plugins exist for Java, Kotlin, JavaScript/TypeScript (in Aspect's aspect configure) and protobuf. For a large Java codebase they turn the "one target per package" granularity from a chore into a command.

Migration checklist

Step Why
Pin everything first: maven_install.json, go.sum, a Python lock file a migration is no time for version drift
Mirror the module structure, then refine a working coarse build beats a perfect plan
Run both builds in CI until outputs match trust is the real deliverable
Generate BUILD files where a tool exists (Gazelle) and check them in CI (bazel run //:gazelle -- -mode=diff) stale BUILD files are the main long-term cost
Teach the team bazel query and the error messages developers stop fighting the build once they can read it

Test yourself

Gradle compiles fine, but Bazel reports a strict deps error for com.google.common.collect.ImmutableList. Why?

  1. Guava is missing from Maven Central
  2. The code uses Guava but only gets it transitively; Bazel requires it as a direct dep
  3. Java version mismatch
  4. Visibility

What does Gazelle do?

  1. Runs Go tests
  2. Generates and updates BUILD files from source imports and go.mod
  3. Replaces rules_go
  4. Uploads to a remote cache

After a change inside a method body in core, why isn't app recompiled?

  1. Bazel skips Java
  2. app compiles against core's header (interface) jar, which didn't change
  3. app has no sources
  4. The test cached it