.bzl files style guide and best practices

Overview

The Fuchsia project follows the official Bazel .bzl Style Guide, with a few exceptions. The guidance on this page is in addition to the common Bazel style guide and best practices.

.bzl files are most often used for Defining rules, macros, and functions, for which there is additional guidance.

This page is part of the Bazel style guide and best practices.

Visibility

Load visibility

Unlike .gni files, .bzl files support load visibility to restrict from where they can be loaded. By default, there are no restrictions.

Always specify visibility in .bzl files:

  • Use visibility("private") for any .bzl files not specifically intended for use outside the package.

    • Especially when a package contains a mix of public and private .bzl files, it may make sense to put the latter in a private/ directory. Bazel has mechanisms to restrict loading of files in such directories.
  • Otherwise, use visibility([...]) to specify the packages (directories) that may use it.

Load visibility uses a different syntax than target visibility:

  • Just the path is the equivalent of :__pkg__.

  • The path followed by /... is the equivalent of :__subpackages__.

For very common targets truly meant to be used across the code base, "//..." may be used. Do not use public visibility (visibility("public")). In most cases, though, a set of top-level and/or second-level directories (e.g., "//src/..." and "//sdk/lib/...") is sufficient.

Symbol visibility

Within .bzl files, prefix symbol names with an underscore to restrict access to within the .bzl file, preventing use by other files even within the same package (directory).

Do not create defs.bzl files

Though you may see them, especially in third-party repositories, defining or exporting multiple symbols that are not certain to be used together, as is often the case in defs.bzl files, is an anti-pattern. See Limit the symbols exported by each .bzl file. In all cases, choose a more descriptive file name.