BAZEL Bazel build file
AI-powered detection and analysis of Bazel build file files.
Instant BAZEL File Detection
Use our advanced AI-powered tool to instantly detect and analyze Bazel build file files with precision and speed.
File Information
Bazel build file
Code
.bazel, .bzl
text/plain
Bazel Build Configuration (.bazel)
Bazel is a fast, scalable build tool developed by Google that supports multi-language builds and tests. Originally derived from Google's internal build tool called Blaze, Bazel was open-sourced in 2015. It uses BUILD files (often with .bazel extension) to define build targets, dependencies, and rules. Bazel is designed to handle large codebases efficiently with features like incremental builds, remote caching, and parallel execution.
Technical Overview
Bazel operates on the concept of workspaces, packages, and targets. BUILD files define packages containing multiple targets (executables, libraries, tests). Bazel uses a declarative approach where developers specify what to build rather than how to build it. The build system creates a directed acyclic graph (DAG) of dependencies and executes builds in parallel when possible.
Key Features
- Fast Incremental Builds: Only rebuilds what has changed
- Remote Caching: Share build artifacts across teams and CI/CD
- Remote Execution: Distribute builds across multiple machines
- Multi-Language Support: Java, C++, Python, Go, JavaScript, and more
- Hermetic Builds: Reproducible builds with explicit dependencies
- Scalability: Handles large monorepos with millions of lines of code
Bazel BUILD File Syntax
Basic BUILD File Structure
# BUILD.bazel or BUILD file
load("@rules_java//java:defs.bzl", "java_binary", "java_library", "java_test")
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
# Package declaration (optional)
package(default_visibility = ["//visibility:public"])
# License declaration
licenses(["notice"]) # Apache 2.0, MIT, etc.
# Java library target
java_library(
name = "hello-lib",
srcs = ["src/main/java/com/example/Hello.java"],
deps = [
"//third_party:guava",
"@maven//:org_apache_commons_commons_lang3",
],
visibility = ["//visibility:public"],
)
# Java binary target
java_binary(
name = "hello-world",
srcs = ["src/main/java/com/example/HelloWorld.java"],
main_class = "com.example.HelloWorld",
deps = [":hello-lib"],
jvm_flags = ["-Xmx256m"],
data = ["//data:config.properties"],
)
# C++ library
cc_library(
name = "math-lib",
srcs = [
"src/math/calculator.cc",
"src/math/operations.cc",
],
hdrs = [
"src/math/calculator.h",
"src/math/operations.h",
],
includes = ["src"],
deps = ["@com_google_absl//absl/strings"],
)
# C++ binary
cc_binary(
name = "calculator",
srcs = ["src/main.cc"],
deps = [":math-lib"],
copts = ["-std=c++17"],
linkopts = ["-lm"],
)
# Test target
java_test(
name = "hello-test",
srcs = ["src/test/java/com/example/HelloTest.java"],
test_class = "com.example.HelloTest",
deps = [
":hello-lib",
"@maven//:junit_junit",
"@maven//:org_hamcrest_hamcrest_core",
],
size = "small",
timeout = "short",
)
# File group for documentation
filegroup(
name = "docs",
srcs = glob(["docs/**/*.md"]),
visibility = ["//visibility:public"],
)
# Shell script
sh_binary(
name = "deploy",
srcs = ["scripts/deploy.sh"],
data = [
":hello-world",
"//config:production.yaml",
],
)
Advanced BUILD Patterns
# Globbing patterns
java_library(
name = "all-sources",
srcs = glob([
"src/main/java/**/*.java",
], exclude = [
"src/main/java/**/*Test.java",
"src/main/java/**/testdata/**",
]),
)
# Select expressions for platform-specific code
cc_library(
name = "platform-lib",
srcs = select({
"@platforms//os:linux": ["linux_impl.cc"],
"@platforms//os:macos": ["macos_impl.cc"],
"@platforms//os:windows": ["windows_impl.cc"],
"//conditions:default": ["generic_impl.cc"],
}),
hdrs = ["platform_lib.h"],
)
# Conditional compilation flags
cc_binary(
name = "app",
srcs = ["app.cc"],
copts = select({
"//:debug_build": ["-g", "-O0", "-DDEBUG"],
"//conditions:default": ["-O2", "-DNDEBUG"],
}),
deps = [":platform-lib"],
)
# Configurable attributes
config_setting(
name = "debug_build",
values = {"compilation_mode": "dbg"},
)
# Custom rule usage
load("//tools:custom_rules.bzl", "proto_library_custom")
proto_library_custom(
name = "api_proto",
srcs = ["api.proto"],
deps = ["@com_google_protobuf//:any_proto"],
)
# Macro usage
load("//macros:java_macros.bzl", "java_library_with_tests")
java_library_with_tests(
name = "service",
srcs = ["Service.java"],
test_srcs = ["ServiceTest.java"],
deps = ["//third_party:guava"],
test_deps = ["//third_party:mockito"],
)
WORKSPACE Configuration
WORKSPACE File
# WORKSPACE.bazel or WORKSPACE file
workspace(name = "my_project")
# Load repository rules
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
# Java rules
http_archive(
name = "rules_java",
urls = [
"https://github.com/bazelbuild/rules_java/releases/download/6.0.0/rules_java-6.0.0.tar.gz",
],
sha256 = "469b7f3b580b4fcf8112f4d6d0d5a4ce8e1ad5e21fee67d8e8335d5f1c6fdac8",
)
# C++ rules
http_archive(
name = "rules_cc",
urls = ["https://github.com/bazelbuild/rules_cc/releases/download/0.0.6/rules_cc-0.0.6.tar.gz"],
sha256 = "3d9e271e2876ba42e114c9b9bc51454e379cbf0ec9ef9d40e2ae4cec61a31b40",
)
# Python rules
http_archive(
name = "rules_python",
sha256 = "0a8003b044294d7840ac7d9d73eef05d6ceb682d7516781a4ec62eeb34702578",
strip_prefix = "rules_python-0.24.0",
url = "https://github.com/bazelbuild/rules_python/releases/download/0.24.0/rules_python-0.24.0.tar.gz",
)
# Go rules
http_archive(
name = "io_bazel_rules_go",
sha256 = "278b7ff5a826f3dc10f04feaf0b70d48b68748ccd512d7f98bf442077f043fe3",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.41.0/rules_go-v0.41.0.zip",
"https://github.com/bazelbuild/rules_go/releases/download/v0.41.0/rules_go-v0.41.0.zip",
],
)
# Protocol Buffers
http_archive(
name = "com_google_protobuf",
sha256 = "3bd7828aa5af4b13b99c191e8b1e884ebfa9ad371b0ce264605d347f135d2568",
strip_prefix = "protobuf-3.19.4",
urls = [
"https://github.com/protocolbuffers/protobuf/archive/v3.19.4.tar.gz",
],
)
# gRPC
http_archive(
name = "com_github_grpc_grpc",
urls = [
"https://github.com/grpc/grpc/archive/refs/tags/v1.50.0.tar.gz",
],
strip_prefix = "grpc-1.50.0",
)
# Maven dependencies
http_archive(
name = "rules_jvm_external",
sha256 = "f86fd42a809e1871ca0aabe89db0d440451219c3ce46c58da240c7dcdc00125f",
strip_prefix = "rules_jvm_external-5.2",
url = "https://github.com/bazelbuild/rules_jvm_external/releases/download/5.2/rules_jvm_external-5.2.tar.gz",
)
load("@rules_jvm_external//:repositories.bzl", "rules_jvm_external_deps")
rules_jvm_external_deps()
load("@rules_jvm_external//:setup.bzl", "rules_jvm_external_setup")
rules_jvm_external_setup()
load("@rules_jvm_external//:defs.bzl", "maven_install")
maven_install(
artifacts = [
"com.google.guava:guava:31.1-jre",
"junit:junit:4.13.2",
"org.hamcrest:hamcrest-core:1.3",
"org.apache.commons:commons-lang3:3.12.0",
"com.fasterxml.jackson.core:jackson-core:2.14.2",
"org.slf4j:slf4j-api:2.0.6",
"ch.qos.logback:logback-classic:1.4.5",
],
repositories = [
"https://repo1.maven.org/maven2",
"https://maven.google.com",
],
)
# Node.js rules
http_archive(
name = "build_bazel_rules_nodejs",
sha256 = "5dd1e5dea1322174c57d3ca7b899da381d516220793d0adef3ba03b9d23baa8e",
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/5.8.0/rules_nodejs-5.8.0.tar.gz"],
)
# Docker rules
http_archive(
name = "io_bazel_rules_docker",
sha256 = "b1e80761a8a8243d03ebca8845e9cc1ba6c82ce7c5179ce2b295cd36f7e394bf",
urls = ["https://github.com/bazelbuild/rules_docker/releases/download/v0.25.0/rules_docker-v0.25.0.tar.gz"],
)
# Load and setup rules
load("@rules_java//java:repositories.bzl", "rules_java_dependencies", "rules_java_toolchains")
rules_java_dependencies()
rules_java_toolchains()
load("@rules_python//python:repositories.bzl", "py_repositories", "python_register_toolchains")
py_repositories()
python_register_toolchains(
name = "python3_11",
python_version = "3.11",
)
load("@io_bazel_rules_go//go:deps.bzl", "go_rules_dependencies", "go_register_toolchains")
go_rules_dependencies()
go_register_toolchains(version = "1.20.5")
# Custom repository
git_repository(
name = "my_custom_rules",
remote = "https://github.com/myorg/my-custom-rules.git",
tag = "v1.0.0",
)
Custom Rules and Macros
Custom Rule Definition
# tools/custom_rules.bzl
def _proto_library_custom_impl(ctx):
"""Implementation function for custom proto library rule."""
proto_sources = ctx.files.srcs
output_dir = ctx.actions.declare_directory(ctx.label.name + "_proto_out")
# Generate protocol buffer files
ctx.actions.run(
executable = ctx.executable._protoc,
arguments = [
"--proto_path=" + ctx.label.package,
"--java_out=" + output_dir.path,
] + [f.path for f in proto_sources],
inputs = proto_sources + ctx.files.deps,
outputs = [output_dir],
tools = [ctx.executable._protoc],
mnemonic = "ProtoCompile",
progress_message = "Compiling protocol buffers for %s" % ctx.label,
)
return [DefaultInfo(files = depset([output_dir]))]
proto_library_custom = rule(
implementation = _proto_library_custom_impl,
attrs = {
"srcs": attr.label_list(
allow_files = [".proto"],
mandatory = True,
doc = "Protocol buffer source files",
),
"deps": attr.label_list(
providers = [ProtoInfo],
doc = "Protocol buffer dependencies",
),
"_protoc": attr.label(
default = "@com_google_protobuf//:protoc",
executable = True,
cfg = "exec",
),
},
doc = "Custom protocol buffer library rule",
)
# Macro for Java libraries with automatic test generation
def java_library_with_tests(name, srcs, test_srcs, deps = [], test_deps = [], **kwargs):
"""Macro that creates a Java library and its corresponding test."""
# Create the main library
native.java_library(
name = name,
srcs = srcs,
deps = deps,
**kwargs
)
# Create the test if test sources are provided
if test_srcs:
native.java_test(
name = name + "_test",
srcs = test_srcs,
test_class = _derive_test_class(test_srcs[0]),
deps = [
":" + name,
"@maven//:junit_junit",
] + test_deps,
size = "small",
)
def _derive_test_class(test_file):
"""Derive the test class name from the test file path."""
# Convert path/to/TestClass.java -> path.to.TestClass
return test_file.replace("/", ".").replace(".java", "")
# Configuration rule for feature flags
def _feature_flag_impl(ctx):
return [config_common.FeatureFlagInfo(value = ctx.attr.value)]
feature_flag = rule(
implementation = _feature_flag_impl,
attrs = {
"value": attr.string(mandatory = True),
},
doc = "A feature flag that can be used in select() expressions",
)
Aspect for Code Analysis
# tools/analysis.bzl
def _code_coverage_aspect_impl(target, ctx):
"""Aspect that adds code coverage instrumentation."""
if JavaInfo in target:
# Process Java targets
instrumented_jar = ctx.actions.declare_file(
target.label.name + "_instrumented.jar"
)
ctx.actions.run(
executable = ctx.executable._coverage_tool,
arguments = [
"--input", target[JavaInfo].compile_jar.path,
"--output", instrumented_jar.path,
"--coverage-metadata", ctx.outputs.coverage_metadata.path,
],
inputs = [target[JavaInfo].compile_jar],
outputs = [instrumented_jar, ctx.outputs.coverage_metadata],
tools = [ctx.executable._coverage_tool],
)
return [
OutputGroupInfo(
instrumented_jars = depset([instrumented_jar]),
coverage_metadata = depset([ctx.outputs.coverage_metadata]),
)
]
return []
code_coverage_aspect = aspect(
implementation = _code_coverage_aspect_impl,
attr_aspects = ["deps"],
attrs = {
"_coverage_tool": attr.label(
default = "//tools:coverage_instrumenter",
executable = True,
cfg = "exec",
),
},
outputs = {
"coverage_metadata": "%{name}.coverage_metadata",
},
)
# Usage in BUILD file:
# bazel build --aspects=//tools:analysis.bzl%code_coverage_aspect //src:my_library
Platform and Toolchain Configuration
Platform Definition
# platforms/BUILD.bazel
load("@platforms//os:defs.bzl", "os")
load("@platforms//cpu:defs.bzl", "cpu")
# Define custom platforms
platform(
name = "linux_x86_64",
constraint_values = [
"@platforms//os:linux",
"@platforms//cpu:x86_64",
],
)
platform(
name = "macos_arm64",
constraint_values = [
"@platforms//os:macos",
"@platforms//cpu:arm64",
],
)
platform(
name = "windows_x86_64",
constraint_values = [
"@platforms//os:windows",
"@platforms//cpu:x86_64",
],
)
# Custom constraint for CUDA support
constraint_setting(name = "cuda")
constraint_value(
name = "cuda_enabled",
constraint_setting = ":cuda",
)
constraint_value(
name = "cuda_disabled",
constraint_setting = ":cuda",
)
platform(
name = "linux_x86_64_cuda",
constraint_values = [
"@platforms//os:linux",
"@platforms//cpu:x86_64",
":cuda_enabled",
],
)
Toolchain Configuration
# toolchains/BUILD.bazel
load("@rules_cc//cc:defs.bzl", "cc_toolchain", "cc_toolchain_suite")
# Custom C++ toolchain
cc_toolchain_suite(
name = "custom_toolchain_suite",
toolchains = {
"k8": ":custom_toolchain",
"darwin": ":custom_toolchain_macos",
},
)
cc_toolchain(
name = "custom_toolchain",
toolchain_identifier = "custom-linux-toolchain",
toolchain_config = ":custom_toolchain_config",
all_files = ":custom_compiler_files",
compiler_files = ":custom_compiler_files",
dwp_files = ":empty",
linker_files = ":custom_linker_files",
strip_files = ":empty",
supports_param_files = 1,
)
# Toolchain configuration
load("//toolchains:custom_toolchain_config.bzl", "custom_toolchain_config")
custom_toolchain_config(
name = "custom_toolchain_config",
cpu = "k8",
compiler = "gcc",
toolchain_identifier = "custom-linux-toolchain",
host_system_name = "local",
target_system_name = "local",
target_libc = "unknown",
abi_version = "unknown",
abi_libc_version = "unknown",
tool_paths = {
"gcc": "/usr/bin/gcc-11",
"g++": "/usr/bin/g++-11",
"ar": "/usr/bin/ar",
"ld": "/usr/bin/ld",
"nm": "/usr/bin/nm",
"objdump": "/usr/bin/objdump",
"strip": "/usr/bin/strip",
},
compile_flags = [
"-fstack-protector",
"-Wall",
"-Wunused-but-set-parameter",
"-Wno-free-nonheap-object",
"-fno-omit-frame-pointer",
],
opt_compile_flags = [
"-g0",
"-O2",
"-DNDEBUG",
"-ffunction-sections",
"-fdata-sections",
],
dbg_compile_flags = ["-g"],
link_flags = [
"-fuse-ld=gold",
"-Wl,-no-as-needed",
"-Wl,-z,relro,-z,now",
"-B/usr/bin",
"-pass-exit-codes",
],
link_libs = ["-lstdc++", "-lm"],
opt_link_flags = ["-Wl,--gc-sections"],
unfiltered_compile_flags = [
"-no-canonical-prefixes",
"-Wno-builtin-macro-redefined",
"-D__DATE__=\"redacted\"",
"-D__TIMESTAMP__=\"redacted\"",
"-D__TIME__=\"redacted\"",
],
coverage_compile_flags = ["--coverage"],
coverage_link_flags = ["--coverage"],
supports_start_end_lib = True,
)
Testing and CI/CD Integration
Test Configuration
# BUILD.bazel for tests
load("@rules_java//java:defs.bzl", "java_test")
load("//tools:test_macros.bzl", "integration_test_suite")
# Unit tests
java_test(
name = "unit_tests",
srcs = glob(["src/test/java/**/*Test.java"]),
test_class = "com.example.AllTests",
deps = [
"//src/main/java/com/example:lib",
"@maven//:junit_junit",
"@maven//:org_mockito_mockito_core",
"@maven//:org_hamcrest_hamcrest_all",
],
size = "small",
timeout = "short",
jvm_flags = ["-Xmx512m"],
data = [
"//testdata:sample_configs",
],
)
# Integration tests
integration_test_suite(
name = "integration_tests",
srcs = glob(["src/integration/java/**/*IT.java"]),
deps = [
"//src/main/java/com/example:app",
"@maven//:org_testcontainers_testcontainers",
"@maven//:org_testcontainers_junit_jupiter",
],
size = "large",
timeout = "long",
tags = ["integration"],
data = [
"//docker:test_images",
"//config:test_configs",
],
)
# Performance tests
java_test(
name = "performance_tests",
srcs = ["src/perf/java/com/example/PerfTest.java"],
deps = [
"//src/main/java/com/example:lib",
"@maven//:org_openjdk_jmh_jmh_core",
"@maven//:org_openjdk_jmh_jmh_generator_annprocess",
],
size = "large",
timeout = "eternal",
tags = ["performance", "manual"],
jvm_flags = [
"-Xmx2g",
"-XX:+UseG1GC",
],
)
# Test suite
test_suite(
name = "all_tests",
tests = [
":unit_tests",
":integration_tests",
],
tags = ["ci"],
)
.bazelrc Configuration
# .bazelrc - Bazel configuration file
# Common build options
build --show_timestamps
build --announce_rc
build --experimental_repository_cache_hardlinks
build --repository_cache=~/.bazel/repository_cache
build --disk_cache=~/.bazel/disk_cache
# C++ configuration
build --cxxopt=-std=c++17
build --host_cxxopt=-std=c++17
# Java configuration
build --java_language_version=11
build --java_runtime_version=11
build --tool_java_language_version=11
build --tool_java_runtime_version=11
# Test configuration
test --test_output=errors
test --test_verbose_timeout_warnings
test --build_tests_only
# Remote cache configuration (optional)
build:remote --remote_cache=grpc://your-remote-cache:9092
build:remote --remote_timeout=60
# CI configuration
build:ci --curses=no
build:ci --progress_report_interval=10
build:ci --show_progress_rate_limit=5
build:ci --keep_going
build:ci --jobs=50
build:ci --announce_rc
build:ci --experimental_repository_cache_hardlinks
# Debug configuration
build:debug --compilation_mode=dbg
build:debug --copt=-g
build:debug --strip=never
# Optimized release build
build:release --compilation_mode=opt
build:release --copt=-O3
build:release --linkopt=-Wl,--strip-all
# Sanitizer configurations
build:asan --strip=never
build:asan --copt=-fsanitize=address
build:asan --copt=-DADDRESS_SANITIZER
build:asan --copt=-g
build:asan --copt=-fno-omit-frame-pointer
build:asan --linkopt=-fsanitize=address
build:tsan --strip=never
build:tsan --copt=-fsanitize=thread
build:tsan --copt=-DTHREAD_SANITIZER
build:tsan --copt=-g
build:tsan --copt=-fno-omit-frame-pointer
build:tsan --linkopt=-fsanitize=thread
# Coverage configuration
coverage --combined_report=lcov
coverage --coverage_report_generator=@bazel_tools//tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator:Main
# Try to import local configuration
try-import %workspace%/.bazelrc.local
Common Build Commands
# Build all targets
bazel build //...
# Build specific target
bazel build //src/main/java/com/example:hello-world
# Build with specific configuration
bazel build --config=release //src:app
# Run tests
bazel test //...
bazel test //src/test/java/...
bazel test --test_tag_filters=unit //...
# Run specific binary
bazel run //src/main/java/com/example:hello-world
# Clean build artifacts
bazel clean
bazel clean --expunge # Remove all build artifacts
# Query build graph
bazel query "deps(//src:app)"
bazel query "rdeps(//..., //src:lib)"
bazel query "tests(//src/...)"
# Analyze build performance
bazel build --profile=/tmp/profile.json //...
bazel analyze-profile /tmp/profile.json
# Remote execution
bazel build --config=remote //...
# Build with aspects
bazel build --aspects=//tools:analysis.bzl%code_coverage_aspect //src:lib
File Format Details
- MIME Type:
text/plain
- File Extensions:
.bazel
,BUILD
,BUILD.bazel
- Language: Starlark (Python-like syntax)
- Character Encoding: UTF-8
- Build System: Bazel
Bazel provides a powerful and scalable build system that excels in large, multi-language codebases. Its hermetic builds, remote caching, and parallel execution capabilities make it an excellent choice for organizations needing fast, reliable, and reproducible builds across diverse technology stacks.
AI-Powered BAZEL File Analysis
Instant Detection
Quickly identify Bazel build file files with high accuracy using Google's advanced Magika AI technology.
Security Analysis
Analyze file structure and metadata to ensure the file is legitimate and safe to use.
Detailed Information
Get comprehensive details about file type, MIME type, and other technical specifications.
Privacy First
All analysis happens in your browser - no files are uploaded to our servers.
Related File Types
Explore other file types in the Code category and discover more formats:
Start Analyzing BAZEL Files Now
Use our free AI-powered tool to detect and analyze Bazel build file files instantly with Google's Magika technology.
⚡ Try File Detection Tool