Recently, I have noticed more rulesets adopting Bzlmod-specific features. With Bazel 6 no longer supported and Bzlmod adoption continuing across the ecosystem, rulesets can increasingly rely on newer module APIs.
One feature that caught my attention while I was setting up a hermetic Android toolchain is the ability to override a repository generated by a module extension.
override_reporequires Bazel 7.4.0 or newer and can only be used by the root module.
Overriding a repository
There are several reasons to override a repository generated by a module extension.
It can simplify migrations by allowing existing call sites to keep using the same repository name. It can also avoid introducing multiple similarly named repositories. Most importantly, it gives module authors a way to provide a smoother developer experience when integrating with other rulesets.
A good example is Keith’s hermetic Android toolchain. Setting it up requires only a small amount of configuration:
bazel_dep(
name = "hermetic_android_toolchains",
version = "0.3.0",
)
bazel_dep(
name = "rules_android",
version = "0.7.3",
)
android = use_extension(
"@hermetic_android_toolchains//:extensions.bzl",
"android",
)
android.sdk(
build_tools_version = "37.0.0",
version = "37.0",
)
use_repo(android, "androidsdk")
# Make @rules_android's @androidsdk labels resolve to the hermetic SDK.
rules_android_sdk = use_extension(
"@rules_android//rules/android_sdk_repository:rule.bzl",
"android_sdk_repository_extension",
)
override_repo(rules_android_sdk, "androidsdk")
register_toolchains("@androidsdk//:all")
The important line is:
override_repo(rules_android_sdk, "androidsdk")
The rules_android_sdk extension normally generates its own repository named androidsdk. The positional form of override_repo tells Bazel to replace it with the repository of the same name that is already visible to the root module—in this case, the androidsdk repository generated by hermetic_android_toolchains.
As a result, references to @androidsdk from the rules_android extension resolve to the hermetically downloaded SDK rather than a separately configured Android SDK repository.
The keyword form can be used when the two repositories have different names:
override_repo(
some_extension,
generated_repo_name = "replacement_repo_name",
)
Here, generated_repo_name is the repository produced by the extension, while replacement_repo_name is a repository visible to the root module.
Conclusion
That is all there is to it. override_repo is a small Bzlmod feature, but it can make integrations and migrations considerably cleaner. It is worth keeping in mind whenever two module extensions need to agree on the repository behind a well-known name.