Building up on the file example, we can create a rule that builds and runs a simple executable shell script.
Rename the rule #
To begin with, let’s rename the rule as it is customary in Bazel to postfix
the executable rules with _binary
. Our BUILD
file will now be:
load(":rules.bzl", "demo_binary")
demo_binary(name = "executable")
Renaming the functions in rules.bzl
is trivial:
def _demo_binary_impl(ctx):
...
demo_binary = rule(
implementation = _demo_binary_impl,
...
Create a script #
We can now change the generated file to a shell script
def _demo_binary_impl(ctx):
out = ctx.actions.declare_file("hello")
ctx.actions.write(
output = out,
content = "#!/bin/sh\necho \"Hello, World!\"\n",
)
...
Make the rule executable #
Finally, we mark the rule as an executable and specify the our script as the executable file:
def _demo_binary_impl(ctx):
...
return [DefaultInfo(
files = depset([out]),
executable = out,
)]
demo_binary = rule(
implementation = _demo_binary_impl,
executable = True,
)
Build and run #
We can now build the file as we did before:
$ bazel build //executable
...
Target //executable:executable up-to-date:
bazel-bin/executable/hello
...
We can use Bazel to run it as well:
$ bazel run //executable
...
Target //executable:executable up-to-date:
bazel-bin/executable/hello
...
Hello, World!
We can also run the script directly:
$ bazel-bin/executable/hello
Hello, World!
The complete example is here.