---
layout: documentation
title: Extension Examples
---
# Extension Examples
**Tip:** For further examples, see the [GitHub repository](https://github.com/bazelbuild/examples/tree/master/rules).
## Macro creating a rule
An example of a macro creating a rule.
`empty.bzl`:
```python
def _impl(ctx):
print("This rule does nothing")
empty = rule(implementation=_impl)
```
`extension.bzl`:
```python
# Loading the rule. The rule doesn't have to be in a separate file.
load("//pkg:empty.bzl", "empty")
def macro(name, visibility=None):
# Creating the rule.
empty(name = name, visibility = visibility)
```
`BUILD`:
```python
load("//pkg:extension.bzl", "macro")
macro(name = "myrule")
```
## Macro creating a native rule
An example of a macro creating a native rule. Native rules are special rules
that are automatically available (without load
). They are
accessed using the native module.
`extension.bzl`:
```python
def macro(name, visibility=None):
# Creating a native genrule.
native.genrule(
name = name,
outs = [name + ".txt"],
cmd = "echo hello > $@",
visibility = visibility,
)
```
`BUILD`:
```python
load("//pkg:extension.bzl", "macro")
macro(name = "myrule")
```
## Macro multiple rules
There's currently no easy way to create a rule that directly uses the
action of a native rule. You can work around this using macros:
```python
def _impl(ctx):
return struct([...],
# When instrumenting this rule, again hide implementation from
# users.
instrumented_files(
source_attributes = ["srcs", "csrcs"],
dependency_attributes = ["deps", "cdeps"]))
# This rule is private and can only be accessed from the current file.
_cc_and_something_else_binary = rule(implementation=_impl)
# This macro is public, it's the public interface to instantiate the rule.
def cc_and_something_else_binary(name, srcs, deps, csrcs, cdeps):
cc_binary_name = "%s.cc_binary" % name
native.cc_binary(
name = cc_binary_name,
srcs = csrcs,
deps = cdeps,
visibility = ["//visibility:private"]
)
_cc_and_something_else_binary(
name = name,
srcs = srcs,
deps = deps,
# A label attribute so that this depends on the internal rule.
cc_binary = cc_binary_name,
# Redundant labels attributes so that the rule with this target name knows
# about everything it would know about if cc_and_something_else_binary
# were an actual rule instead of a macro.
csrcs = csrcs,
cdeps = cdeps)
```
## Conditional instantiation
Macros can look at previously instantiated rules. This is done with
`native.existing_rule`, which returns information on a single rule defined in
the same `BUILD` file, eg.,
```python
native.existing_rule("descriptor_proto")
```
This is useful to avoid instantiating the same rule twice, which is an
error. For example, the following macro will simulate a test suite,
instantiating tests for diverse flavors of the same test.
`extension.bzl`:
```python
def system_test(name, test_file, flavor):
n = "system_test_%s_%s_test" % (test_file, flavor)
if native.existing_rule(n) == None:
native.py_test(
name = n,
srcs = [
"test_driver.py",
test_file,
],
args = ["--flavor=" + flavor],
)
return n
def system_test_suite(name, flavors=["default"], test_files=[]):
ts = []
for flavor in flavors:
for test in test_files:
ts.append(system_test(name, test, flavor))
native.test_suite(name = name, tests = ts)
```
In the following BUILD file, note how `(basic_test.py, fast)` is emitted for
both the `smoke` test suite and the `thorough` test suite.
`BUILD`:
```python
load("//pkg:extension.bzl", "system_test_suite")
# Run all files through the 'fast' flavor.
system_test_suite(
name = "smoke",
flavors = ["fast"],
test_files = glob(["*_test.py"]),
)
# Run the basic test through all flavors.
system_test_suite(
name = "thorough",
flavors = [
"fast",
"debug",
"opt",
],
test_files = ["basic_test.py"],
)
```
## Aggregating over the BUILD file
Macros can collect information from the BUILD file as processed so far. We call
this aggregation. The typical example is collecting data from all rules of a
certain kind. This is done by calling
native.existing\_rules, which
returns a dictionary representing all rules defined so far in the current BUILD
file. The dictionary has entries of the form `name` => `rule`, with the values
using the same format as `native.existing_rule`.
```python
def archive_cc_src_files(tag):
"""Create an archive of all C++ sources that have the given tag."""
all_src = []
for r in native.existing_rules().values():
if tag in r["tags"] and r["kind"] == "cc_library":
all_src.append(r["srcs"])
native.genrule(cmd = "zip $@ $^", srcs = all_src, outs = ["out.zip"])
```
Since `native.existing_rules` constructs a potentially large dictionary, you
should avoid calling it repeatedly within BUILD file.
## Empty rule
Minimalist example of a rule that does nothing. If you build it, the target will
succeed (with no generated file).
[See example on GitHub](https://github.com/bazelbuild/examples/tree/master/rules/empty)
`empty.bzl`:
```python
def _impl(ctx):
# You may use print for debugging.
print("This rule does nothing")
empty = rule(implementation=_impl)
```
`BUILD`:
```python
load("//pkg:empty.bzl", "empty")
empty(name = "nothing")
```
## Rule with attributes
Example of a rule that shows how to declare attributes and access them.
[See example on GitHub](https://github.com/bazelbuild/examples/tree/master/rules/attributes)
`printer.bzl`:
```python
def _impl(ctx):
# You may use print for debugging.
print("Rule name = %s, package = %s" % (ctx.label.name, ctx.label.package))
# This prints the labels of the deps attribute.
print("There are %d deps" % len(ctx.attr.deps))
for i in ctx.attr.deps:
print("- %s" % i.label)
# A label can represent any number of files (possibly 0).
print(" files = %s" % [f.path for f in i.files])
printer = rule(
implementation=_impl,
attrs={
# Do not declare "name": It is added automatically.
"number": attr.int(default = 1),
"deps": attr.label_list(allow_files=True),
})
```
`BUILD`:
```python
load("//pkg:printer.bzl", "printer")
printer(
name = "nothing",
deps = [
"BUILD",
":other",
],
)
printer(name = "other")
```
If you execute this file, some information is printed as a warning by the
rule. No file is generated.
## Simple shell command
Example of a rule that runs a shell command on an input file specified by
the user. The output has the same name as the rule, with a `.size` suffix.
While convenient, Shell commands should be used carefully. Generating the
command-line can lead to escaping and injection issues. It can also create
portability problems. It is often better to declare a binary target in a
BUILD file and execute it.
See the example [executing a binary](#execute-bin).
`size.bzl`:
```python
def _impl(ctx):
output = ctx.outputs.out
input = ctx.file.file
# The command may only access files declared in inputs.
ctx.actions.run_shell(
inputs=[input],
outputs=[output],
progress_message="Getting size of %s" % input.short_path,
command="stat -L -c%%s %s > %s" % (input.path, output.path))
size = rule(
implementation=_impl,
attrs={"file": attr.label(mandatory=True, allow_files=True, single_file=True)},
outputs={"out": "%{name}.size"},
)
```
`foo.txt`:
```
Hello
```
`BUILD`:
```python
load("//pkg:size.bzl", "size")
size(
name = "foo_size",
file = "foo.txt",
)
```
## Write string to a file
Example of a rule that writes a string to a file.
`file.bzl`:
```python
def _impl(ctx):
output = ctx.outputs.out
ctx.file_action(output=output, content=ctx.attr.content)
file = rule(
implementation=_impl,
attrs={"content": attr.string()},
outputs={"out": "%{name}.txt"},
)
```
`BUILD`:
```python
load("//pkg:file.bzl", "file")
file(
name = "hello",
content = "Hello world",
)
```
## Execute a binary
This rule executes an existing binary. In this particular example, the
binary is a tool that merges files. During the analysis phase, we cannot
access any arbitrary label: the dependency must have been previously
declared. To do so, the rule needs a label attribute. In this example, we
will give the label a default value and make it private (so that it is not
visible to end users). Keeping the label private can simplify maintenance,
since you can easily change the arguments and flags you pass to the tool.
`execute.bzl`:
```python
def _impl(ctx):
# The list of arguments we pass to the script.
args = [ctx.outputs.out.path] + [f.path for f in ctx.files.srcs]
# Action to call the script.
ctx.actions.run(
inputs=ctx.files.srcs,
outputs=[ctx.outputs.out],
arguments=args,
progress_message="Merging into %s" % ctx.outputs.out.short_path,
executable=ctx.executable._merge_tool)
concat = rule(
implementation=_impl,
attrs={
"srcs": attr.label_list(allow_files=True),
"out": attr.output(mandatory=True),
"_merge_tool": attr.label(executable=True, cfg="host", allow_files=True,
default=Label("//pkg:merge"))
}
)
```
Any executable target can be used. In this example, we will use a
`sh_binary` rule that concatenates all the inputs.
`BUILD`:
```
load("execute", "concat")
concat(
name = "sh",
srcs = [
"header.html",
"body.html",
"footer.html",
],
out = "page.html",
)
# This target is used by the shell rule.
sh_binary(
name = "merge",
srcs = ["merge.sh"],
)
```
`merge.sh`:
```sh
#!/bin/sh
out=$1
shift
cat "$@" > $out
```
`header.html`:
```