Packages & Visibility
In a monorepo, anyone can import anything is how a codebase turns into a ball of mud: a team's internal helper becomes a dependency of fifty other teams, and it can never change again. Bazel's answer is visibility: every target says which packages may depend on it, and the build fails at analysis time if anyone else does.
The rules
A target's visibility attribute is a list of these:
| Value | Who may depend on the target |
|---|---|
//visibility:private |
only targets in the same package (the default) |
//visibility:public |
everyone, including other modules |
//foo:__pkg__ |
targets in package //foo |
//foo:__subpackages__ |
targets in //foo and every package below it |
//foo:my_group |
the packages listed in a package_group(name = "my_group", packages = [...]) |
The default for a package can be changed with package(default_visibility = [...]) at the top of the BUILD file; a target's own visibility overrides it.
Visibility controls who may depend on a target, not who may build it: you can always bazel build //any:target.
A violation, on purpose
Here //payments/internal:ledger is meant for the payments team only. The //payments/api package may use it; //marketing may not:
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_cc", version = "0.2.27")' > MODULE.bazel
mkdir -p payments/internal payments/api marketing
cat > payments/internal/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_library")
cc_library(
name = "ledger",
srcs = ["ledger.cc"],
hdrs = ["ledger.h"],
visibility = ["//payments:__subpackages__"],
)
EOF
printf '#pragma once\nint balance();\n' > payments/internal/ledger.h
printf '#include "payments/internal/ledger.h"\nint balance() { return 42; }\n' > payments/internal/ledger.cc
cat > payments/api/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(name = "api", srcs = ["api.cc"], deps = ["//payments/internal:ledger"])
EOF
printf '#include <cstdio>\n#include "payments/internal/ledger.h"\nint main() { std::printf("balance %%d\\n", balance()); }\n' > payments/api/api.cc
cat > marketing/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(name = "promo", srcs = ["promo.cc"], deps = ["//payments/internal:ledger"])
EOF
cp payments/api/api.cc marketing/promo.cc
bazel run //payments/api 2>/dev/null
bazel build //marketing:promo 2>&1 | grep -v '^INFO'balance 42
ERROR: /home/learner/ws/marketing/BUILD.bazel:2:10: in cc_binary rule //marketing:promo: Visibility error:
target '//payments/internal:ledger' is not visible from
target '//marketing:promo'
Recommendation: modify the visibility declaration if you think the dependency is legitimate. For more info see https://bazel.build/concepts/visibility
ERROR: /home/learner/ws/marketing/BUILD.bazel:2:10: Analysis of target '//marketing:promo' (config: 0a96350) failed
ERROR: Analysis of target '//marketing:promo' failed; build aborted
ERROR: Build did NOT complete successfully
The error comes from the analysis phase: nothing was compiled for promo. The fix is a conversation with the payments team, not a code change: either they publish a public API target (//payments/api:client, visibility = ["//visibility:public"]) or they add //marketing:__pkg__ to the list on purpose.
package_group and default_visibility
When the same audience appears on many targets, name it once:
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_cc", version = "0.2.27")' > MODULE.bazel
mkdir -p core teams/search teams/ads tools
cat > core/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_library")
package_group(
name = "product_teams",
packages = ["//teams/..."],
)
package(default_visibility = [":product_teams"])
cc_library(name = "strings", hdrs = ["strings.h"])
cc_library(name = "metrics", hdrs = ["metrics.h"])
cc_library(name = "secret", hdrs = ["secret.h"], visibility = ["//visibility:private"])
EOF
touch core/strings.h core/metrics.h core/secret.h
for t in search ads; do
printf 'load("@rules_cc//cc:defs.bzl", "cc_library")\ncc_library(name = "%s", deps = ["//core:strings", "//core:metrics"])\n' $t > teams/$t/BUILD.bazel
done
printf 'load("@rules_cc//cc:defs.bzl", "cc_library")\ncc_library(name = "lint", deps = ["//core:strings"])\n' > tools/BUILD.bazel
bazel build //teams/... 2>&1 | tail -1
bazel build //tools:lint 2>&1 | grep -A1 'Visibility error' | sed 's#/home/learner/ws/##'
bazel query 'visible(//teams/search:search, kind(cc_library, //core:*))' 2>/dev/nullINFO: Build completed successfully, 1 total action
ERROR: tools/BUILD.bazel:2:11: in cc_library rule //tools:lint: Visibility error:
target '//core:strings' is not visible from
//core:metrics
//core:strings
package(default_visibility = ...) gave both libraries the same audience, secret opted out, and //tools is outside the group. bazel query 'visible(T, set)' lists which targets in a set a target is allowed to depend on, which is handy when designing an API package.
Note:
package_groupcan also takeincludes = [":other_group"], and itspackageslist uses//foo(exactly that package),//foo/...(the package and below) andpublic/private. Its syntax differs fromvisibility's__pkg__/__subpackages__, a frequent source of confusion.
Files, tests and .bzl files
| Thing | Visibility rule |
|---|---|
| Source files | another package can only name a file that its own package uses in a rule or lists in exports_files(["schema.json"], visibility = [...]); export files you mean to share explicitly, with a visibility |
| Generated files | have the visibility of the rule that generates them |
.bzl files |
loadable from anywhere by default; a .bzl can restrict who may load() it with a top-level visibility(["//build/defs/..."]) call (load visibility) |
testonly = True targets |
can only be depended on by other testonly targets (tests, test helpers), so test fakes never leak into production binaries |
Designing boundaries
Visibility turns your repository layout into an architecture you can enforce:
| Pattern | Visibility |
|---|---|
| Public API of a component | //visibility:public on one or two api targets |
| Implementation details | //component:__subpackages__ |
| Shared test utilities | testonly = True plus a package_group of the test packages |
| Deprecated code with a deadline | a shrinking allow-list of current users, plus deprecation = "use //new:thing" (prints a warning to every dependent) |
Large repositories add automated checks on top (an owners file per package, a code review rule when someone edits a visibility list), but the build-time error is the part that can't be bypassed.
Test yourself
What is the default visibility of a target with no visibility attribute and no package(default_visibility)?
- Public
- Private: only the same package
- The whole module
- Subpackages
In which phase does Bazel report a visibility violation?
- Loading
- Analysis
- Execution (compile)
- Only at link time
How do you let test helpers be used by tests but never by production binaries?
- visibility = ["//visibility:private"]
- Mark them
testonly = True - Put them in a tests/ directory
- Use a .bzl file