Skip to content

Bazel

Bazel uses a precise vocabulary built around directed acyclic graphs (DAGs) and pure functional execution. Understanding these core terms will help you read BUILD files, debug sandbox errors, and navigate the documentation without confusion.

  • Workspace: The entire directory tree on your filesystem containing all the source files for a single Bazel project.
  • MODULE.bazel: The modern root marker file (introduced with Bzlmod) that defines the workspace boundaries, declares external dependencies, and configures module extensions. (Replaces the legacy WORKSPACE file).
  • Package: Any directory inside your workspace that contains a BUILD or BUILD.bazel file. A package includes all files in that directory and any subdirectories except those that contain their own BUILD files.
  • BUILD (or BUILD.bazel): A declarative configuration file written in Starlark that defines the build targets, rules, and dependencies for a specific package.
  • Starlark: The configuration language used in BUILD, MODULE.bazel, and .bzl files. It is a deterministic, sandboxed subset of Python without I/O, network access, or arbitrary side effects.
  • .bazelignore: A root file listing workspace directories Bazel should completely ignore (e.g., node_modules, target/) so wildcards like //... don’t crawl or fail on non-Bazel trees.
  • Output Symlinks (bazel-bin, bazel-out, bazel-testlogs): Convenience symlinks Bazel creates in the workspace root pointing into its external output base where compiled artifacts and test logs live (should be gitignored).
  • Repo (External Repository): A mounted filesystem directory boundary (addressed via @repo_name) containing Bazel packages and targets. Every module is backed by a repo, and module extensions can generate additional plain repos.
  • bazel_dep: A declarative statement in MODULE.bazel that registers an external module dependency and mounts it as a repo in your workspace.
  • Module Extension (use_extension): A Starlark factory defined in a .bzl file that accepts configuration tags (like Scala versions or Maven coordinates) and dynamically generates external repos.
  • use_repo: A statement in MODULE.bazel that imports specific repos generated by a module_extension into your workspace’s @ namespace.
  • .bzl File: A Bazel extension file containing reusable Starlark logic, wrapper macros, custom rules (rule(…)), module extensions, or shared constants.
  • Target: An addressable node in Bazel’s dependency graph defined inside a BUILD file. Targets can be files (source code or generated artifacts) or rules (instructions on how to create files).
  • Rule: A function in a BUILD file (e.g., scala_binary, py_library, cc_test) that specifies the relationship between inputs and outputs, and registers the execution steps required to build them.
  • Label: The unique identifier string used to address any target in the workspace. A standard canonical label looks like @repo//path/to/package:target_name.
    • // denotes the root of the current workspace.
    • : separates the package directory path from the specific target name.
  • Visibility: An attribute on a target (visibility = [...]) that controls which other packages are allowed to depend on it. By default, targets are private to their own package.
  • Runfiles (data): Files a binary or test needs at runtime (configs, test fixtures, helper executables) rather than compile time. Declaring them in a target’s data attribute—instead of srcs or deps—tells Bazel to stage them into the runtime sandbox so they don’t fail with “file not found.”
  • Loading Phase: The first phase of a build, where Bazel reads MODULE.bazel and relevant BUILD files to parse targets and construct the initial dependency graph.
  • Analysis Phase: The second phase, where Bazel evaluates the rules, resolves toolchains, validates dependencies, and generates the Action Graph (the exact blueprint of commands to run).
  • Execution Phase: The final phase, where Bazel actually runs the compilers, linkers, and test runners defined in the Action Graph—or fetches their outputs from the cache.
  • Action: A single, atomic step during the execution phase (e.g., invoking scalac on a specific set of .scala files to produce a .jar). Every action has strictly declared inputs and outputs.
  • Client / Server: Bazel uses a lightweight CLI client that communicates with a background server process per workspace, keeping the parsed dependency graph warm in memory for fast incremental builds (bazel shutdown stops it).
  • Hermeticity: The property of a build being completely isolated from the host machine’s environment. A hermetic build cannot access undeclared files, system environment variables, or ambient network resources, guaranteeing identical outputs anywhere.
  • Sandbox: An isolated temporary directory (using OS-level namespaces or symlinks) created for a single Action. Bazel mounts only the explicitly declared input files into the sandbox so the compiler cannot accidentally touch undeclared local files.
  • Action Cache: A lookup table mapping a cryptographic hash of an Action’s inputs, flags, and compiler tools (Action Key) to its previously built output artifacts.
  • Repository Cache: A content-addressable local disk cache (--repository_cache) that stores downloaded external files (like Maven JARs or Python wheels) indexed by their SHA-256 hash so they aren’t re-downloaded across clean builds.
  • Remote Cache & RBE: Network extensions of the Action Cache (and optional Remote Build Execution) that let developers and CI share cached outputs or offload build actions to remote workers.
  • Bzlmod: Bazel’s modern external dependency management system (powered by MODULE.bazel and MODULE.bazel.lock) that handles version resolution via Minimal Version Selection (MVS).
  • .bzl File: A Starlark extension file where reusable custom rules, macros, and repository extensions are written and loaded into BUILD files via load(...).
  • Macro: A Starlark function in a .bzl file that expands into one or more rules during the Loading Phase. Unlike a Rule (which registers build actions during analysis), a macro encapsulates repetitive target definitions to keep BUILD files concise.
  • Toolchain: An abstraction that decouples a build rule (e.g., “compile Scala”) from the specific platform tools required to run it (e.g., “use JDK 17 and Scala 3.9 on Linux x86_64”).
  • Platform: A target describing a machine environment (OS, CPU architecture, and custom constraints) used to select the matching Toolchain and evaluate conditional select() branches across host, execution, and target platforms.
  • Persistent Worker: A long-lived background process (commonly used for JVM/Scala compilers like Zinc) that stays warm across multiple Actions to avoid heavy runtime startup overhead while maintaining sandbox isolation.
  • Gazelle: A fast, automated build-file generator that scans source code imports (import ..., #include ...) and automatically updates BUILD files with the corresponding dependency labels.
  • Bazelisk & .bazelversion: A launcher wrapper (similar to nvm/pyenv) that automatically downloads and runs the exact Bazel version pinned in your repository’s .bazelversion file.
  • Named Profile (--config): A labeled group of command-line flags defined in .bazelrc using <command>:<name> syntax (e.g., build:ci, build:opt, build:asan). Invoking Bazel with --config=<name> expands all flags under that profile, making it easy to switch between build modes or environments without typing long flag lists.

Bazel provides distinct sets of built-in Starlark functions depending on whether you are editing MODULE.bazel or a BUILD file. Because MODULE.bazel resolves the external dependency graph and BUILD files declare compilation targets, each file scope exposes only the functions relevant to its phase.


1. Functions Used in MODULE.bazel (Bzlmod)

Section titled “1. Functions Used in MODULE.bazel (Bzlmod)”

These functions manage your project’s identity, external Bazel modules, and third-party package resolvers like Maven.

  • module(): Declares the name, version, and compatibility level of your root Bazel module. Must be called first.
    • Scala Example: module(name = "my_scala_app", version = "0.1.0")
  • bazel_dep(): Declares a direct dependency on another Bazel module from the Bazel Central Registry (BCR).
    • Scala Example: bazel_dep(name = "rules_scala", version = "7.4.0")
  • use_extension(): Instantiates a module extension (a Starlark hook that runs custom resolution logic, like fetching Maven artifacts) and returns a proxy object.
    • Scala Example: maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven")
  • use_repo(): Imports repositories generated by a use_extension() proxy into your module’s scope so @repo labels resolve.
    • Scala Example: use_repo(maven, "maven")
  • register_toolchains(): Registers specific compiler or runtime toolchains for Bazel’s toolchain resolution engine to select.
    • Scala Example: register_toolchains("@rules_scala_toolchains//...")
  • single_version_override(): Forces a transitive Bazel module to use a specific version or patch, resolving version conflicts.
    • Scala Example: single_version_override(module_name = "protobuf", version = "27.1")
  • git_override(): Overrides a bazel_dep to pull directly from a specific Git repository and commit hash instead of the BCR.
    • Scala Example: git_override(module_name = "rules_scala", remote = "...", commit = "abc1234")
module(name = "analytics_service", version = "1.0.0")
bazel_dep(name = "rules_scala", version = "7.4.0")
bazel_dep(name = "rules_jvm_external", version = "6.1")
scala_config = use_extension("@rules_scala//scala/extensions:config.bzl", "scala_config")
scala_config.settings(scala_version = "3.9.0")
use_repo(scala_config, "rules_scala_toolchains")
maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven")
maven.install(
artifacts = ["org.typelevel:cats-effect_3:3.5.4"],
lock_file = "//:maven_install.json",
)
use_repo(maven, "maven")

2. Core Built-in Functions Used in BUILD Files

Section titled “2. Core Built-in Functions Used in BUILD Files”

These functions are globally available in every BUILD and BUILD.bazel file without needing a load() statement.

  • load(): Imports rule functions, macros, or constants from a .bzl extension file into the current BUILD file.
    • Scala Example: load("@rules_scala//scala:scala.bzl", "scala_library", "scala_binary")
  • glob(): Matches files in the current package directory using wildcard patterns (*, **) and returns a list of file labels.
    • Scala Example: srcs = glob(["src/main/scala/**/*.scala"])
  • package(): Sets default metadata (like default visibility) for every target defined in the current BUILD file.
    • Scala Example: package(default_visibility = ["//visibility:public"])
  • exports_files(): Exposes raw source or config files in this package so other packages can reference them directly by label.
    • Scala Example: exports_files(["application.conf"])
  • filegroup(): Groups a collection of files under a single target label so they can be passed together as inputs or resources.
    • Scala Example: filegroup(name = "configs", srcs = glob(["conf/*.yaml"]))
  • alias(): Creates an alternative target label that points to another target (useful for renaming or platform switching).
    • Scala Example: alias(name = "server", actual = "//src/app:http_server")
  • config_setting(): Defines a named build condition matching specific command-line flags or platform constraints (OS, CPU, compilation mode) so targets can branch on it.
    • Example: config_setting(name = "linux_x86", constraint_values = ["@platforms//os:linux", "@platforms//cpu:x86_64"])
  • select(): Makes any rule attribute (like deps, srcs, or compiler flags) conditional on config_setting() targets—the standard way to write portable, multi-platform BUILD files without breaking hermeticity.
    • Example: deps = [":core"] + select({":linux_x86": [":native_linux"], "//conditions:default": []})
  • genrule(): A built-in escape hatch for running an arbitrary Bash command to transform declared srcs into declared outs when no dedicated language rule exists. Prefer language-specific rules or custom .bzl rules for anything complex or cross-platform.
    • Example: genrule(name = "version_txt", outs = ["version.txt"], cmd = "echo 1.0.0 > $@")

3. Scala Rule Functions (Loaded from rules_scala)

Section titled “3. Scala Rule Functions (Loaded from rules_scala)”

Unlike built-ins, language-specific rules are Starlark functions imported via load().

  • scala_library(): Compiles .scala source files into a .jar library that other targets can depend on.
    • Example: scala_library(name = "core", srcs = glob(["*.scala"]), deps = ["@maven//:org_typelevel_cats_core_3"])
  • scala_binary(): Compiles .scala files and packages an executable wrapper script (plus an implicit _deploy.jar target).
    • Example: scala_binary(name = "cli", srcs = ["Main.scala"], main_class = "com.app.Main", deps = [":core"])
  • scala_junit_test(): Compiles and runs JUnit-compatible test suites (including MUnit and ScalaTest) with test caching.
    • Example: scala_junit_test(name = "core_test", srcs = glob(["*Spec.scala"]), deps = [":core", "@maven//:org_scalameta_munit_3"])
  • scala_macro_library(): Compiles Scala code containing macros, ensuring the macro definitions are available on the compile-time classpath.
    • Example: scala_macro_library(name = "macros", srcs = ["Macros.scala"])
load("@rules_scala//scala:scala.bzl", "scala_binary", "scala_library")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "app_resources",
srcs = glob(["resources/*"]),
)
scala_library(
name = "domain",
srcs = glob(["*.scala"], exclude = ["Main.scala"]),
deps = [
"@maven//:org_typelevel_cats_effect_3",
],
)
scala_binary(
name = "app",
srcs = ["Main.scala"],
main_class = "com.example.Main",
resources = [":app_resources"],
deps = [
":domain",
"@maven//:org_typelevel_cats_effect_3",
],
)

