bazel

How to programmatically figure out the current bazel system?


I'm writing a script which adds a dependency to an arbitrary bazel project. The script should edit the MODULE.bazel or WORKSPACE file, depending on the bazel system in use. It tries to figure out which system is used by probing the filesystem, looking for WORKSPACE, MODULE.bazel or WORKSPACE.bzlmod.

However, this heuristic is brittle, and projects (such as cppitertools) may have an empty WORKSPACE file.

Is there a way to reliably get the system in use?


Solution

  • In the most general case, it is impossible to know. That's because after your script is finished doing its thing, the user might decide to launch bazel build --enable_workspace --noenable_bzlmod //whatever, or they could instead launch bazel build --enable_bzlmod --noenable_workspace //whatever - and you have no idea which alternative the user will decide to pick, and whether or not the user is expecting for both alternatives to work, or cares only about one (and which one).

    However, as a heuristic that will work in most cases, you should prefer to edit MODULE.bazel, and fall back to editing WORKSPACE only if there is no pre-existing MODULE.bazel file. This is because the Bazel ecosystem is moving towards modules, and in Bazel 8.0 and higher, support for WORKSPACE files is disabled by default.