Writing a Rule
A rule is a new kind of target. You write it in a .bzl file with two parts: the rule declaration (rule(...): its attributes and implementation function) and the implementation function, which runs during analysis, receives a ctx object and declares actions. It doesn't run anything itself; Bazel decides later whether the actions need to run.
def _impl(ctx):
out = ctx.actions.declare_file(ctx.label.name + ".txt") # 1. declare outputs
ctx.actions.run_shell( # 2. declare actions that produce them
inputs = ctx.files.srcs,
outputs = [out],
command = "cat {} > {}".format(" ".join([f.path for f in ctx.files.srcs]), out.path),
)
return [DefaultInfo(files = depset([out]))] # 3. return providers
concat = rule(
implementation = _impl,
attrs = {"srcs": attr.label_list(allow_files = True)},
)The ctx object
| Member | Gives you |
|---|---|
ctx.label |
the target's label (ctx.label.name, ctx.label.package) |
ctx.attr.<name> |
attribute values; for label attributes, the dependency targets (with their providers) |
ctx.file.<name>, ctx.files.<name> |
the files of a single-file / list label attribute |
ctx.executable.<name> |
an executable tool from an attribute with executable = True, cfg = "exec" |
ctx.actions.declare_file(name) |
a new output file in this package's output directory |
ctx.actions.write(output, content) |
an action that writes a string (no process started) |
ctx.actions.expand_template(template, output, substitutions) |
template substitution, also without a process |
ctx.actions.run(executable, arguments, inputs, outputs) |
run a program, no shell: the preferred way |
ctx.actions.run_shell(command, inputs, outputs) |
run a shell command: convenient for small steps |
ctx.actions.args() |
an Args object that builds command lines lazily (efficient for huge file lists) |
A real rule: a release manifest
The rule below takes source files and a version, writes a manifest with an action that runs sha256sum, and returns it as its default output. A second target uses the manifest through a genrule:
mkdir ws && cd ws
echo 'module(name = "rules_demo")' > MODULE.bazel
mkdir -p build_defs release
touch build_defs/BUILD.bazel
cat > build_defs/manifest.bzl <<'EOF'
def _manifest_impl(ctx):
header = ctx.actions.declare_file(ctx.label.name + ".header")
ctx.actions.write(
output = header,
content = "name={}\nversion={}\n".format(ctx.attr.product, ctx.attr.version),
)
out = ctx.actions.declare_file(ctx.label.name + ".manifest")
srcs = sorted(ctx.files.srcs, key = lambda f: f.path)
ctx.actions.run_shell(
inputs = [header] + srcs,
outputs = [out],
command = "cat {header} > {out} && sha256sum {files} | cut -c1-12,65- >> {out}".format(
header = header.path,
out = out.path,
files = " ".join([f.path for f in srcs]),
),
mnemonic = "Manifest",
progress_message = "Writing manifest for %{label}",
)
return [DefaultInfo(files = depset([out]))]
release_manifest = rule(
implementation = _manifest_impl,
doc = "Writes a manifest with the product name, version and a short hash of every source.",
attrs = {
"srcs": attr.label_list(allow_files = True, mandatory = True),
"product": attr.string(mandatory = True),
"version": attr.string(default = "0.0.0"),
},
)
EOF
cat > release/BUILD.bazel <<'EOF'
load("//build_defs:manifest.bzl", "release_manifest")
release_manifest(
name = "shop",
srcs = ["README.txt", "config.yaml"],
product = "shop",
version = "2.1.0",
)
genrule(
name = "shop_lines",
srcs = [":shop"],
outs = ["shop_lines.txt"],
cmd = "wc -l < lt; > $@",
)
EOF
echo "Shop service" > release/README.txt
echo "port: 8080" > release/config.yaml
bazel build //release:shop //release:shop_lines 2>&1 | grep -E 'up-to-date|bazel-bin|processes'
cat bazel-bin/release/shop.manifest
cat bazel-bin/release/shop_lines.txt
echo "== aquery shows the new mnemonic"
bazel aquery 'mnemonic("Manifest", //release:shop)' 2>/dev/null | grep -E "^action|Mnemonic|Outputs"
echo "== query knows the new kind"
bazel query --output=label_kind //release:all 2>/dev/nullINFO: 4 processes: 2 internal, 2 processwrapper-sandbox.
name=shop
version=2.1.0
f59931de5246 release/README.txt
04eeaa6d3c2a release/config.yaml
4
== aquery shows the new mnemonic
action 'Writing manifest for //release:shop'
Mnemonic: Manifest
Outputs: [bazel-out/k8-fastbuild/bin/release/shop.manifest]
== query knows the new kind
release_manifest rule //release:shop
genrule rule //release:shop_lines
Walk through it:
ctx.actions.writeproduced the header without starting a process (it's an "internal" action in the summary).run_shelldeclared one action with exactly the header and the sorted sources as inputs. Sorting matters: the command line is part of the cache key, so it must not depend on the order Bazel happens to hand you files.DefaultInfo(files = …)defines whatbazel build //release:shopbuilds and whatlt;means when another rule (the genrule) depends on it.- The action has its own mnemonic and progress message, so it's easy to find in
aquery, profiles and execution logs. The rule is a first-class kind:queryreportsrelease_manifest rule.
Executable and test rules
A rule declared with executable = True must return DefaultInfo(executable = …), and then bazel run works on it; test = True makes it a test rule (its name must end in _test) that bazel test runs:
mkdir ws && cd ws
echo 'module(name = "rules_demo")' > MODULE.bazel
mkdir -p build_defs checks
touch build_defs/BUILD.bazel
cat > build_defs/file_check.bzl <<'EOF'
def _file_check_test_impl(ctx):
script = ctx.actions.declare_file(ctx.label.name + ".sh")
lines = ["#!/bin/bash", "fail=0"]
for f in ctx.files.files:
lines.append('grep -q "{}" "{}" || {{ echo "missing in {}"; fail=1; }}'.format(ctx.attr.must_contain, f.short_path, f.short_path))
lines.append('echo "checked {} file(s)"; exit $fail'.format(len(ctx.files.files)))
ctx.actions.write(script, "\n".join(lines) + "\n", is_executable = True)
return [DefaultInfo(executable = script, runfiles = ctx.runfiles(files = ctx.files.files))]
file_check_test = rule(
implementation = _file_check_test_impl,
test = True,
attrs = {
"files": attr.label_list(allow_files = True),
"must_contain": attr.string(mandatory = True),
},
)
EOF
cat > checks/BUILD.bazel <<'EOF'
load("//build_defs:file_check.bzl", "file_check_test")
file_check_test(name = "license_test", size = "small", files = glob(["*.py"]), must_contain = "SPDX-License-Identifier")
EOF
echo "# SPDX-License-Identifier: MIT" > checks/a.py
echo "print('no header')" > checks/b.py
bazel test //checks:license_test --test_output=errors 2>&1 | grep -E '^(missing|checked)|PASSED|FAILED in'
sed -i '1i # SPDX-License-Identifier: MIT' checks/b.py
bazel test //checks:license_test 2>&1 | grep -E 'PASSED|FAILED in'missing in checks/b.py
checked 2 file(s)
//checks:license_test FAILED in 0.0s
//checks:license_test PASSED in 0.0s
The test rule's action only writes a script; bazel test runs it with the files in its runfiles (that's what ctx.runfiles(files = …) adds; f.short_path is the file's path inside the runfiles tree). Editing b.py changed a runfile, so the test reran and passed.
Rule-writing checklist
- Declare every input (
inputs = …) and output; never read paths you didn't declare. - Prefer
ctx.actions.runwith anArgsobject overrun_shellfor anything with many files or user-controlled strings (no quoting bugs). - Use
cfg = "exec"on attributes for tools that run during the build. - Make outputs deterministic: sort, strip timestamps, avoid absolute paths.
- Give actions a
mnemonicandprogress_message. - Return providers that downstream rules need: the next lesson.
Test yourself
When does a rule's implementation function run?
- During loading
- During analysis; it declares actions that run later only if needed
- During execution
- Every time an output is read
Why sort ctx.files.srcs before building a command line?
- Style
- The command line is part of the action key; an unstable order would cause cache misses
- Bazel requires it
- To speed up sha256sum
What must a rule declared with test = True return?
- Nothing
- DefaultInfo with an
executable - A TestInfo only
- A list of strings