Black
Bazel rules for the Python formatter black.
Setup
First ensure rules_venv is setup by referring to rules_venv setup.
Next, the black rules work mostly off of toolchains which are used to provide the necessary python targets (aka black)
for the process wrappers. Users will want to make sure they have a way to get the necessary python dependencies. Tools such as
req-compile can provide these.
With the appropriate dependencies available, a py_black_toolchain will need to be configured:
load("@rules_venv//python/black:defs.bzl", "py_black_toolchain")
py_black_toolchain(
name = "toolchain_impl",
black = "@pip_deps//black",
visibility = ["//visibility:public"]
)
toolchain(
name = "toolchain",
toolchain = ":toolchain_impl",
toolchain_type = "@rules_venv//python/black:toolchain_type",
visibility = ["//visibility:public"]
)
This toolchain then needs to be registered in the MODULE.bazel file.
register_toolchains("//tools/python/black:toolchain")
Usage
Python code can be formatted using the following command:
bazel run @rules_venv//python/black
In addition to this formatter, a check can be added to bazel build invocations using the py_black_aspect
aspect. Simply add the following to a .bazelrc file to enable this check.
build --aspects=@rules_venv//python/black:py_black_aspect.bzl%py_black_aspect
build --output_groups=+py_black_checks
Rules
Aspects
py_black_test
load("@rules_venv//python/black:defs.bzl", "py_black_test")
py_black_test(name, config, target)
A rule for running black on a Python target.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| config | The config file (pyproject.toml) containing black settings. | Label | optional | "@rules_venv//python/black:config" |
| target | The target to run black on. | Label | required |
py_black_toolchain
load("@rules_venv//python/black:defs.bzl", "py_black_toolchain")
py_black_toolchain(name, black)
A toolchain for the black formatter rules.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| black | The black py_library to use with the rules. | Label | required |
py_black_aspect
load("@rules_venv//python/black:defs.bzl", "py_black_aspect")
py_black_aspect()
An aspect for running black on targets with Python sources.
ASPECT ATTRIBUTES
ATTRIBUTES