Practical Bazel: Prefix All Generated Files
Practical Bazel bazel
Published: 2020-11-04

When writing a custom rule that generates files, be sure to add prefixes to all filenames so that multiple instances of your rule can be instantiated within the same Bazel package.

I like to place all generated files in a subdirectory prefixed with the rule’s label and %, as in:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def _impl(ctx):
    prefix = ctx.label.name + "%/"
    file1 = ctx.actions.declare_file(prefix + "generated_file1.txt")
    # generate file1
    file2 = ctx.actions.declare_file(prefix + "generated_file2.txt")
    # generate file2
    ...

my_rule = rule(
    _impl,
    attrs = {
        ...
    },
)