@bazel_lib//:bzl_library.bzl
A library rule and macro for grouping Starlark sources.
Drop-in replacement for bzl_library in bazel_skylib, with exceptions:
- We support .bzl and .star extensions, while bzl_library accepts .bzl and .scl.
- Generates starlark_doc_extract
targets, one for each element ofsrcs
, ensuring that the sources list all their dependencies.
Fixes https://github.com/bazelbuild/bazel-skylib/issues/568
Functions & Macros
bzl_library
Wrapper for bzl_library.
Parameters
*name | name |
srcs | List of Default: [] |
deps | List of other Default: [] |
kwargs | additional arguments for the bzl_library rule. |
Rules
bzl_library_rule
Creates a logical collection of Starlark .bzl and .star files.
Attribute | Type | Description |
---|---|---|
*name | name | A unique name for this target. |
srcs | list of labels | Default: [] |
deps | list of labels | Default: [] |
@bazel_lib//lib:base64.bzl
Utility functions for encoding and decoding strings with base64.
Functions & Macros
base64.decode
Decode a base64 encoded string.
Parameters
*data | base64-encoded string |
base64.encode
Base64 encode a string.
Parameters
*data | string to encode |
@bazel_lib//lib:bats.bzl
A test rule that invokes the Bash Automated Testing System.
For example, a bats_test
target containing a single .bat and basic configuration:
bats_test( name = "my_test", size = "small", srcs = [ "my_test.bats", ], data = [ "data.bin", ], env = { "DATA_PATH": "$(location :data.bin)", }, args = ["--timing"], )
Rules
bats_test
Attribute | Type | Description |
---|---|---|
*name | name | A unique name for this target. |
srcs | list of labels | Test files Default: [] |
data | list of labels | Runtime dependencies of the test. Default: [] |
env | dictionary: String → String | Environment variables of the action. Subject to $(location) and "Make variable" substitution. Default: {} |
@bazel_lib//lib:copy_directory.bzl
A rule that copies a directory to another place.
The rule uses a precompiled binary to perform the copy, so no shell is required.
Preserving modification times
copy_directory
and copy_to_directory
have a preserve_mtime
attribute, however
there are two caveats to consider when using this feature:
- Remote Execution / Caching: These layers will reset the modify time and are
incompatible with this feature. To avoid these failures the no-remote tag
can be added. - Caching: Changes to only the modified time will not re-trigger cached actions. This can
be worked around by using a clean build when these types of changes occur. For tests the
external tag can be used but this will result in tests never being cached.
Functions & Macros
copy_directory
Copies a directory to another location.
This rule uses a precompiled binary to perform the copy, so no shell is required.
If using this rule with source directories, it is recommended that you use the
--host_jvm_args=-DBAZEL_TRACK_SOURCE_DIRECTORIES=1
startup option so that changes
to files within source directories are detected. See
https://github.com/bazelbuild/bazel/commit/c64421bc35214f0414e4f4226cc953e8c55fa0d2
for more context.
Parameters
*name | Name of the rule. |
*src | The directory to make a copy of. Can be a source directory or TreeArtifact. |
*out | Path of the output directory, relative to this package. |
hardlink | Controls when to use hardlinks to files instead of making copies. Creating hardlinks is much faster than making copies of files with the caveat that Since Bazel removes write permissions on files in the output tree after an action completes,
Default: "auto" |
kwargs | further keyword arguments, e.g. |
copy_directory_bin_action
Factory function that creates an action to copy a directory from src to dst using a tool binary.
The tool binary will typically be the @bazel_lib//tools/copy_directory
go_binary
either built from source or provided by a toolchain.
This helper is used by the copy_directory rule. It is exposed as a public API so it can be used
within other rule implementations.
Parameters
*ctx | The rule context. |
*src | The source directory to copy. |
*dst | The directory to copy to. Must be a TreeArtifact. |
*copy_directory_bin | Copy to directory tool binary. |
copy_directory_toolchain | The toolchain type for Auto Exec Groups. The default is probably what you want. Default: "@bazel_lib//lib:copy_directory_toolchain_type" |
hardlink | Controls when to use hardlinks to files instead of making copies. See copy_directory rule documentation for more details. Default: "auto" |
verbose | print verbose logs to stdout Default: False |
preserve_mtime | preserve the modified time from the source. Default: False |
@bazel_lib//lib:copy_file.bzl
A rule that copies a file to another place.
native.genrule()
is sometimes used to copy files (often wishing to rename them).
The copy_file
rule does this with a simpler interface than genrule.
This rule uses a hermetic uutils/coreutils cp
binary, no shell is required.
This fork of bazel-skylib's copy_file adds DirectoryPathInfo
support and allows multiple
copy_file
rules in the same package.
Functions & Macros
copy_file
Copies a file or directory to another location.
native.genrule()
is sometimes used to copy files (often wishing to rename them). The 'copy_file' rule does this with a simpler interface than genrule.
This rule uses a hermetic uutils/coreutils cp
binary, no shell is required.
If using this rule with source directories, it is recommended that you use the
--host_jvm_args=-DBAZEL_TRACK_SOURCE_DIRECTORIES=1
startup option so that changes
to files within source directories are detected. See
https://github.com/bazelbuild/bazel/commit/c64421bc35214f0414e4f4226cc953e8c55fa0d2
for more context.
Parameters
*name | Name of the rule. |
*src | A Label. The file to make a copy of. |
*out | Path of the output file, relative to this package. |
is_executable | A boolean. Whether to make the output file executable. When Default: False |
allow_symlink | A boolean. Whether to allow symlinking instead of copying. Default: False |
kwargs | further keyword arguments, e.g. |
copy_file_action
Factory function that creates an action to copy a file from src to dst.
If src is a TreeArtifact, dir_path must be specified as the path within
the TreeArtifact to the file to copy.
This helper is used by copy_file. It is exposed as a public API so it can be used within
other rule implementations.
To use copy_file_action
in your own rules, you need to include the toolchains it uses
in your rule definition. For example:
load("@bazel_lib//lib:copy_file.bzl", "COPY_FILE_TOOLCHAINS") my_rule = rule( ..., toolchains = COPY_FILE_TOOLCHAINS, )
Additionally, you must ensure that the coreutils toolchain is has been registered in your
WORKSPACE if you are not using bzlmod:
load("@bazel_lib//lib:repositories.bzl", "register_coreutils_toolchains") register_coreutils_toolchains()
Parameters
*ctx | The rule context. |
*src | The source file to copy or TreeArtifact to copy a single file out of. |
*dst | The destination file. |
dir_path | If src is a TreeArtifact, the path within the TreeArtifact to the file to copy. Default: None |
@bazel_lib//lib:copy_to_bin.bzl
A rule that copies source files to the output tree.
This rule uses a Bash command (diff) on Linux/macOS/non-Windows, and a cmd.exe
command (fc.exe) on Windows (no Bash is required).
Originally authored in rules_nodejs
https://github.com/bazel-contrib/rules_nodejs/blob/8b5d27400db51e7027fe95ae413eeabea4856f8e/internal/common/copy_to_bin.bzl
Functions & Macros
copy_file_to_bin_action
Factory function that creates an action to copy a file to the output tree.
File are copied to the same workspace-relative path. The resulting files is
returned.
If the file passed in is already in the output tree is then it is returned
without a copy action.
To use copy_file_to_bin_action
in your own rules, you need to include the toolchains it uses
in your rule definition. For example:
load("@bazel_lib//lib:copy_to_bin.bzl", "COPY_FILE_TO_BIN_TOOLCHAINS") my_rule = rule( ..., toolchains = COPY_FILE_TO_BIN_TOOLCHAINS, )
Additionally, you must ensure that the coreutils toolchain is has been registered in your
WORKSPACE if you are not using bzlmod:
load("@bazel_lib//lib:repositories.bzl", "register_coreutils_toolchains") register_coreutils_toolchains()
Parameters
*ctx | The rule context. |
*file | The file to copy. |
copy_files_to_bin_actions
Factory function that creates actions to copy files to the output tree.
Files are copied to the same workspace-relative path. The resulting list of
files is returned.
If a file passed in is already in the output tree is then it is added
directly to the result without a copy action.
Parameters
*ctx | The rule context. |
*files | List of File objects. |
copy_to_bin
Copies a source file to output tree at the same workspace-relative path.
e.g. <execroot>/path/to/file -> <execroot>/bazel-out/<platform>/bin/path/to/file
If a file passed in is already in the output tree is then it is added directly to the
DefaultInfo provided by the rule without a copy.
This is useful to populate the output folder with all files needed at runtime, even
those which aren't outputs of a Bazel rule.
This way you can run a binary in the output folder (execroot or runfiles_root)
without that program needing to rely on a runfiles helper library or be aware that
files are divided between the source tree and the output tree.
Parameters
*name | Name of the rule. |
*srcs | A list of labels. File(s) to copy. |
kwargs | further keyword arguments, e.g. |
@bazel_lib//lib:copy_to_directory.bzl
Copy files and directories to an output directory.
Functions & Macros
copy_to_directory_lib.impl
Parameters
*ctx |
copy_to_directory_bin_action
Factory function to copy files to a directory using a tool binary.
The tool binary will typically be the @bazel_lib//tools/copy_to_directory
go_binary
either built from source or provided by a toolchain.
This helper is used by copy_to_directory. It is exposed as a public API so it can be used within
other rule implementations where additional_files can also be passed in.
Parameters
*ctx | The rule context. |
*name | Name of target creating this action used for config file generation. |
*dst | The directory to copy to. Must be a TreeArtifact. |
*copy_to_directory_bin | Copy to directory tool binary. |
copy_to_directory_toolchain | The toolchain type for Auto Exec Groups. The default is probably what you want. Default: "@bazel_lib//lib:copy_to_directory_toolchain_type" |
files | List of files to copy into the output directory. Default: [] |
targets | List of targets that provide Default: [] |
root_paths | List of paths that are roots in the output directory. See copy_to_directory rule documentation for more details. Default: ["."] |
include_external_repositories | List of external repository names to include in the output directory. See copy_to_directory rule documentation for more details. Default: [] |
include_srcs_packages | List of Bazel packages to include in output directory. See copy_to_directory rule documentation for more details. Default: ["**"] |
exclude_srcs_packages | List of Bazel packages (with glob support) to exclude from output directory. See copy_to_directory rule documentation for more details. Default: [] |
include_srcs_patterns | List of paths (with glob support) to include in output directory. See copy_to_directory rule documentation for more details. Default: ["**"] |
exclude_srcs_patterns | List of paths (with glob support) to exclude from output directory. See copy_to_directory rule documentation for more details. Default: [] |
replace_prefixes | Map of paths prefixes to replace in the output directory path when copying files. See copy_to_directory rule documentation for more details. Default: {} |
allow_overwrites | If True, allow files to be overwritten if the same output file is copied to twice. See copy_to_directory rule documentation for more details. Default: False |
hardlink | Controls when to use hardlinks to files instead of making copies. See copy_to_directory rule documentation for more details. Default: "auto" |
preserve_mtime | If true, preserve the modified time from the source. Default: False |
verbose | If true, prints out verbose logs to stdout Default: False |
Rules
copy_to_directory
Copies files and directories to an output directory.
Files and directories can be arranged as needed in the output directory using
the root_paths
, include_srcs_patterns
, exclude_srcs_patterns
and replace_prefixes
attributes.
Filters and transformations are applied in the following order:
-
include_external_repositories
-
include_srcs_packages
-
exclude_srcs_packages
-
root_paths
-
include_srcs_patterns
-
exclude_srcs_patterns
-
replace_prefixes
For more information each filters / transformations applied, see
the documentation for the specific filter / transformation attribute.
Glob patterns are supported. Standard wildcards (globbing patterns) plus the **
doublestar (aka. super-asterisk)
are supported with the underlying globbing library, https://github.com/bmatcuk/doublestar. This is the same
globbing library used by gazelle. See https://github.com/bmatcuk/doublestar#patterns
for more information on supported globbing patterns.
Attribute | Type | Description |
---|---|---|
*name | name | A unique name for this target. |
srcs | list of labels | Files and/or directories or targets that provide Default: [] |
out | string | Path of the output directory, relative to this package. If not set, the name of the target is used. Default: "" |
add_directory_to_runfiles | boolean | Whether to add the outputted directory to the target's runfiles. Default: True |
root_paths | list of strings | List of paths (with glob support) that are roots in the output directory. If any parent directory of a file being copied matches one of the root paths Matching is done on the parent directory of the output file path so a trailing '**' glob patterm Forward slashes ( A Defaults to Globs are supported (see rule docstring above). Default: ["."] |
include_external_repositories | list of strings | List of external repository names (with glob support) to include in the output directory. Files from external repositories are only copied into the output directory if When copied from an external repository, the file path in the output directory For example, the following copies
Files that come from matching external are subject to subsequent filters and Globs are supported (see rule docstring above). Default: [] |
include_srcs_packages | list of strings | List of Bazel packages (with glob support) to include in output directory. Files in srcs are only copied to the output directory if Forward slashes ( Defaults to Files that have matching Bazel packages are subject to subsequent filters and Globs are supported (see rule docstring above). Default: ["**"] |
exclude_srcs_packages | list of strings | List of Bazel packages (with glob support) to exclude from output directory. Files in srcs are not copied to the output directory if Forward slashes ( Files that have do not have matching Bazel packages are subject to subsequent Globs are supported (see rule docstring above). Default: [] |
include_srcs_patterns | list of strings | List of paths (with glob support) to include in output directory. Files in srcs are only copied to the output directory if their output Forward slashes ( Defaults to Files that have matching output directory paths are subject to subsequent Globs are supported (see rule docstring above). Default: ["**"] |
exclude_srcs_patterns | list of strings | List of paths (with glob support) to exclude from output directory. Files in srcs are not copied to the output directory if their output Forward slashes ( Files that do not have matching output directory paths are subject to subsequent Globs are supported (see rule docstring above). Default: [] |
replace_prefixes | dictionary: String → String | Map of paths prefixes (with glob support) to replace in the output directory path when copying files. If the output directory path for a file starts with or fully matches a Forward slashes ( Replace prefix transformation are the final step in the list of filters and transformations. Globs are supported (see rule docstring above). Default: {} |
allow_overwrites | boolean | If True, allow files to be overwritten if the same output file is copied to twice. The order of srcs matters as the last copy of a particular file will win when overwriting. Default: False |
hardlink | string | Controls when to use hardlinks to files instead of making copies. Creating hardlinks is much faster than making copies of files with the caveat that Since Bazel removes write permissions on files in the output tree after an action completes,
Default: "auto" |
preserve_mtime | boolean | If True, the last modified time of copied files is preserved. Default: False |
verbose | boolean | If true, prints out verbose logs to stdout Default: False |
@bazel_lib//lib:diff_test.bzl
A test rule that compares two binary files or two directories.
Similar to bazel-skylib
's diff_test
but also supports comparing directories.
The rule uses a Bash command (diff) on Linux/macOS/non-Windows, and a cmd.exe
command (fc.exe) on Windows (no Bash is required).
See also: rules_diff
Functions & Macros
diff_test
A test that compares two files.
The test succeeds if the files' contents match.
Parameters
*name | The name of the test rule. |
*file1 | Label of the file to compare to <code>file2</code>. |
*file2 | Label of the file to compare to <code>file1</code>, or a list of strings which are the lines to expect <code>file1</code> to contain. |
diff_args | Arguments to pass to the Default: [] |
size | standard attribute for tests Default: "small" |
kwargs | The <a href="https://docs.bazel.build/versions/main/be/common-definitions.html#common-attributes-tests">common attributes for tests</a>. |
@bazel_lib//lib:directory_path.bzl
Rule and corresponding provider that joins a label pointing to a TreeArtifact
with a path nested within that directory
Functions & Macros
make_directory_path
Helper function to generate a directory_path target and return its label.
Parameters
*name | unique name for the generated |
*directory |
|
*path |
|
kwargs | parameters to pass to generated |
make_directory_paths
Helper function to convert a dict of directory to path mappings to directory_path targets and labels.
For example,
make_directory_paths("my_name", {
"//directory/artifact:target_1": "file/path",
"//directory/artifact:target_2": ["file/path1", "file/path2"],
})
generates the targets,
directory_path(
name = "my_name_0",
directory = "//directory/artifact:target_1",
path = "file/path"
)
directory_path(
name = "my_name_1",
directory = "//directory/artifact:target_2",
path = "file/path1"
)
directory_path(
name = "my_name_2",
directory = "//directory/artifact:target_2",
path = "file/path2"
)
and the list of targets is returned,
[
"my_name_0",
"my_name_1",
"my_name_2",
]
Parameters
*name | The target name to use for the generated targets & labels. The names are generated as zero-indexed |
*dict | The dictionary of directory keys to path or path list values. |
kwargs | additional parameters to pass to each generated target |
Rules
directory_path
Provide DirectoryPathInfo to reference some path within a directory.
Otherwise there is no way to give a Bazel label for it.
Providers
DirectoryPathInfo
Joins a label pointing to a TreeArtifact with a path nested within that directory.
Fields
directory | a TreeArtifact (ctx.actions.declare_directory) |
path | path relative to the directory |
@bazel_lib//lib:expand_make_vars.bzl
Public API for expanding variables
Functions & Macros
expand_locations
Expand location templates.
Expands all $(execpath ...)
, $(rootpath ...)
and deprecated $(location ...)
templates in the
given string by replacing with the expanded path. Expansion only works for labels that point to direct dependencies
of this rule or that are explicitly listed in the optional argument targets.
See https://docs.bazel.build/versions/main/be/make-variables.html#predefined_label_variables.
Use $(rootpath)
and $(rootpaths)
to expand labels to the runfiles path that a built binary can use
to find its dependencies. This path is of the format:
./file
path/to/file
../external_repo/path/to/file
Use $(execpath)
and $(execpaths)
to expand labels to the execroot (where Bazel runs build actions).
This is of the format:
./file
path/to/file
external/external_repo/path/to/file
<bin_dir>/path/to/file
<bin_dir>/external/external_repo/path/to/file
The deprecated $(location)
and $(locations)
expansions returns either the execpath or rootpath depending on the context.
Parameters
*ctx | context |
*input | String to be expanded |
targets | List of targets for additional lookup information. Default: [] |
expand_variables
Expand make variables and substitute like genrule does.
Bazel pre-defined variables
are expanded however only $@
, $(@D)
and $(RULEDIR)
of
pre-defined genrule variables
are supported.
This function is the same as ctx.expand_make_variables with the additional
genrule-like substitutions of:
-
$<
: The input file if it is a single file. Else triggers a build error. -
$@
: The output file if it is a single file. Else triggers a build error. -
$(@D)
: The output directory.If there is only one file name in outs, this expands to the directory containing that file.
If there is only one directory in outs, this expands to the single output directory.
If there are multiple files, this instead expands to the package's root directory in the bin tree,
even if all generated files belong to the same subdirectory! -
$(RULEDIR)
: The output directory of the rule, that is, the directory
corresponding to the name of the package containing the rule under the bin tree. -
$(BUILD_FILE_PATH)
: ctx.build_file_path -
$(VERSION_FILE)
: ctx.version_file.path -
$(INFO_FILE)
: ctx.info_file.path -
$(TARGET)
: ctx.label -
$(WORKSPACE)
: ctx.workspace_name
See https://docs.bazel.build/versions/main/be/general.html#genrule.cmd and
https://docs.bazel.build/versions/main/be/make-variables.html#predefined_genrule_variables
for more information of how these special variables are expanded.
Parameters
*ctx | starlark rule context |
*s | expression to expand |
outs | declared outputs of the rule, for expanding references to outputs Default: [] |
inputs | declared inputs of the rule, for expanding references to inputs Default: [] |
attribute_name | name of the attribute containing the expression. Used for error reporting. Default: "args" |
@bazel_lib//lib:expand_template.bzl
Public API for expand template
Functions & Macros
expand_template
Wrapper macro for expand_template_rule
.
Parameters
*name | name of resulting rule |
*template | the label of a template file, or a list of strings |
kwargs | other named parameters to |
Rules
expand_template_rule
Template expansion
This performs a simple search over the template file for the keys in substitutions,
and replaces them with the corresponding values.
Values may also use location templates as documented in
expand_locations
as well as configuration variables
such as $(BINDIR)
, $(TARGET_CPU)
, and $(COMPILATION_MODE)
as documented in
expand_variables.
Attribute | Type | Description |
---|---|---|
*name | name | A unique name for this target. |
data | list of labels | List of targets for additional lookup information. Default: [] |
is_executable | boolean | Whether to mark the output file as executable. Default: False |
out | label | Where to write the expanded file. If the Otherwise, Default: None |
stamp_substitutions | dictionary: String → String | Mapping of strings to substitutions. There are overlaid on top of substitutions when stamping is enabled Substitutions can contain $(execpath :target) and $(rootpath :target) Default: {} |
substitutions | dictionary: String → String | Mapping of strings to substitutions. Substitutions can contain $(execpath :target) and $(rootpath :target) Default: {} |
*template | label | The template file to expand. |
stamp | integer | Whether to encode build information into the output. Possible values:
Default: -1 |
@bazel_lib//lib:extensions.bzl
Module extensions for use with bzlmod
Module Extensions
host
Tag Classes
host
toolchains
Tag Classes
copy_directory
Attribute | Type | Description |
---|---|---|
name | name | Default: "copy_directory" |
copy_to_directory
Attribute | Type | Description |
---|---|---|
name | name | Default: "copy_to_directory" |
coreutils
Attribute | Type | Description |
---|---|---|
name | name | Default: "coreutils" |
version | string | Default: "0.1.0" |
zstd
Attribute | Type | Description |
---|---|---|
name | name | Default: "zstd" |
expand_template
Attribute | Type | Description |
---|---|---|
name | name | Default: "expand_template" |
bats
Attribute | Type | Description |
---|---|---|
name | name | Default: "bats" |
core_version | string | Default: "v1.10.0" |
@bazel_lib//lib:glob_match.bzl
Public API
Functions & Macros
glob_match
Test if the passed path matches the glob expression.
*
A single asterisk stands for zero or more arbitrary characters except for the the path separator /
if match_path_separator
is False
?
The question mark stands for exactly one character except for the the path separator /
if match_path_separator
is False
**
A double asterisk stands for an arbitrary sequence of 0 or more characters. It is only allowed when preceded by either the beginning of the string or a slash. Likewise it must be followed by a slash or the end of the pattern.
Parameters
*expr | the glob expression |
*path | the path against which to match the glob expression |
match_path_separator | whether or not to match the path separator '/' when matching Default: False |
is_glob
Determine if the passed string is a global expression
Parameters
*expr | the potential glob expression |
@bazel_lib//lib:host_repo.bzl
Public API
Repository Rules
host_repo
Exposes information about the host platform
Attribute | Type | Description |
---|---|---|
*name | name | A unique name for this repository. |
repo_mapping | dictionary: String → String | In For example, an entry This attribute is not supported in |
@bazel_lib//lib:lists.bzl
Functions for lists
Functions & Macros
every
Check if every item of arr
passes function f
.
Example:
every(lambda i: i.endswith(".js"), ["app.js", "lib.js"]) // True
Parameters
*f | Function to execute on every item |
*arr | List to iterate over |
filter
Filter a list arr
by applying a function f
to each item.
Example:
filter(lambda i: i.endswith(".js"), ["app.ts", "app.js", "lib.ts", "lib.js"]) // ["app.js", "lib.js"]
Parameters
*f | Function to execute on every item |
*arr | List to iterate over |
find
Find a particular item from list arr
by a given function f
.
Unlike pick
, the find
method returns a tuple of the index and the value of first item passing by f
.
Furthermore find
does not fail if no item passes f
.
In this case (-1, None)
is returned.
Parameters
*f | Function to execute on every item |
*arr | List to iterate over |
map
Apply a function f
with each item of arr
and return a new list.
Example:
map(lambda i: i*2, [1, 2, 3]) // [2, 4, 6]
Parameters
*f | Function to execute on every item |
*arr | List to iterate over |
once
Check if exactly one item in list arr
passes the given function f
.
Parameters
*f | Function to execute on every item |
*arr | List to iterate over |
pick
Pick a particular item in list arr
by a given function f
.
Unlike filter
, the pick
method returns the first item found by f
.
If no item has passed f
, the function will fail.
Parameters
*f | Function to execute on every item |
*arr | List to iterate over |
some
Check if at least one item of arr
passes function f
.
Example:
some(lambda i: i.endswith(".js"), ["app.js", "lib.ts"]) // True
Parameters
*f | Function to execute on every item |
*arr | List to iterate over |
unique
Return a new list with unique items in it.
Example:
unique(["foo", "bar", "foo", "baz"]) // ["foo", "bar", "baz"]
Parameters
*arr | List to iterate over |
@bazel_lib//lib:output_files.bzl
A rule that provides file(s) specific via DefaultInfo from a given target's DefaultInfo or OutputGroupInfo.
See also select_file from bazel-skylib.
Functions & Macros
make_output_files
Helper function to generate a output_files target and return its label.
Parameters
*name | unique name for the generated |
*target |
|
*paths |
|
kwargs | parameters to pass to generated |
Rules
output_files
A rule that provides file(s) specific via DefaultInfo from a given target's DefaultInfo or OutputGroupInfo
Attribute | Type | Description |
---|---|---|
*name | name | A unique name for this target. |
*target | label | the target to look in for requested paths in its' DefaultInfo or OutputGroupInfo |
*paths | list of strings | the paths of the file(s), relative to their roots, to provide via DefaultInfo from the given target's DefaultInfo or OutputGroupInfo |
output_group | string | if set, we look in the specified output group for paths instead of DefaultInfo Default: "" |
@bazel_lib//lib:params_file.bzl
params_file public API
Functions & Macros
params_file
Generates a UTF-8 encoded params file from a list of arguments.
Handles variable substitutions for args.
Parameters
*name | Name of the rule. |
*out | Path of the output file, relative to this package. |
args | Arguments to concatenate into a params file.
Default: [] |
data | Data for Default: [] |
newline | Line endings to use. One of [
Default: "auto" |
kwargs | undocumented named arguments |
@bazel_lib//lib:paths.bzl
Utilities for working with file paths.
Functions & Macros
relative_file
Resolves a relative path between two files, "to_file" and "frm_file".
If neither of the paths begin with ../ it is assumed that they share the same root. When finding the relative path,
the incoming files are treated as actual files (not folders) so the resulting relative path may differ when compared
to passing the same arguments to python's "os.path.relpath()" or NodeJs's "path.relative()".
For example, 'relative_file("../foo/foo.txt", "bar/bar.txt")' will return '../../foo/foo.txt'
Parameters
*to_file | the path with file name to resolve to, from frm |
*frm_file | the path with file name to resolve from |
to_output_relative_path
The relative path from bazel-out/[arch]/bin to the given File object
Parameters
*file | a |
to_repository_relative_path
The repository relative path for a File
This is the full runfiles path of a File
excluding its workspace name.
This differs from root path (a.k.a. short_path) and
rlocation path as it does not include the repository name if the File
is from an external repository.
Parameters
*file | a |
to_rlocation_path
The rlocation path for a File
This produces the same value as the rlocationpath
predefined source/output path variable.
From https://bazel.build/reference/be/make-variables#predefined_genrule_variables:
rlocationpath
: The path a built binary can pass to theRlocation
function of a runfiles
library to find a dependency at runtime, either in the runfiles directory (if available)
or using the runfiles manifest.
This is similar to root path (a.k.a. short_path)
in that it does not contain configuration prefixes, but differs in that it always starts with the
name of the repository.
The rlocation path of a
File
in an external repository repo will start withrepo/
, followed by the
repository-relative path.
Passing this path to a binary and resolving it to a file system path using the runfiles libraries
is the preferred approach to find dependencies at runtime. Compared to root path, it has the
advantage that it works on all platforms and even if the runfiles directory is not available.
Parameters
*ctx | starlark rule execution context |
*file | a |
@bazel_lib//lib:platform_utils.bzl
Public API
Functions & Macros
platform_utils.host_platform_is_darwin
platform_utils.host_platform_is_linux
platform_utils.host_platform_is_windows
@bazel_lib//lib:repo_utils.bzl
Public API
Functions & Macros
repo_utils.get_env_var
Find an environment variable in system. Doesn't %-escape the value!
Parameters
*rctx | rctx |
*name | environment variable name |
*default | default value to return if env var is not set in system |
repo_utils.get_home_directory
Parameters
*rctx |
repo_utils.is_darwin
Returns true if the host operating system is Darwin
Parameters
*rctx |
repo_utils.is_linux
Returns true if the host operating system is Linux
Parameters
*rctx |
repo_utils.is_windows
Returns true if the host operating system is Windows
Parameters
*rctx |
repo_utils.os
Returns the name of the host operating system
Parameters
*rctx | rctx |
repo_utils.platform
Returns a normalized name of the host os and CPU architecture.
Alias archictures names are normalized:
x86_64 => amd64
aarch64 => arm64
The result can be used to generate repository names for host toolchain
repositories for toolchains that use these normalized names.
Common os & architecture pairs that are returned are,
- darwin_amd64
- darwin_arm64
- linux_amd64
- linux_arm64
- linux_s390x
- linux_ppc64le
- windows_amd64
Parameters
*rctx | rctx |
patch
Implementation of patching an already extracted repository.
This rule is intended to be used in the implementation function of
a repository rule. If the parameters patches
, patch_tool
,
patch_args
, patch_cmds
and patch_cmds_win
are not specified
then they are taken from ctx.attr
.
Parameters
*ctx | The repository context of the repository rule calling this utility |
patches | The patch files to apply. List of strings, Labels, or paths. Default: None |
patch_cmds | Bash commands to run for patching, passed one at a Default: None |
patch_cmds_win | Powershell commands to run for patching, passed Default: None |
patch_tool | Path of the patch tool to execute for applying Default: None |
patch_args | Arguments to pass to the patch tool. List of strings. Default: None |
auth | An optional dict specifying authentication information for some of the URLs. Default: None |
patch_directory | Directory to apply the patches in Default: None |
@bazel_lib//lib:repositories.bzl
Macros for loading dependencies and registering toolchains
Functions & Macros
bazel_lib_dependencies
Load dependencies
register_zstd_toolchains
Registers zstd toolchain and repositories
Parameters
name | override the prefix for the generated toolchain repositories Default: "zstd" |
register | whether to call through to native.register_toolchains. Default: True |
register_bats_toolchains
Registers bats toolchain and repositories
Parameters
name | override the prefix for the generated toolchain repositories Default: "bats" |
core_version | bats-core version to use Default: "v1.10.0" |
support_version | bats-support version to use Default: "v0.3.0" |
assert_version | bats-assert version to use Default: "v2.1.0" |
file_version | bats-file version to use Default: "v0.4.0" |
libraries | additional labels for libraries Default: [] |
register | whether to call through to native.register_toolchains. Default: True |
register_coreutils_toolchains
Registers coreutils toolchain and repositories
Parameters
name | override the prefix for the generated toolchain repositories Default: "coreutils" |
version | the version of coreutils to execute (see https://github.com/uutils/coreutils/releases) Default: "0.1.0" |
register | whether to call through to native.register_toolchains. Default: True |
register_copy_directory_toolchains
Registers copy_directory toolchain and repositories
Parameters
name | override the prefix for the generated toolchain repositories Default: "copy_directory" |
register | whether to call through to native.register_toolchains. Default: True |
register_copy_to_directory_toolchains
Registers copy_to_directory toolchain and repositories
Parameters
name | override the prefix for the generated toolchain repositories Default: "copy_to_directory" |
register | whether to call through to native.register_toolchains. Default: True |
register_expand_template_toolchains
Registers expand_template toolchain and repositories
Parameters
name | override the prefix for the generated toolchain repositories Default: "expand_template" |
register | whether to call through to native.register_toolchains. Default: True |
bazel_lib_register_toolchains
Register all bazel-lib toolchains at their default versions.
To be more selective about which toolchains and versions to register,
call the individual toolchain registration macros.
@bazel_lib//lib:resource_sets.bzl
Utilities for rules that expose resource_set on ctx.actions.run[_shell]
Workaround for https://github.com/bazelbuild/bazel/issues/15187
Note, this workaround only provides some fixed values for either CPU or Memory.
Rule authors who are ALSO the BUILD author might know better, and can
write custom resource_set functions for use within their own repository.
This seems to be the use case that Google engineers imagined.
Functions & Macros
resource_set
Parameters
*attr |
@bazel_lib//lib:run_binary.bzl
Runs a binary as a build action. This rule does not require Bash (unlike native.genrule()).
This fork of bazel-skylib's run_binary adds directory output support and better makevar expansions.
Functions & Macros
run_binary
Runs a binary as a build action.
This rule does not require Bash (unlike native.genrule
).
Parameters
*name | The target name |
*tool | The tool to run in the action. Must be the label of a *_binary rule of a rule that generates an executable file, or of |
srcs | Additional inputs of the action. These labels are available for Default: [] |
args | Command line arguments of the binary. Subject to Default: [] |
env | Environment variables of the action. Subject to Default: {} |
outs | Output files generated by the action. These labels are available for Output files cannot be nested within output directories in out_dirs. Default: [] |
out_dirs | Output directories generated by the action. These labels are not available for Output directories cannot be nested within other output directories in out_dirs. Default: [] |
mnemonic | A one-word description of the action, for example, CppCompile or GoLink. Default: "RunBinary" |
progress_message | Progress message to show to the user during the build, for example, Default: None |
execution_requirements | Information for scheduling the action. For example,
See https://docs.bazel.build/versions/main/be/common-definitions.html#common.tags for useful keys. Default: None |
use_default_shell_env | Passed to the underlying ctx.actions.run. May introduce non-determinism when True; use with care! Refer to https://bazel.build/rules/lib/builtins/actions#run for more details. Default: False |
stamp | Whether to include build status files as inputs to the tool. Possible values:
When stamping is enabled, an additional two environment variables will be set for the action: These files can be read and parsed by the action, for example to pass some values to a linker. Default: 0 |
kwargs | Additional arguments |
@bazel_lib//lib:stamping.bzl
Version Stamping
Bazel is generally only a build tool, and is unaware of your version control system.
However, when publishing releases, you may want to embed version information in the resulting distribution.
Bazel supports this with the concept of a "Workspace status" which is evaluated before each build.
See the Bazel workspace status docs
To stamp a build, you pass the --stamp
argument to Bazel.
Note: https://github.com/bazelbuild/bazel/issues/14341 proposes that Bazel enforce this by
only giving constant values to rule implementations when stamping isn't enabled.
Stamping is typically performed on a later action in the graph, like on a linking or packaging rule (pkg_*
).
This means that a changed status variable only causes that action, not re-compilation and thus does not cause cascading re-builds.
Bazel provides a couple of statuses by default, such as BUILD_EMBED_LABEL
which is the value of the --embed_label
argument, as well as BUILD_HOST
, BUILD_TIMESTAMP
, and BUILD_USER
.
You can supply more with the workspace status script, see below.
Some rules accept an attribute that uses the status variables.
They will usually say something like "subject to stamp variable replacements".
Stamping with a Workspace status script
To define additional statuses, pass the --workspace_status_command
flag to bazel
.
This slows down every build, so you should avoid passing this flag unless you need to stamp this build.
The value of this flag is a path to a script that prints space-separated key/value pairs, one per line, such as
#!/usr/bin/env bash echo STABLE_GIT_COMMIT $(git rev-parse HEAD)
For a more full-featured script, take a look at this example in Angular
Make sure you set the executable bit, eg. chmod +x tools/bazel_stamp_vars.sh
.
NOTE keys that start with
STABLE_
will cause a re-build when they change.
Other keys will NOT cause a re-build, so stale values can appear in your app.
Non-stable (volatile) keys should typically be things like timestamps that always vary between builds.
You might like to encode your setup using an entry in .bazelrc
such as:
# This tells Bazel how to interact with the version control system # Enable this with --config=release build:release --stamp --workspace_status_command=./tools/bazel_stamp_vars.sh
Writing a custom rule which reads stamp variables
First, load the helpers:
load("@bazel_lib//lib:stamping.bzl", "STAMP_ATTRS", "maybe_stamp")
In your rule implementation, call the maybe_stamp
function.
If it returns None
then this build doesn't have stamping enabled.
Otherwise you can use the returned struct to access two files.
- The
stable_status
file contains the keys which were prefixed withSTABLE_
, see above. - The
volatile_status
file contains the rest of the keys.
def _rule_impl(ctx): args = ctx.actions.args() inputs = [] stamp = maybe_stamp(ctx) if stamp: args.add("--volatile_status_file", stamp.volatile_status_file.path) args.add("--stable_status_file", stamp.stable_status_file.path) inputs.extend([stamp.volatile_status_file, stamp.stable_status_file]) # ... call actions which parse the stamp files and do something with the values ...
Finally, in the declaration of the rule, include the STAMP_ATTRS
to declare attributes
which are read by that maybe_stamp
function above.
my_stamp_aware_rule = rule( attrs = dict({ # ... my attributes ... }, **STAMP_ATTRS), )
Functions & Macros
maybe_stamp
Provide the bazel-out/stable_status.txt and bazel-out/volatile_status.txt files.
Parameters
*ctx | The rule context |
@bazel_lib//lib:strings.bzl
Utilities for strings
Functions & Macros
chr
returns a string encoding a codepoint
chr returns a string that encodes the single Unicode code
point whose value is specified by the integer i
Parameters
*i | position of the character |
ord
returns the codepoint of a character
ord(c) returns the integer value of the sole Unicode code point
encoded by the string c
.
If c
does not encode exactly one Unicode code point, ord
fails.
Each invalid code within the string is treated as if it encodes the
Unicode replacement character, U+FFFD.
Parameters
*c | character whose codepoint to be returned. |
hex
Format integer to hexadecimal representation
Parameters
*number | number to format |
split_args
Split a string into a list space separated arguments
Unlike the naive .split(" ")
, this function takes quoted strings
and escapes into account.
Parameters
*s | input string |
@bazel_lib//lib:testing.bzl
Helpers for making test assertions
Functions & Macros
assert_contains
Generates a test target which fails if the file doesn't contain the string.
Depends on bash, as it creates an sh_test target.
Parameters
*name | target to create |
*actual | Label of a file |
*expected | a string which should appear in the file |
size | standard attribute for tests Default: "small" |
kwargs | additional named arguments for the resulting sh_test |
assert_outputs
Assert that the default outputs of a target are the expected ones.
Parameters
*name | name of the resulting diff_test |
*actual | string of the label to check the outputs |
*expected | a list of rootpaths of expected outputs, as they would appear in a runfiles manifest |
kwargs | additional named arguments for the resulting diff_test |
assert_archive_contains
Assert that an archive file contains at least the given file entries.
Parameters
*name | name of the resulting sh_test target |
*archive | Label of the the .tar or .zip file |
*expected | a (partial) file listing, either as a Label of a file containing it, or a list of strings |
type | "tar" or "zip". If None, a type will be inferred from the filename. Default: None |
kwargs | additional named arguments for the resulting sh_test |
assert_directory_contains
Assert that a directory contains at least the given file entries.
Parameters
*name | name of the resulting sh_test target |
*directory | Label of the directory artifact |
*expected | a (partial) file listing, either as a Label of a file containing it, or a list of strings |
kwargs | additional named arguments for the resulting sh_test |
@bazel_lib//lib:transitions.bzl
Rules for working with transitions.
Rules
platform_transition_filegroup
Transitions the srcs to use the provided platform. The filegroup will contain artifacts for the target platform.
Attribute | Type | Description |
---|---|---|
*name | name | A unique name for this target. |
*target_platform | label | The target platform to transition the srcs. |
srcs | list of labels | The input to be transitioned to the target platform. Default: [] |
platform_transition_binary
Transitions the binary to use the provided platform. Will forward RunEnvironmentInfo
@bazel_lib//lib:utils.bzl
General-purpose Starlark utility functions
Usage example
load("@bazel_lib//lib:utils.bzl", "utils") out_label = utils.to_label(out_file)
Functions & Macros
utils.consistent_label_str
Generate a consistent label string for all Bazel versions.
Starting in Bazel 6, the workspace name is empty for the local workspace and there's no other
way to determine it. This behavior differs from Bazel 5 where the local workspace name was fully
qualified in str(label).
This utility function is meant for use in rules and requires the rule context to determine the
user's workspace name (ctx.workspace_name
).
Parameters
*ctx | The rule context. |
*label | A Label. |
utils.default_timeout
Provide a sane default for *_test timeout attribute.
The test-encyclopedia says:
Tests may return arbitrarily fast regardless of timeout.
A test is not penalized for an overgenerous timeout, although a warning may be issued:
you should generally set your timeout as tight as you can without incurring any flakiness.
However Bazel's default for timeout is medium, which is dumb given this guidance.
It also says:
Tests which do not explicitly specify a timeout have one implied based on the test's size as follows
Therefore if size is specified, we should allow timeout to take its implied default.
If neither is set, then we can fix Bazel's wrong default here to avoid warnings under
--test_verbose_timeout_warnings
.
This function can be used in a macro which wraps a testing rule.
Parameters
*size | the size attribute of a test target |
*timeout | the timeout attribute of a test target |
utils.file_exists
Check whether a file exists.
Useful in macros to set defaults for a configuration file if it is present.
This can only be called during the loading phase, not from a rule implementation.
Parameters
*path | a label, or a string which is a path relative to this package |
utils.glob_directories
Parameters
*include | |
kwargs |
utils.is_bazel_6_or_greater
Detects if the Bazel version being used is greater than or equal to 6 (including Bazel 6 pre-releases and RCs).
Detecting Bazel 6 or greater is particularly useful in rules as slightly different code paths may be needed to
support bzlmod which was added in Bazel 6.
Unlike the undocumented native.bazel_version
, which only works in WORKSPACE and repository rules, this function can
be used in rules and BUILD files.
An alternate approach to make the Bazel version available in BUILD files and rules would be to
use the host_repo repository rule
which contains the bazel_version in the exported host
struct:
WORKSPACE:
load("@bazel_lib//lib:host_repo.bzl", "host_repo")
host_repo(name = "bazel_lib_host")
BUILD.bazel:
load("@bazel_lib_host//:defs.bzl", "host")
print(host.bazel_version)
That approach, however, incurs a cost in the user's WORKSPACE.
utils.is_bazel_7_or_greater
Detects if the Bazel version being used is greater than or equal to 7 (including Bazel 7 pre-releases and RCs).
Unlike the undocumented native.bazel_version
, which only works in WORKSPACE and repository rules, this function can
be used in rules and BUILD files.
An alternate approach to make the Bazel version available in BUILD files and rules would be to
use the host_repo repository rule
which contains the bazel_version in the exported host
struct:
WORKSPACE:
load("@bazel_lib//lib:host_repo.bzl", "host_repo")
host_repo(name = "bazel_lib_host")
BUILD.bazel:
load("@bazel_lib_host//:defs.bzl", "host")
print(host.bazel_version)
That approach, however, incurs a cost in the user's WORKSPACE.
utils.is_bzlmod_enabled
Detect the value of the --enable_bzlmod flag
utils.is_external_label
Returns True if the given Label (or stringy version of a label) represents a target outside of the workspace
Parameters
*param | a string or label |
utils.maybe_http_archive
Adapts a maybe(http_archive, ...) to look like an http_archive.
This makes WORKSPACE dependencies easier to read and update.
Typical usage looks like,
load("//lib:utils.bzl", http_archive = "maybe_http_archive")
http_archive(
name = "aspect_rules_js",
sha256 = "5bb643d9e119832a383e67f946dc752b6d719d66d1df9b46d840509ceb53e1f1",
strip_prefix = "rules_js-1.6.2",
url = "https://github.com/aspect-build/rules_js/archive/refs/tags/v1.6.2.tar.gz",
)
instead of the classic maybe pattern of,
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
maybe(
http_archive,
name = "aspect_rules_js",
sha256 = "5bb643d9e119832a383e67f946dc752b6d719d66d1df9b46d840509ceb53e1f1",
strip_prefix = "rules_js-1.6.2",
url = "https://github.com/aspect-build/rules_js/archive/refs/tags/v1.6.2.tar.gz",
)
Parameters
kwargs | all arguments to pass-forward to http_archive |
utils.path_to_workspace_root
Returns the path to the workspace root under bazel
utils.propagate_common_binary_rule_attributes
Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all binary rules
These are listed in Bazel's documentation:
https://bazel.build/reference/be/common-definitions#common-attributes
https://bazel.build/reference/be/common-definitions#common-attributes-binary
Parameters
*attrs | Dict of parameters to filter |
utils.propagate_common_rule_attributes
Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all rules
These are listed in Bazel's documentation:
https://bazel.build/reference/be/common-definitions#common-attributes
Parameters
*attrs | Dict of parameters to filter |
utils.propagate_common_test_rule_attributes
Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all test rules
These are listed in Bazel's documentation:
https://bazel.build/reference/be/common-definitions#common-attributes
https://bazel.build/reference/be/common-definitions#common-attributes-tests
Parameters
*attrs | Dict of parameters to filter |
utils.to_label
Converts a string to a Label. If Label is supplied, the same label is returned.
Parameters
*param | a string representing a label or a Label |
default_timeout
Provide a sane default for *_test timeout attribute.
The test-encyclopedia says:
Tests may return arbitrarily fast regardless of timeout.
A test is not penalized for an overgenerous timeout, although a warning may be issued:
you should generally set your timeout as tight as you can without incurring any flakiness.
However Bazel's default for timeout is medium, which is dumb given this guidance.
It also says:
Tests which do not explicitly specify a timeout have one implied based on the test's size as follows
Therefore if size is specified, we should allow timeout to take its implied default.
If neither is set, then we can fix Bazel's wrong default here to avoid warnings under
--test_verbose_timeout_warnings
.
This function can be used in a macro which wraps a testing rule.
Parameters
*size | the size attribute of a test target |
*timeout | the timeout attribute of a test target |
file_exists
Check whether a file exists.
Useful in macros to set defaults for a configuration file if it is present.
This can only be called during the loading phase, not from a rule implementation.
Parameters
*path | a label, or a string which is a path relative to this package |
glob_directories
Parameters
*include | |
kwargs |
is_bazel_6_or_greater
Detects if the Bazel version being used is greater than or equal to 6 (including Bazel 6 pre-releases and RCs).
Detecting Bazel 6 or greater is particularly useful in rules as slightly different code paths may be needed to
support bzlmod which was added in Bazel 6.
Unlike the undocumented native.bazel_version
, which only works in WORKSPACE and repository rules, this function can
be used in rules and BUILD files.
An alternate approach to make the Bazel version available in BUILD files and rules would be to
use the host_repo repository rule
which contains the bazel_version in the exported host
struct:
WORKSPACE:
load("@bazel_lib//lib:host_repo.bzl", "host_repo")
host_repo(name = "bazel_lib_host")
BUILD.bazel:
load("@bazel_lib_host//:defs.bzl", "host")
print(host.bazel_version)
That approach, however, incurs a cost in the user's WORKSPACE.
is_bazel_7_or_greater
Detects if the Bazel version being used is greater than or equal to 7 (including Bazel 7 pre-releases and RCs).
Unlike the undocumented native.bazel_version
, which only works in WORKSPACE and repository rules, this function can
be used in rules and BUILD files.
An alternate approach to make the Bazel version available in BUILD files and rules would be to
use the host_repo repository rule
which contains the bazel_version in the exported host
struct:
WORKSPACE:
load("@bazel_lib//lib:host_repo.bzl", "host_repo")
host_repo(name = "bazel_lib_host")
BUILD.bazel:
load("@bazel_lib_host//:defs.bzl", "host")
print(host.bazel_version)
That approach, however, incurs a cost in the user's WORKSPACE.
is_bzlmod_enabled
Detect the value of the --enable_bzlmod flag
is_external_label
Returns True if the given Label (or stringy version of a label) represents a target outside of the workspace
Parameters
*param | a string or label |
maybe_http_archive
Adapts a maybe(http_archive, ...) to look like an http_archive.
This makes WORKSPACE dependencies easier to read and update.
Typical usage looks like,
load("//lib:utils.bzl", http_archive = "maybe_http_archive")
http_archive(
name = "aspect_rules_js",
sha256 = "5bb643d9e119832a383e67f946dc752b6d719d66d1df9b46d840509ceb53e1f1",
strip_prefix = "rules_js-1.6.2",
url = "https://github.com/aspect-build/rules_js/archive/refs/tags/v1.6.2.tar.gz",
)
instead of the classic maybe pattern of,
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
maybe(
http_archive,
name = "aspect_rules_js",
sha256 = "5bb643d9e119832a383e67f946dc752b6d719d66d1df9b46d840509ceb53e1f1",
strip_prefix = "rules_js-1.6.2",
url = "https://github.com/aspect-build/rules_js/archive/refs/tags/v1.6.2.tar.gz",
)
Parameters
kwargs | all arguments to pass-forward to http_archive |
path_to_workspace_root
Returns the path to the workspace root under bazel
propagate_common_rule_attributes
Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all rules
These are listed in Bazel's documentation:
https://bazel.build/reference/be/common-definitions#common-attributes
Parameters
*attrs | Dict of parameters to filter |
propagate_common_test_rule_attributes
Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all test rules
These are listed in Bazel's documentation:
https://bazel.build/reference/be/common-definitions#common-attributes
https://bazel.build/reference/be/common-definitions#common-attributes-tests
Parameters
*attrs | Dict of parameters to filter |
propagate_common_binary_rule_attributes
Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all binary rules
These are listed in Bazel's documentation:
https://bazel.build/reference/be/common-definitions#common-attributes
https://bazel.build/reference/be/common-definitions#common-attributes-binary
Parameters
*attrs | Dict of parameters to filter |
to_label
Converts a string to a Label. If Label is supplied, the same label is returned.
Parameters
*param | a string representing a label or a Label |
consistent_label_str
Generate a consistent label string for all Bazel versions.
Starting in Bazel 6, the workspace name is empty for the local workspace and there's no other
way to determine it. This behavior differs from Bazel 5 where the local workspace name was fully
qualified in str(label).
This utility function is meant for use in rules and requires the rule context to determine the
user's workspace name (ctx.workspace_name
).
Parameters
*ctx | The rule context. |
*label | A Label. |
@bazel_lib//lib:windows_utils.bzl
Helpers for rules running on windows
Functions & Macros
create_windows_native_launcher_script
Create a Windows Batch file to launch the given shell script.
The rule should specify @bazel_tools//tools/sh:toolchain_type as a required toolchain.
Parameters
*ctx | Rule context |
*shell_script | The bash launcher script |
@bazel_lib//lib:write_source_files.bzl
write_source_files provides a workaround for the restriction that bazel build
cannot write to the source tree.
Read more about the philosophy of writing to the source tree: https://blog.aspect.build/bazel-can-write-to-the-source-folder
Usage
load("@bazel_lib//lib:write_source_files.bzl", "write_source_files") write_source_files( name = "write_foobar", files = { "foobar.json": "//some/generated:file", }, )
To update the source file, run:
bazel run //:write_foobar
The generated diff_test
will fail if the file is out of date and print out instructions on
how to update it.
If the file does not exist, Bazel will fail at analysis time and print out instructions on
how to create it.
You can declare a tree of generated source file targets:
load("@bazel_lib//lib:write_source_files.bzl", "write_source_files") write_source_files( name = "write_all", additional_update_targets = [ # Other write_source_files targets to run when this target is run "//a/b/c:write_foo", "//a/b:write_bar", ] )
And update them with a single run:
bazel run //:write_all
When a file is out of date, you can leave a suggestion to run a target further up in the tree by specifying suggested_update_target
.
For example,
write_source_files( name = "write_foo", files = { "foo.json": ":generated-foo", }, suggested_update_target = "//:write_all" )
A test failure from foo.json
being out of date will yield the following message:
//a/b:c:foo.json is out of date. To update this and other generated files, run:
bazel run //:write_all
To update *only* this file, run:
bazel run //a/b/c:write_foo
You can also add a more customized error message using the diff_test_failure_message
argument:
write_source_file( name = "write_foo", out_file = "foo.json", in_file = ":generated-foo", diff_test_failure_message = "Failed to build Foo; please run {{TARGET}} to update." )
A test failure from foo.json
being out of date will then yield:
Failed to build Foo; please run //a/b/c:write_foo to update.
If you have many write_source_files
targets that you want to update as a group, we recommend wrapping
write_source_files
in a macro that defaults suggested_update_target
to the umbrella update target.
NOTE: If you run formatters or linters on your codebase, it is advised that you exclude/ignore the outputs of this
rule from those formatters/linters so as to avoid causing collisions and failing tests.
Functions & Macros
write_source_files
Write one or more files and/or directories to the source tree.
By default, diff_test
targets are generated that ensure the source tree files and/or directories to be written to
are up to date and the rule also checks that all source tree files and/or directories to be written to exist.
To disable the exists check and up-to-date tests set diff_test
to False
.
Parameters
*name | Name of the runnable target that creates or updates the source tree files and/or directories. |
files | A dict where the keys are files or directories in the source tree to write to and the values are labels Destination files and directories must be within the same containing Bazel package as this target if Default: {} |
executable | Whether source tree files written should be made executable. This applies to all source tree files written by this target. This attribute is not propagated to To set different executable permissions on different source tree files use multiple Default: False |
additional_update_targets | List of other Default: [] |
suggested_update_target | Label of the Default: None |
diff_test | Test that the source tree files and/or directories exist and are up to date. Default: True |
diff_test_failure_message | Text to print when the diff test fails, with templating options for Substitutions are performed on the failure message, with the following substitutions being available:
Default: "{{DEFAULT_MESSAGE}}" |
diff_args | Arguments to pass to the Default: [] |
file_missing_failure_message | Text to print when the output file is missing. Subject to the same Default: "{{DEFAULT_MESSAGE}}" |
check_that_out_file_exists | Test that each output file exists and print a helpful error message if it doesn't. If Default: True |
kwargs | Other common named parameters such as |
write_source_file
Write a file or directory to the source tree.
By default, a diff_test
target ("{name}_test") is generated that ensure the source tree file or directory to be written to
is up to date and the rule also checks that the source tree file or directory to be written to exists.
To disable the exists check and up-to-date test set diff_test
to False
.
Parameters
*name | Name of the runnable target that creates or updates the source tree file or directory. |
in_file | File or directory to use as the desired content to write to This is typically a file or directory output of another target. If Default: None |
out_file | The file or directory to write to in the source tree. The output file or directory must be within the same containing Bazel package as this target if Default: None |
executable | Whether source tree file or files within the source tree directory written should be made executable. Default: False |
additional_update_targets | List of other Default: [] |
suggested_update_target | Label of the Default: None |
diff_test | Test that the source tree file or directory exist and is up to date. Default: True |
diff_test_failure_message | Text to print when the diff test fails, with templating options for Substitutions are performed on the failure message, with the following substitutions being available:
Default: "{{DEFAULT_MESSAGE}}" |
file_missing_failure_message | Text to print when the output file is missing. Subject to the same Default: "{{DEFAULT_MESSAGE}}" |
diff_args | Arguments to pass to the Default: [] |
check_that_out_file_exists | Test that the output file exists and print a helpful error message if it doesn't. If Default: True |
verbosity | Verbosity of message when the copy target is run. One of Default: "full" |
kwargs | Other common named parameters such as |
Providers
WriteSourceFileInfo
Provider for write_source_file targets
Fields
executable | Executable that updates the source files |
@bazel_lib//tools:integrity.bzl
Release binary integrity hashes.
This file contents are entirely replaced during release publishing.
The checked in content is only here to allow load() statements in the sources to resolve.
@bazel_lib//tools:version.bzl
version information. replaced with stamped info with each release
@bazel_lib//tools/release:hashes.bzl
Rule for generating integrity files
Default output is a .sha256 file but .sha1 and .md5 files are also available
via output groups.
Based on https://github.com/bazelbuild/examples/blob/main/rules/implicit_output/hash.bzl
Functions & Macros
hashes
Parameters
*name | |
*src | |
kwargs |