.bazelrc is Bazel’s configuration file for specifying default command-line flags and reusable flag presets, keeping build behavior consistent across developers and CI without repeating long flag lists.

  • strict_deps: A rules_scala check that fails the build if your code directly references a symbol from a transitive dependency without declaring it in your target’s direct deps.

  • unused_dependency_checker: A rules_scala check that inspects compiled bytecode to flag declared deps that aren’t actually used by your code.

  • Command-Scoped Defaults: Apply flags automatically to specific Bazel commands (startup, common, build, test, run, query), e.g., common --enable_bzlmod or test --test_output=errors.

  • Named Profiles (--config): Group related flags into reusable profiles (e.g., build:ci, build:opt, build:asan) that can be activated on demand via bazel test --config=ci //....

  • Layered Precedence: Bazel loads rc files in order—system (/etc/bazel.bazelrc), workspace (<workspace>/.bazelrc), user (~/.bazelrc), explicit (--bazelrc=<path>), and CLI flags—with later entries overriding earlier ones.

  • Modular Imports: Compose configs across files using import (required) or try-import (optional), commonly used for untracked local overrides like try-import %workspace%/user.bazelrc.

  • Shared Team Standards: Checking <workspace>/.bazelrc into version control standardizes toolchain options, remote caching/execution settings, and CI behavior across the team.


  • bazel build <target>: Compiles the target and its transitive dependencies, placing outputs under bazel-bin/.
  • bazel test <target>: Builds and executes test targets, caching passing results so unchanged tests aren’t re-run.
  • bazel run <target>: Builds an executable target and runs it with its data runfiles staged (pass runtime args after --, e.g., bazel run //src/app:cli -- --port=8080).
  • bazel query <expr>: Inspects the dependency graph without building—invaluable for debugging BUILD files (e.g., bazel query 'somepath(//app:server, @maven//:cats)' to see why a target depends on a library, or rdeps(//..., //lib:core) to find all reverse dependencies).
  • bazel mod <subcommand>: Inspects the resolved Bzlmod dependency graph (e.g., bazel mod graph, bazel mod explain <module>).
  • bazel clean: Deletes output artifacts (rarely needed thanks to hermetic caching; bazel clean --expunge also wipes the external repository cache and shuts down the server).
  • Buildozer: A CLI tool from bazelbuild/buildtools that safely edits BUILD.bazel files via their AST (e.g., adding or removing deps) without breaking formatting or comments.
  • //...: All targets recursively across the entire workspace.
  • //pkg/...: All targets in pkg and every subpackage underneath it.
  • //pkg:all: All rule targets in pkg (non-recursive).
  • :target: Shorthand for a target in the current working directory’s package.
  • -//pkg/...: Excludes a package subtree when combined with broader patterns (e.g., bazel test -- //... -//experimental/...).