Bazel Exercises
The first four exercises are small pieces of Bazel's logic, written as pure functions with the calls already in place. Run the starter first: it prints placeholder answers. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last exercise is a real Bazel workspace to fix.
Exercise 1: Parse labels
Topics: BUILD Files, Targets & Labels
Turn a label into (repo, package, name), resolving relative labels against the package of the BUILD file they appear in. //app means //app:app; :x and x are in the current package; @repo//pkg:t keeps its repository ("" is the main repository).
def parse_label(label, current_package):
# TODO: handle @repo//pkg:name, //pkg:name, //pkg, :name and name
return ("?", "?", "?")
tests = [
("//app:server", "lib"),
("//app", "lib"),
(":util", "lib/strings"),
("util", "lib/strings"),
("@rules_cc//cc:defs.bzl", "app"),
("@tinyfmt", "app"),
]
for label, pkg in tests:
print(f"{label:24} in {pkg:12} -> {parse_label(label, pkg)}")//app:server in lib -> ('?', '?', '?')
//app in lib -> ('?', '?', '?')
:util in lib/strings -> ('?', '?', '?')
util in lib/strings -> ('?', '?', '?')
@rules_cc//cc:defs.bzl in app -> ('?', '?', '?')
@tinyfmt in app -> ('?', '?', '?')
Expected output:
//app:server in lib -> ('', 'app', 'server')
//app in lib -> ('', 'app', 'app')
:util in lib/strings -> ('', 'lib/strings', 'util')
util in lib/strings -> ('', 'lib/strings', 'util')
@rules_cc//cc:defs.bzl in app -> ('rules_cc', 'cc', 'defs.bzl')
@tinyfmt in app -> ('tinyfmt', '', 'tinyfmt')Show solution
def parse_label(label, current_package):
repo = ""
if label.startswith("@"):
repo, _, rest = label[1:].partition("//")
if not _: # "@tinyfmt" = "@tinyfmt//:tinyfmt"
return (repo, "", repo)
label = "//" + rest
if label.startswith("//"):
pkg, colon, name = label[2:].partition(":")
return (repo, pkg, name if colon else pkg.rsplit("/", 1)[-1])
return (repo, current_package, label.lstrip(":"))Exercise 2: Expand target patterns
Topics: BUILD Files, Targets & Labels, bazel test
Given the rule targets of a workspace and their tags, expand a list of patterns the way bazel build does: //pkg/... (recursive), //pkg:all, exact labels, -pattern to subtract (applied in order), and targets tagged manual are skipped by wildcards but kept when named exactly.
TARGETS = {
"//app:server": [], "//app:server_test": [], "//app/admin:panel": [],
"//lib/strings:strings": [], "//lib/strings:strings_test": [],
"//e2e:checkout_test": ["manual"], "//legacy:old": [],
}
def expand(patterns):
# TODO: return the sorted list of selected targets
return []
print(expand(["//..."]))
print(expand(["//app/..."]))
print(expand(["//lib/strings:all", "//e2e:checkout_test"]))
print(expand(["//...", "-//legacy/...", "-//app/admin/..."]))[]
[]
[]
[]
Expected output:
['//app/admin:panel', '//app:server', '//app:server_test', '//legacy:old', '//lib/strings:strings', '//lib/strings:strings_test']
['//app/admin:panel', '//app:server', '//app:server_test']
['//e2e:checkout_test', '//lib/strings:strings', '//lib/strings:strings_test']
['//app:server', '//app:server_test', '//lib/strings:strings', '//lib/strings:strings_test']Show solution
def matches(pattern, label):
pkg = label[2:].split(":")[0]
if pattern.endswith("/..."):
root = pattern[2:-4]
return root == "" or pkg == root or pkg.startswith(root + "/")
if pattern.endswith(":all"):
return pkg == pattern[2:-4]
return False
def expand(patterns):
selected = set()
for p in patterns:
negative = p.startswith("-")
p = p.lstrip("-")
if p in TARGETS: # an exact label: manual is fine
hits = {p}
else:
hits = {t for t, tags in TARGETS.items() if matches(p, t) and "manual" not in tags}
selected = selected - hits if negative else selected | hits
return sorted(selected)Exercise 3: Toolchain resolution
Topics: Toolchain Resolution, Platforms
Pick the first registered toolchain whose target_compatible_with constraints are all present on the target platform and whose exec_compatible_with constraints are all present on some execution platform (try execution platforms in order). Return (toolchain, exec_platform) or None.
PLATFORMS = {
"host": {"os:linux", "cpu:x86_64"},
"linux_arm64": {"os:linux", "cpu:aarch64"},
"mac_arm64": {"os:macos", "cpu:aarch64"},
}
EXEC_PLATFORMS = ["host"]
TOOLCHAINS = [ # (name, exec_compatible_with, target_compatible_with), in registration order
("gcc_x86", {"os:linux", "cpu:x86_64"}, {"os:linux", "cpu:x86_64"}),
("gcc_cross_arm", {"os:linux", "cpu:x86_64"}, {"os:linux", "cpu:aarch64"}),
("clang_mac", {"os:macos"}, {"os:macos"}),
]
def resolve(target_platform, exec_platforms=EXEC_PLATFORMS):
# TODO
return None
for target in ["host", "linux_arm64", "mac_arm64"]:
print(target, "->", resolve(target))
print("mac_arm64 with a mac worker ->", resolve("mac_arm64", ["host", "mac_arm64"]))host -> None
linux_arm64 -> None
mac_arm64 -> None
mac_arm64 with a mac worker -> None
Expected output:
host -> ('gcc_x86', 'host')
linux_arm64 -> ('gcc_cross_arm', 'host')
mac_arm64 -> None
mac_arm64 with a mac worker -> ('clang_mac', 'mac_arm64')Show solution
def resolve(target_platform, exec_platforms=EXEC_PLATFORMS):
target = PLATFORMS[target_platform]
for name, exec_needs, target_needs in TOOLCHAINS:
if not target_needs <= target:
continue
for ep in exec_platforms:
if exec_needs <= PLATFORMS[ep]:
return (name, ep)
return NoneExercise 4: Bzlmod's version selection
Topics: MODULE.bazel.lock & bazel mod
Implement minimal version selection over a registry of MODULE.bazel requirements: starting from the root's bazel_deps, visit every requirement of every reached module version and keep the highest version per module. Then report which versions were read from the registry but not selected.
REGISTRY = {
("rules_cc", "0.2.27"): [("bazel_skylib", "1.8.0"), ("platforms", "0.0.10")],
("rules_go", "0.65.0"): [("bazel_skylib", "1.8.1"), ("platforms", "1.1.0"), ("rules_cc", "0.1.5")],
("rules_cc", "0.1.5"): [("platforms", "0.0.10")],
("bazel_skylib", "1.8.0"): [("platforms", "0.0.10")],
("bazel_skylib", "1.8.1"): [("platforms", "0.0.10")],
("platforms", "0.0.10"): [],
("platforms", "1.1.0"): [],
}
ROOT = [("rules_cc", "0.2.27"), ("rules_go", "0.65.0")]
def vkey(v):
return tuple(int(x) for x in v.split("."))
def select(root):
# TODO: return ({module: selected_version}, sorted list of (module, version) read but not selected)
return ({}, [])
selected, unused = select(ROOT)
for m in sorted(selected):
print(f"{m:13} {selected[m]}")
print("read but not selected:", unused)read but not selected: []
Expected output:
bazel_skylib 1.8.1
platforms 1.1.0
rules_cc 0.2.27
rules_go 0.65.0
read but not selected: [('bazel_skylib', '1.8.0'), ('platforms', '0.0.10'), ('rules_cc', '0.1.5')]Show solution
def select(root):
selected, seen, todo = {}, set(), list(root)
while todo:
mod, ver = todo.pop()
if (mod, ver) in seen:
continue
seen.add((mod, ver))
if mod not in selected or vkey(ver) > vkey(selected[mod]):
selected[mod] = ver
todo.extend(REGISTRY[(mod, ver)])
unused = sorted((m, v) for m, v in seen if selected[m] != v)
return selected, unusedExercise 5: Fix the broken workspace
Topics: Bzlmod, visibility, C++ headers, genrule
This workspace has four bugs. Run it, read each error, and fix them one at a time (the session stops reporting new errors until the earlier ones are fixed):
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_cc", version = "0.2.27")' > MODULE.bazel
mkdir -p lib app gen
cat > lib/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_library")
cc_library(name = "money", srcs = ["money.cc"], hdrs = ["money.h"])
EOF
printf '#pragma once\n#include "lib/rounding.h"\nlong cents(double eur);\n' > lib/money.h
printf '#pragma once\ninline long round_half_up(double x) { return (long)(x + 0.5); }\n' > lib/rounding.h
printf '#include "lib/money.h"\nlong cents(double eur) { return round_half_up(eur * 100); }\n' > lib/money.cc
cat > gen/BUILD.bazel <<'EOF'
genrule(name = "rate", outs = ["rate.h"], cmd = "echo \"#define VAT $(cat gen/vat.txt)\" > $@", visibility = ["//visibility:public"])
EOF
echo 20 > gen/vat.txt
cat > app/BUILD.bazel <<'EOF'
cc_binary(name = "app", srcs = ["main.cc", "//gen:rate"], deps = ["//lib:money"])
EOF
printf '#include <cstdio>\n#include "lib/money.h"\n#include "gen/rate.h"\nint main() { std::printf("%%ld cents, VAT %%d%%%%\\n", cents(19.99), VAT); }\n' > app/main.cc
bazel build //app 2>&1 | grep -E -A1 '^(ERROR|Error in)' | grep -v -E '^(--|INFO)' | cut -c1-140 | head -4ERROR: Traceback (most recent call last):
File "/home/learner/ws/app/BUILD.bazel", line 1, column 10, in <toplevel>
Error in fail:
This rule has been removed from Bazel. Please add a `load()` statement for it.
Expected output once everything is fixed: bazel run //app prints 1999 cents, VAT 20%.
Show solution
- Missing load. Bazel 9 has no built-in
cc_binary: addload("@rules_cc//cc:defs.bzl", "cc_binary")toapp/BUILD.bazel. - Visibility.
//lib:moneyis private to//lib: addvisibility = ["//app:__pkg__"](or apackage_group). - Undeclared header.
money.hincludeslib/rounding.h, which no rule declares, so it isn't in the sandbox: add it tohdrs(it's part of the public interface because a public header includes it). - Undeclared genrule input. The genrule reads
gen/vat.txtwithout declaring it:srcs = ["vat.txt"]andcmd = "echo \"#define VAT $(cat lt;)\" > $@". (The error shows up ascat: gen/vat.txt: No such file or directoryfollowed by an#define VATwith no value.)
# the fixed files
cat > app/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(name = "app", srcs = ["main.cc", "//gen:rate"], deps = ["//lib:money"])
EOF
cat > lib/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_library")
cc_library(name = "money", srcs = ["money.cc"], hdrs = ["money.h", "rounding.h"], visibility = ["//app:__pkg__"])
EOF
cat > gen/BUILD.bazel <<'EOF'
genrule(name = "rate", srcs = ["vat.txt"], outs = ["rate.h"], cmd = "echo \"#define VAT $(cat lt;)\" > $@", visibility = ["//visibility:public"])
EOF
bazel run //app # 1999 cents, VAT 20%Test yourself
Inside package lib/strings, what does the label util mean?
- //util:util
- //lib/strings:util
- @util//:util
- A file called util anywhere
Why does //... skip a target tagged manual but //e2e:checkout_test builds it?
- Manual targets are broken
- manual only removes a target from wildcard expansion
- Exact labels ignore tags entirely, including size
- It's random