TExcelTAD
Home › Monorepo Builds: Bazel (+ Buck2 & Pants) › genrule & Generated Files

genrule & Generated Files

Most monorepos generate code: constants from a config file, protobuf stubs, version headers, lookup tables. The quickest way to add a generation step is genrule, a built-in rule that runs one shell command with declared inputs and outputs.

python
genrule(
    name = "version_h",
    srcs = ["VERSION"],                   # inputs
    outs = ["version.h"],                 # outputs, relative to the package
    tools = ["//tools/codegen"],          # programs run at build time (built for the exec platform)
    cmd = "echo \"#define VERSION \\\"$(cat 
lt;)\\\"\" > $@", )

Make variables in cmd

Variable Expands to
$@ the single output (when outs has one file)
lt;
the single input (when srcs has one file)
$(SRCS), $(OUTS) all inputs / all outputs, space-separated
$(location :x), $(execpath :x) the path of the file produced by target :x, relative to the execution root
$(locations :x), $(execpaths :x) all files of :x
$(RULEDIR) the output directory of this package (bazel-out/…/bin/pkg)
$ a literal $ for the shell ($(date) would be a shell substitution; don't do that)

Every output must be listed in outs; anything else the command writes is thrown away. Every input must be in srcs or tools; anything else is not in the sandbox.

C++ generator → Python, a cross-language generated file

This genrule runs a C++ program at build time to generate a Python module, which a py_binary then imports. It's the "build-time dependency" kind of cross-language link from the polyglot lesson:

bash · try it yourself
mkdir ws && cd ws
cat > MODULE.bazel <<'EOF'
bazel_dep(name = "rules_cc", version = "0.2.27")
bazel_dep(name = "rules_python", version = "2.4.5")
EOF
mkdir -p codegen app
cat > codegen/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(name = "crc_table", srcs = ["crc_table.cc"], visibility = ["//visibility:public"])
EOF
cat > codegen/crc_table.cc <<'EOF'
#include <cstdio>
// Prints the first entries of the CRC-32 lookup table as a Python module.
int main() {
  std::printf("# Generated by //codegen:crc_table. Do not edit.\nCRC_TABLE = [");
  for (unsigned n = 0; n < 4; ++n) {
    unsigned c = n;
    for (int k = 0; k < 8; ++k) c = (c & 1) ? 0xEDB88320u ^ (c >> 1) : c >> 1;
    std::printf("%s0x%08X", n ? ", " : "", c);
  }
  std::printf("]\n");
}
EOF
cat > app/BUILD.bazel <<'EOF'
load("@rules_python//python:defs.bzl", "py_binary")
genrule(
    name = "crc_py",
    outs = ["crc.py"],
    tools = ["//codegen:crc_table"],
    cmd = "$(execpath //codegen:crc_table) > $@",
)
py_binary(name = "show", srcs = ["show.py", ":crc_py"])
EOF
printf 'from app.crc import CRC_TABLE\nprint([hex(x) for x in CRC_TABLE])\n' > app/show.py
bazel run //app:show 2>/dev/null
cat bazel-bin/app/crc.py
echo "== the generator's configuration"
bazel cquery 'deps(//app:crc_py, 1)' --noimplicit_deps 2>/dev/null
['0x0', '0x77073096', '0xee0e612c', '0x990951ba']
# Generated by //codegen:crc_table. Do not edit.
CRC_TABLE = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA]
== the generator's configuration
//app:crc_py (0a96350)
//codegen:crc_table (a0bd5d0)

Notice:

  • tools (not srcs) holds the generator, so Bazel builds it in the exec configuration, for the machine that runs the build; cquery shows the different configuration id. If the target platform were ARM, the generator would still be built for x86-64.
  • The generated crc.py lives in bazel-bin/app/, not in the source tree, and the py_binary lists it by label (:crc_py) exactly like a source file. Generated files are never committed.
  • Change crc_table.cc and Bazel reruns the generator, then everything that depends on crc.py, and nothing else.

The genrule escape hatch, and its limits

genrule is fine for a one-off step, but it has sharp edges:

Problem Better choice
The same cmd copied into many packages a macro, or a rule with attributes
You need to know the outputs' names from the inputs (one .proto → x.pb.h + x.pb.cc) a rule (outputs computed in Starlark)
You need information from dependencies (include paths, transitive files) a rule with providers
The command is a long shell script with quoting problems a real script in a sh_binary/py_binary passed as tools, plus ctx.actions.run in a rule
Portability to Windows cmd_bat/cmd_ps exist, but a tool binary is more robust

Also avoid stamp = 1 and local = True unless you mean them: local = True runs the command outside the sandbox and never caches it remotely, and stamped outputs change on every commit.

Test yourself

In a genrule, why put the generator in tools rather than srcs?

  1. No difference
  2. Targets in tools are built for the exec platform (the build machine), since they run during the build
  3. srcs can't hold binaries
  4. So it is cached remotely

What happens to a file the genrule command writes that isn't listed in outs?

  1. It becomes an output automatically
  2. It is discarded; only declared outputs exist
  3. It is written to the source tree
  4. Bazel fails silently

How do you write a literal $ for the shell in a genrule cmd?

  1. $
  2. $
  3. ${}
  4. It is impossible