Run clang-format
on Bazel C++ targets directly. It's like
bazel_clang_tidy but for
clang-format
.
Update your project with
# //:WORKSPACE.bazel
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_repository")
BAZEL_CLANG_FORMAT_COMMIT = ...
http_repository(
name = "bazel_clang_format",
integrity = ...,
strip_prefix = "bazel_clang_format-{commit}".format(
commit = BAZEL_CLANG_FORMAT_COMMIT,
),
url = "https://github.com/oliverlee/bazel_clang_format/archive/{commit}.tar.gz".format(
commit = BAZEL_CLANG_FORMAT_COMMIT,
),
)
# //:.bazelrc
build:clang-format --aspects=@bazel_clang_format//:defs.bzl%check_aspect
build:clang-format --output_groups=report
build:clang-format-fix --aspects=@bazel_clang_format//:defs.bzl%fix_aspect
build:clang-format-fix --output_groups=report
build:clang-format-fix --use_action_cache=false
Check formatting with
bazel build //... --config=clang-format
Fix formatting with
bazel build //... --config=clang-format-fix
This will use clang-format
in your PATH
and .clang-format
defined in this
repo.
To specify a specific binary (e.g. clang-format
is specified by a hermetic
toolchain like this), update the
build setting in .bazelrc
.
# //:.bazelrc
build:clang-format-base --output_groups=report
build:clang-format-base --@bazel_clang_format//:binary=@llvm18//:clang-format
build:clang-format --aspects=@bazel_clang_format//:defs.bzl%check_aspect
build:clang-format-fix --aspects=@bazel_clang_format//:defs.bzl%fix_aspect
build:clang-format-fix --use_action_cache=false
To override the default .clang-format
, define a filegroup
containing the
replacement config and update build setting in .bazelrc
.
# //:BUILD.bazel
load("@bazel_clang_format//:defs.bzl")
filegroup(
name = "clang-format-config",
srcs = [".clang-format"],
visibility = ["//visibility:public"],
)
# //:.bazelrc
build:clang-format-base --output_groups=report
build:clang-format-base --@bazel_clang_format//:config=//:clang-format-config
...
Formatting can be skipped for certain targets by specifying a filegroup
# //:BUILD.bazel
filegroup(
name = "clang-format-ignore",
srcs = [
"//third_party/lib1",
"//third_party/lib2",
],
)
# //:.bazelrc
build:clang-format-base --output_groups=report
build:clang-format-base --@bazel_clang_format//:ignore=//:clang-format-ignore
...
- Bazel 5.x
- ClangFormat 14