Repositories & Module Extensions
Not everything you depend on is a Bazel module in a registry. A vendor SDK tarball, a C library without BUILD files, a directory in another part of your company's file system, a set of pip or Maven packages: all of these become external repositories, created by repository rules. This lesson shows the three ways to create them from MODULE.bazel.
| Mechanism | Use it for |
|---|---|
bazel_dep (+ *_override) |
anything published as a Bazel module (BCR or your own registry) |
use_repo_rule(...) |
one-off repositories in the root module: an archive, a local directory |
| a module extension | repositories computed from tags across the module graph: SDKs, package-manager lockfiles, toolchains |
Repository rules: an archive and a local directory
http_archive downloads, verifies and unpacks an archive; it accepts file:// URLs, which lets this offline session demonstrate it for real with a "vendor" tarball. build_file adds a BUILD file to code that has none:
mkdir -p vendor-src/tinyfmt-1.2.0 && cd vendor-src
cat > tinyfmt-1.2.0/tinyfmt.h <<'EOF'
#pragma once
#include <string>
inline std::string bold(const std::string& s) { return "**" + s + "**"; }
EOF
tar --sort=name --mtime=@$SOURCE_DATE_EPOCH --owner=0 --group=0 -czf ../tinyfmt-1.2.0.tar.gz tinyfmt-1.2.0
cd .. && sha=$(sha256sum tinyfmt-1.2.0.tar.gz | cut -d' ' -f1)
mkdir -p shared-config && echo 'APP_NAME = "shop"' > shared-config/config.bzl && touch shared-config/BUILD.bazel shared-config/REPO.bazel
mkdir ws && cd ws
cat > MODULE.bazel <<EOF
bazel_dep(name = "rules_cc", version = "0.2.27")
http_archive = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "tinyfmt",
urls = ["file:///home/learner/tinyfmt-1.2.0.tar.gz"],
sha256 = "$sha",
strip_prefix = "tinyfmt-1.2.0",
build_file = "//third_party:tinyfmt.BUILD",
)
local_repository = use_repo_rule("@bazel_tools//tools/build_defs/repo:local.bzl", "local_repository")
local_repository(name = "shared_config", path = "/home/learner/shared-config")
EOF
mkdir -p third_party app
touch third_party/BUILD.bazel
cat > third_party/tinyfmt.BUILD <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_library")
cc_library(name = "tinyfmt", hdrs = ["tinyfmt.h"], visibility = ["//visibility:public"])
EOF
cat > app/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_binary")
load("@shared_config//:config.bzl", "APP_NAME")
cc_binary(name = "app", srcs = ["main.cc"], deps = ["@tinyfmt"], local_defines = ['APP=\\"%s\\"' % APP_NAME])
EOF
printf '#include <cstdio>\n#include "tinyfmt.h"\nint main() { std::puts(bold(APP).c_str()); }\n' > app/main.cc
bazel run //app 2>/dev/null
echo "== the expected checksum doesn't match the archive"
sed -i "s/$sha/$(echo $sha | rev)/" MODULE.bazel
bazel build //app 2>&1 | grep -o 'Checksum was .*' | head -1 | cut -c1-60**shop**
== the expected checksum doesn't match the archive
Checksum was 1d35cad161ef18623063da64f52fde4ac13249deb97b8ef
Points to notice:
@tinyfmtis short for@tinyfmt//:tinyfmt. The header is included as"tinyfmt.h"because it sits at the root of its repository.- The
sha256(orintegrity) attribute is mandatory in practice: it makes the download reproducible and lets Bazel take the archive from the repository cache (--repository_cache, shared by all workspaces) without any network access, which is how this course image works offline. When the archive and the expected checksum disagree, the build stops. - The flip side: the repository cache is keyed by checksum. If you change the URL to a new release but forget to change
sha256, Bazel may happily reuse the old archive from the cache. Always update both together. local_repositoryturns a directory into a repository; the directory must mark its root with aREPO.bazel(orMODULE.bazel) file, otherwise the fetch fails with "No MODULE.bazel, REPO.bazel, or WORKSPACE file found";new_local_repositorydoes the same for a directory without BUILD files (withbuild_file). Here a.bzlfile from it provides a constant, but it could be whole libraries.
Tip: For your own modules in a monorepo or a sibling checkout, prefer
bazel_deppluslocal_path_override(module_name = "x", path = "../x"): the dependency stays a normal module and the override can be dropped when it's published.
A module extension
A module extension is Starlark code that runs after module resolution, reads tags that any module in the graph wrote (go_sdk.download(version = …), pip.parse(...), maven.install(...) are all tags) and creates repositories. Here is a tiny one: modules declare feature flags with a tag, and the extension generates one repository with all of them:
mkdir ws && cd ws
mkdir -p build_defs app
touch build_defs/BUILD.bazel
cat > build_defs/features.bzl <<'EOF'
def _features_repo_impl(rctx):
lines = ["FEATURES = {"] + [' "%s": %s,' % (k, v) for k, v in sorted(rctx.attr.flags.items())] + ["}"]
rctx.file("BUILD.bazel", "")
rctx.file("features.bzl", "\n".join(lines) + "\n")
features_repo = repository_rule(
implementation = _features_repo_impl,
attrs = {"flags": attr.string_dict()},
)
def _features_ext_impl(mctx):
flags = {}
for mod in mctx.modules:
for tag in mod.tags.enable:
flags[tag.name] = "True"
for tag in mod.tags.disable:
flags[tag.name] = "False"
features_repo(name = "features", flags = flags)
_enable = tag_class(attrs = {"name": attr.string(mandatory = True)})
_disable = tag_class(attrs = {"name": attr.string(mandatory = True)})
features = module_extension(
implementation = _features_ext_impl,
tag_classes = {"enable": _enable, "disable": _disable},
)
EOF
cat > MODULE.bazel <<'EOF'
module(name = "shop")
features = use_extension("//build_defs:features.bzl", "features")
features.enable(name = "new_checkout")
features.disable(name = "legacy_cart")
use_repo(features, "features")
EOF
cat > app/BUILD.bazel <<'EOF'
load("@features//:features.bzl", "FEATURES")
genrule(name = "flags", outs = ["flags.txt"], cmd = "echo '%s' > $@" % FEATURES)
EOF
bazel build //app:flags 2>/dev/null && cat bazel-bin/app/flags.txt
cat $(bazel info output_base 2>/dev/null)/external/+features+features/features.bzl
jq -r '.moduleExtensions | keys[]' MODULE.bazel.lock{"legacy_cart": False, "new_checkout": True}
FEATURES = {
"legacy_cart": False,
"new_checkout": True,
}
//build_defs:features.bzl%features
@@rules_python+//python/extensions:config.bzl%config
The extension ran once, after the module graph was known, and created the repository @features (canonical name +features+features: the extension's module, its name, the repository). use_repo imported it into the root module under its apparent name. The lockfile now records the extension's result, so it won't rerun until its inputs change.
That's exactly how the real language extensions work: rules_go's go_sdk collects download tags from every module and picks one SDK; rules_python's pip reads lock files and creates @pypi; rules_jvm_external's maven merges all modules' Maven coordinates into one resolution. Two rules of thumb:
- An extension must be deterministic given its tags and the files it reads (it may download, with checksums); Bazel caches its result in the lockfile.
- Only the root module's
use_repodecides what's visible to your BUILD files;bazel mod tidykeeps that list in sync.
Test yourself
Why should an http_archive always have a sha256 or integrity value?
- Style
- It makes the download verifiable and reproducible, and lets Bazel serve it from the repository cache offline
- It speeds up extraction
- It's needed for visibility
How do you depend on your own module that lives in a sibling directory during development?
- Copy it into the repo
- bazel_dep plus local_path_override
- A genrule
- --override_module only on CI
What does a module extension do?
- Adds commands to bazel
- Reads tags from modules in the graph and creates repositories (SDKs, packages, toolchains)
- Builds targets faster
- Formats BUILD files