### Example: Binding Arguments with partial.make and partial.call
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/partial_doc.md
Demonstrates creating a partial function with initial arguments and then calling it with additional arguments. This example shows how positional and keyword arguments are handled during both creation and invocation.
```Starlark
def _foo(make_arg1, func_arg1):
print(make_arg1 + " " + func_arg1 + "!")
hi_func = partial.make(_foo, "Hello")
bye_func = partial.make(_foo, "Goodbye")
partial.call(hi_func, "Jennifer")
partial.call(hi_func, "Dave")
partial.call(bye_func, "Jennifer")
partial.call(bye_func, "Dave")
```
--------------------------------
### Typical build_test Usage Example
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/build_test_doc.md
Demonstrates how to use the build_test rule in a BUILD file to ensure a target can be built.
```bazel
load("@bazel_skylib//rules:build_test.bzl", "build_test")
build_test(
name = "my_build_test",
targets = [
"//some/package:rule",
],
)
```
--------------------------------
### Example: Overriding Keyword Arguments with partial.make and partial.call
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/partial_doc.md
Illustrates how keyword arguments provided during `partial.call` can override those set during `partial.make`. This allows for flexible default value management.
```Starlark
def _foo(make_arg1, call_arg1, make_location, call_location):
print(make_arg1 + " is from " + make_location + " and " +
call_arg1 + " is from " + call_location + "!")
func = partial.make(_foo, "Ben", make_location="Hollywood")
partial.call(func, "Jennifer", call_location="Denver")
```
```Starlark
partial.call(func, "Jennifer", make_location="LA", call_location="Denver")
```
--------------------------------
### directory_glob Usage Example
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/directory_glob_doc.md
Demonstrates how to use the directory_glob rule to specify files and data to include, and patterns to exclude. The `directory` attribute is required.
```bzl
directory_glob(
name = "foo",
directory = ":directory",
srcs = ["foo/bar"],
data = ["foo/**"],
exclude = ["foo/**/*.h"]
)
```
--------------------------------
### Typical usage of analysis_test
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/analysis_test_doc.md
Example of how to use the analysis_test rule in a BUILD file. Specify the name of the test and the targets to analyze.
```bzl
load("@bazel_skylib//rules:analysis_test.bzl", "analysis_test")
analysis_test(
name = "my_analysis_test",
targets = [
"//some/package:rule",
],
)
```
--------------------------------
### Add Skylib WORKSPACE Setup
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/README.md
Include this in your WORKSPACE file to set up Skylib for versions released in or after December 2018. This enables the use of modules like unittest.bzl.
```python
load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace")
bazel_skylib_workspace()
```
--------------------------------
### Register Unittest Toolchains
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/unittest_doc.md
Call register_unittest_toolchains to make the necessary toolchains available for unittest users. This is a setup function for the testing framework.
```Starlark
load("@bazel_skylib//lib:unittest.bzl", "register_unittest_toolchains")
register_unittest_toolchains()
```
--------------------------------
### Get Target Binary Directory Path
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/unittest_doc.md
Use `analysistest.target_bin_dir_path` to get the `ctx.bin_dir.path` for the target under test. This function requires the test environment.
```Starlark
load("@bazel_skylib//lib:unittest.bzl", "analysistest")
analysistest.target_bin_dir_path(env)
```
--------------------------------
### Check if Path Starts With
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/paths_doc.md
Use paths.starts_with to check if one path is an ancestor of another. This function does not account for operating system-specific case-insensitivity.
```Starlark
load("@bazel_skylib//lib:paths.bzl", "paths")
paths.starts_with(path_a, path_b)
```
--------------------------------
### Define a New Skylib Module
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/README.md
Example of how to structure a new Skylib module. Private functions are prefixed with an underscore, and the exported module struct maps public names to implementations.
```python
def _manipulate():
...
things = struct(
manipulate=_manipulate,
)
```
--------------------------------
### List all direct subpackages
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/subpackages_doc.md
Use this to get a list of all direct subpackages of the current package. It does not include subpackages of subpackages. It fails if native.subpackages() is not supported.
```Starlark
load("@bazel_skylib//lib:subpackages.bzl", "subpackages")
subpackages.all(exclude = [], allow_empty = False, fully_qualified = True)
```
--------------------------------
### Get a string representation of a set (alternative)
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/new_sets_doc.md
Use `sets.str` to obtain a string that represents the set 's'. This function is an alternative to `sets.repr`. The input 's' must be a set created by `sets.make()`.
```Starlark
load("@bazel_skylib//lib:new_sets.bzl", "sets")
sets.str(s)
```
--------------------------------
### paths.relativize
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/paths_doc.md
Returns the portion of `path` that is relative to `start`. Fails if `path` is not beneath `start`.
```APIDOC
## paths.relativize
### Description
Returns the portion of `path` that is relative to `start`.
### Parameters
#### Path Parameters
- **path** (string) - Required - The path to relativize.
- **start** (string) - Required - The ancestor path against which to relativize.
### Returns
- (string) - The portion of `path` that is relative to `start`.
```
--------------------------------
### Begin Unit Test
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/unittest_doc.md
Use unittest.begin as the first function in a unit test implementation to initialize the test environment. This environment collects assertion failures for reporting.
```Starlark
load("@bazel_skylib//lib:unittest.bzl", "unittest")
unittest.begin(ctx)
```
--------------------------------
### Relativize Path
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/paths_doc.md
Use paths.relativize to determine the portion of a path that is relative to a starting path. This function will fail if the path is not a subdirectory of the start path, unlike Python's os.path.relpath.
```Starlark
load("@bazel_skylib//lib:paths.bzl", "paths")
paths.relativize(path, start)
```
--------------------------------
### unittest.begin
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/unittest_doc.md
Initializes the unit test environment. This function must be called at the beginning of any unit test to set up the test context.
```APIDOC
## unittest.begin
### Description
Begins a unit test. This should be the first function called in a unit test implementation function. It initializes a "test environment" that is used to collect assertion failures so that they can be reported and logged at the end of the test.
### Parameters
* `ctx` (object) - Required - The Starlark context. Pass the implementation function's `ctx` argument in verbatim.
### Returns
* A test environment struct that must be passed to assertions and finally to `unittest.end`. Do not rely on internal details about the fields in this struct as it may change.
```
--------------------------------
### Using select_file() Build Rule
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/select_file_doc.md
Demonstrates how to load and use the select_file rule. Specify a unique name, the source target, and the relative path to the desired file.
```python
load("@bazel_skylib//rules:select_file.bzl", "select_file")
select_file(
name = "my_selected_file",
srcs = ":my_target_producing_files",
subpath = "path/to/desired/file.txt",
)
```
--------------------------------
### loadingtest.make
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/unittest_doc.md
Initializes a test environment for the loading phase and creates a test suite. This is the entry point for loading phase tests.
```APIDOC
## loadingtest.make
### Description
Creates a loading phase test environment and test_suite.
### Parameters
* `name` (string) - Required - name of the suite of tests to create.
### Returns
* loading phase environment passed to other loadingtest functions
```
--------------------------------
### Load and Use copy_directory Rule
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/copy_directory_doc.md
This snippet shows how to load and use the `copy_directory` rule in a BUILD file. It requires specifying a name, source directory, and output directory.
```bazel
load("@bazel_skylib//rules:copy_directory.bzl", "copy_directory")
copy_directory(
name = "my_copy",
src = "//path/to/source:directory",
out = "destination_directory",
)
```
--------------------------------
### Partial Function Application with `lib/partial`
Source: https://context7.com/bazelbuild/bazel-skylib/llms.txt
Demonstrates deferred function calls using `partial.make` to bind arguments and `partial.call` to invoke them. Use `partial.is_instance` to check if a value is a partial object.
```starlark
load("@bazel_skylib//lib:partial.bzl", "partial")
def _greet(greeting, name, punctuation = "!"):
return greeting + ", " + name + punctuation
hi = partial.make(_greet, "Hello")
bye = partial.make(_greet, "Goodbye", punctuation = ".")
partial.call(hi, "Alice") # => "Hello, Alice!"
partial.call(hi, "Bob", punctuation = "?") # => "Hello, Bob?"
partial.call(bye, "Charlie") # => "Goodbye, Charlie."
partial.is_instance(hi) # => True
partial.is_instance(_greet) # => False
# Practical: pass a rule implementation with pre-bound config
impl = partial.make(_make_action, compiler = "gcc")
```
--------------------------------
### Get Target Actions in Analysis Test
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/unittest_doc.md
Use `analysistest.target_actions` to retrieve a list of actions registered by the target under test. Requires the test environment.
```Starlark
load("@bazel_skylib//lib:unittest.bzl", "analysistest")
analysistest.target_actions(env)
```
--------------------------------
### Create Loading Phase Test Environment
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/unittest_doc.md
Use loadingtest.make to initialize a loading phase test environment and a test_suite. This environment is then passed to other loadingtest functions.
```Starlark
load("@bazel_skylib//lib:unittest.bzl", "loadingtest")
loadingtest.make(name)
```
--------------------------------
### Wrap Pre-built Executables with native_binary and native_test
Source: https://context7.com/bazelbuild/bazel-skylib/llms.txt
Wraps pre-built binaries for use with `bazel run`, `genrule`, or `run_binary`. `native_test` does the same for `bazel test`. Neither rule requires Bash.
```starlark
load("@bazel_skylib//rules:native_binary.bzl", "native_binary", "native_test")
# Wrap a downloaded binary as a Bazel-runnable tool
native_binary(
name = "terraform",
src = "@terraform_linux//:terraform",
out = "terraform",
data = ["@terraform_linux//:shared_libs"],
env = {"TF_LOG": "WARN"},
)
# Make a pre-built test executable runnable via "bazel test"
native_test(
name = "integration_test",
src = "//prebuilt:integration_test_bin",
out = "integration_test",
data = ["//testdata:fixtures"],
)
```
--------------------------------
### Get the number of elements in a set
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/new_sets_doc.md
Use `sets.length` to retrieve the count of elements within a set. The input 's' must be a set created by `sets.make()`.
```Starlark
load("@bazel_skylib//lib:new_sets.bzl", "sets")
sets.length(s)
```
--------------------------------
### Add Bazel Skylib as a dependency (Legacy WORKSPACE)
Source: https://context7.com/bazelbuild/bazel-skylib/llms.txt
This snippet shows how to set up bazel_skylib using a legacy WORKSPACE file. It downloads the archive and registers unittest toolchains.
```Starlark
# WORKSPACE
load(@bazel_tools//tools/build_defs/repo:http.bzl, "http_archive")
http_archive(
name = "bazel_skylib",
sha256 = "",
urls = ["https://github.com/bazelbuild/bazel-skylib/releases/download/1.9.1/bazel-skylib-1.9.1.tar.gz"],
)
load(@bazel_skylib//:workspace.bzl, "bazel_skylib_workspace")
bazel_skylib_workspace() # registers unittest toolchains
```
--------------------------------
### get_relative
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/directory_utils_doc.md
Gets a subdirectory or file located at a specified path relative to a given directory. It supports optional checks to ensure the target is a directory or a file.
```APIDOC
## get_relative
### Description
Gets a subdirectory or file contained within a tree of another directory.
### Parameters
* **directory** (DirectoryInfo) - Required - The directory to look within.
* **path** (string) - Required - The path of the directory or file to look for within it.
* **require_dir** (bool) - Optional - If true, throws an error if the value is not a directory. Defaults to `False`.
* **require_file** (bool) - Optional - If true, throws an error if the value is not a file. Defaults to `False`.
### Returns
(File|DirectoryInfo) - The directory or file contained within.
```
--------------------------------
### Load and Use Skylib Modules
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/README.md
Demonstrates how to load specific modules like 'paths' and 'shell' from Skylib and use their functions. Ensure the modules are available in your WORKSPACE.
```python
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@bazel_skylib//lib:shell.bzl", "shell")
p = paths.basename("foo.bar")
s = shell.quote(p)
```
--------------------------------
### Return from Module Extension to Use All Repositories
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/modules_doc.md
Use `modules.use_all_repos` within a module extension's implementation function to indicate that all generated repositories should be imported via `use_repo`. This function returns an `extension_metadata` object.
```starlark
load("@bazel_skylib//lib:modules.bzl", "modules")
def _ext_impl(module_ctx):
some_repo_rule(name = "foobar")
http_archive(name = "bazqux")
return modules.use_all_repos(module_ctx)
ext = module_extension(_ext_impl)
```
--------------------------------
### Add Bazel Skylib as a dependency (Bzlmod)
Source: https://context7.com/bazelbuild/bazel-skylib/llms.txt
Use this snippet to add bazel_skylib as a dependency when using Bzlmod for your Bazel project. No further workspace setup is required.
```Starlark
# MODULE.bazel
bazel_dep(name = "bazel_skylib", version = "1.9.1")
```
--------------------------------
### Get Target Under Test in Analysis Test
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/unittest_doc.md
Retrieves the target currently being tested within an analysis test environment. Requires the test environment to be initialized by `analysistest.begin`.
```Starlark
load("@bazel_skylib//lib:unittest.bzl", "analysistest")
analysistest.target_under_test(env)
```
--------------------------------
### analysistest.begin
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/unittest_doc.md
Initializes the test environment for an analysis test. This function should be called at the beginning of an analysis test implementation.
```APIDOC
## analysistest.begin
### Description
Begins an analysis test. This should be the first function called in an analysis test implementation function. It initializes a "test environment" that is used to collect assertion failures so that they can be reported and logged at the end of the test.
### Syntax
```python
load("@bazel_skylib//lib:unittest.bzl", "analysistest")
analysistest.begin(
ctx
)
```
### Parameters
* **ctx** (Starlark context) - The Starlark context. Pass the implementation function's `ctx` argument in verbatim.
### Returns
A test environment struct that must be passed to assertions and finally to `analysistest.end`. Do not rely on internal details about the fields in this struct as it may change.
```
--------------------------------
### Create a config_setting_group
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/selects_doc.md
Define a group of config_settings that can be referenced in select(). Use `match_all` to require all settings to match, or `match_any` to require at least one to match. The group's name is used in select() statements.
```Starlark
load("@bazel_skylib//lib:selects.bzl", "selects")
selects.config_setting_group(
name = "one_two_three",
match_all = [":one", ":two", ":three"]
)
```
--------------------------------
### Get a string representation of a set
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/new_sets_doc.md
Use `sets.repr` to obtain a string that represents the set 's'. This is useful for debugging or logging. The input 's' must be a set created by `sets.make()`.
```Starlark
load("@bazel_skylib//lib:new_sets.bzl", "sets")
sets.repr(s)
```
--------------------------------
### Run Binary with run_binary Rule
Source: https://context7.com/bazelbuild/bazel-skylib/llms.txt
Runs an executable as a build action. Supports `$(execpath ...)` and `$(location ...)` expansion in `args` and `env`.
```starlark
load("@bazel_skylib//rules:run_binary.bzl", "run_binary")
run_binary(
name = "gen_proto",
tool = "//tools:protoc",
srcs = ["service.proto", "//tools:proto_plugin"],
outs = ["service.pb.cc", "service.pb.h"],
args = [
"--cpp_out=$(execpath service.pb.cc):$(execpath service.pb.h)",
"$(execpath service.proto)",
],
env = {
"PROTO_PATH": "$(execpath //tools:proto_plugin)",
},
)
```
--------------------------------
### Load and Use directory Rule
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/directory_doc.md
Demonstrates how to load the `directory` rule from the Bazel Skylib library and how to invoke it with its required and optional attributes. Use this rule to define directory-specific metadata targets.
```bzl
load("@bazel_skylib//rules/directory:directory.bzl", "directory")
directory(name, srcs)
```
--------------------------------
### Advanced Select Logic with `lib/selects`
Source: https://context7.com/bazelbuild/bazel-skylib/llms.txt
Utilizes `selects.with_or` for OR-logic in dependencies and `selects.config_setting_group` to create combined configuration settings. This allows for more flexible dependency management based on platform or build configurations.
```starlark
load("@bazel_skylib//lib:selects.bzl", "selects")
# with_or: deps differ between two platforms, same value for a third or fourth
cc_binary(
name = "myapp",
deps = selects.with_or({
"//configs:linux": [":linux_dep"],
("//configs:mac", "//configs:win"): [":posix_dep"],
"//conditions:default": [":fallback"],
}),
)
# config_setting_group: require both settings to be true
config_setting(name = "opt", values = {"compilation_mode": "opt"})
config_setting(name = "linux", constraint_values = ["@platforms//os:linux"])
selects.config_setting_group(
name = "opt_linux",
match_all = [":opt", ":linux"],
)
cc_binary(
name = "optimized_linux_only",
srcs = ["main.cc"],
deps = select({
":opt_linux": [":fast_lib"],
"//conditions:default": [],
}),
)
```
--------------------------------
### Create a new set
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/new_sets_doc.md
Use `sets.make` to initialize a new set. An optional sequence of hashable elements can be provided for initial population. If no elements are provided, an empty set is created.
```Starlark
load("@bazel_skylib//lib:new_sets.bzl", "sets")
sets.make(elements)
```
--------------------------------
### Enumerate BUILD Subpackages with `lib/subpackages`
Source: https://context7.com/bazelbuild/bazel-skylib/llms.txt
Wraps `native.subpackages()` for Bazel 6+ to list or check for direct sub-packages. `subpackages.all()` returns fully qualified labels, while `subpackages.exists()` tests for a specific sub-package's presence.
```starlark
load("@bazel_skylib//lib:subpackages.bzl", "subpackages")
# In a root BUILD file, list all direct sub-packages
# Given: foo/BUILD, foo/sub/BUILD, bar/BUILD
subpackages.all()
# => ["//foo", "//bar"] (foo/sub is a child of //foo, not //)
subpackages.exists("foo") # => True
subpackages.exists("foo/sub") # => False (not a *direct* child of //)
subpackages.supported() # => True (on Bazel 6+)
# Exclude specific sub-packages
subpackages.all(exclude = ["vendor/**"])
```
--------------------------------
### Begin analysis test
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/unittest_doc.md
Initializes the test environment for an analysis test. This function must be called first in the test implementation.
```Starlark
load("@bazel_skylib//lib:unittest.bzl", "analysistest")
_my_test_impl = lambda ctx: analysistest.end(analysistest.begin(ctx))
```
--------------------------------
### Load and Use subdirectory Rule
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/directory_subdirectory_doc.md
This snippet shows how to load the `subdirectory` rule from the Bazel Skylib library and demonstrates its basic usage with required attributes.
```bzl
load("@bazel_skylib//rules/directory:subdirectory.bzl", "subdirectory")
subdirectory(name = "my_subdir", parent = "::", path = "path/to/subdir")
```
--------------------------------
### modules.use_all_repos
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/modules_doc.md
Returns from a module extension to indicate that all its repositories should be imported via `use_repo`. It takes a `module_ctx` and an optional `reproducible` flag.
```APIDOC
## modules.use_all_repos
### Description
Return from a module extension that should have all its repositories imported via `use_repo`.
### Signature
```starlark
load("@bazel_skylib//lib:modules.bzl", "modules")
modules.use_all_repos(module_ctx, reproducible=False)
```
### Parameters
* **module_ctx** (module_ctx) - Required - The [`module_ctx`](https://bazel.build/rules/lib/builtins/module_ctx) object passed to the module extension's implementation function.
* **reproducible** (bool) - Optional - The value of the `reproducible` parameter to pass to the [`extension_metadata`](https://bazel.build/rules/lib/builtins/extension_metadata.html) object returned by this function. This is safe to set with Bazel versions that don't support this parameter and will be ignored in that case. Defaults to `False`.
### Returns
An [`extension_metadata`](https://bazel.build/rules/lib/builtins/extension_metadata.html) object that, when returned from a module extension implementation function, specifies that all repositories generated by this extension should be imported via `use_repo`. If the current version of Bazel doesn't support `extension_metadata`, returns `None` instead, which can safely be returned from a module extension implementation function in all versions of Bazel.
### Example
```starlark
def _ext_impl(module_ctx):
some_repo_rule(name = "foobar")
http_archive(name = "bazqux")
return modules.use_all_repos(module_ctx)
ext = module_extension(_ext_impl)
```
```
--------------------------------
### string_list_setting
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/common_settings_doc.md
Defines a string list-typed build setting that expects comma-separated values on the command line, parsed into a list of strings.
```APIDOC
## string_list_setting
### Description
A string list-typed build setting which expects its value on the command line to be given in comma-separated format; for example, `--//my/setting=foo,bar` will be parsed as `['foo', 'bar']`. Contrast with `repeatable_string_flag`.
### Signature
```
load("@bazel_skylib//rules:common_settings.bzl", "string_list_setting")
string_list_setting(name, scope)
```
### Attributes
* **name** (Name) - Required - A unique name for this target.
* **scope** (String) - Optional - The scope indicates where a flag can propagate to. Defaults to "target".
```
--------------------------------
### int_flag
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/common_settings_doc.md
Defines an integer build setting that can be set on the command line. It returns a BuildSettingInfo with the value of the build setting and can be exposed as a Make variable.
```APIDOC
## int_flag
### Description
An int-typed build setting that can be set on the command line.
### Syntax
```starlark
load("@bazel_skylib//rules:common_settings.bzl", "int_flag")
int_flag(name, make_variable, scope)
```
### Parameters
* **name** (Name) - Required - A unique name for this target.
* **make_variable** (String) - Optional - If set, the build setting's value will be available as a Make variable with this name in the attributes of rules that list this build setting in their 'toolchains' attribute. Defaults to `""`.
* **scope** (String) - Optional - The scope indicates where a flag can propagate to. Defaults to `"target"`.
```
--------------------------------
### int_setting
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/common_settings_doc.md
Defines an integer build setting that cannot be set on the command line. It returns a BuildSettingInfo with the value of the build setting and can be exposed as a Make variable.
```APIDOC
## int_setting
### Description
An int-typed build setting that cannot be set on the command line.
### Syntax
```starlark
load("@bazel_skylib//rules:common_settings.bzl", "int_setting")
int_setting(name, make_variable, scope)
```
### Parameters
* **name** (Name) - Required - A unique name for this target.
* **make_variable** (String) - Optional - If set, the build setting's value will be available as a Make variable with this name in the attributes of rules that list this build setting in their 'toolchains' attribute. Defaults to `""`.
* **scope** (String) - Optional - The scope indicates where a flag can propagate to. Defaults to `"target"`.
```
--------------------------------
### BuildSettingInfo
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/common_settings_doc.md
A provider that encapsulates the raw value of a build setting, which can originate from the command line, an upstream transition, or a default.
```APIDOC
## BuildSettingInfo
### Description
A singleton provider that contains the raw value of a build setting.
### Signature
```
load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo")
BuildSettingInfo(value)
```
### Fields
* **value** - The value of the build setting in the current configuration. This value may come from the command line or an upstream transition, or else it will be the build setting's default.
```
--------------------------------
### Bzlmod Utilities with `lib/modules`
Source: https://context7.com/bazelbuild/bazel-skylib/llms.txt
Provides utilities for migrating WORKSPACE macros to Bzlmod module extensions. `modules.as_extension` wraps a dependency macro, and `modules.use_all_repos` helps in importing generated repos within a module extension.
```starlark
# rules_foo/extensions.bzl
load("@bazel_skylib//lib:modules.bzl", "modules")
def _rules_foo_deps():
http_archive(name = "foo_dep_a", ...)
http_archive(name = "foo_dep_b", ...)
# Wrap the legacy macro as a module extension (reproducible = True by default)
rules_foo_deps_ext = modules.as_extension(
_rules_foo_deps,
doc = "Fetches dependencies for rules_foo",
)
# Consumer's MODULE.bazel:
# foo_ext = use_extension("@rules_foo//:extensions.bzl", "rules_foo_deps_ext")
# use_repo(foo_ext, "foo_dep_a", "foo_dep_b")
```
--------------------------------
### Load and Use write_file Rule
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/write_file_doc.md
Demonstrates how to load the write_file rule from bazel_skylib and its basic signature. This rule is used to create a UTF-8 encoded text file with specified content.
```Starlark
load("@bazel_skylib//rules:write_file.bzl", "write_file")
write_file(name, out, content, is_executable, newline, **kwargs)
```
--------------------------------
### Load and Call bazel_skylib_workspace
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/README.md
Ensure this is called in your WORKSPACE file to resolve toolchain issues with unittest.
```starlark
load("@bazel_skylib_gazelle_plugin//:workspace.bzl", "bazel_skylib_gazelle_plugin_workspace")
bazel_skylib_gazelle_plugin_workspace()
load("@bazel_skylib_gazelle_plugin//:setup.bzl", "bazel_skylib_gazelle_plugin_setup")
bazel_skylib_gazelle_plugin_setup()
```
--------------------------------
### Bazel Version Gating with `lib/versions`
Source: https://context7.com/bazelbuild/bazel-skylib/llms.txt
Implements Bazel version checks using `versions.check` to enforce minimum or range requirements, failing the build if unmet. `versions.is_at_least` and `versions.is_at_most` provide boolean results for conditional logic.
```starlark
load("@bazel_skylib//lib:versions.bzl", "versions")
# Hard minimum version requirement (fails build if not met)
versions.check("6.0.0")
# Require a specific range
versions.check(minimum_bazel_version = "5.0.0", maximum_bazel_version = "8.99.99")
# Conditional logic
def _impl(ctx):
if versions.is_at_least("7.0.0", versions.get()):
# use newer API
pass
else:
# fallback
pass
# Parse a version string into comparable tuple
versions.parse("7.1.2rc1 abc1234") # => (7, 1, 2)
versions.parse("") # => (999999, 999999, 999999) # dev build
```
--------------------------------
### Create a new set
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/new_sets_doc.md
Use `sets.make()` to create an empty set or initialize it with a sequence of values. All provided values must be hashable.
```python
load("@bazel_skylib//lib:new_sets.bzl", "sets")
my_set = sets.make()
my_set_with_values = sets.make([1, 2, 3])
```
--------------------------------
### versions.get
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/versions_doc.md
Returns the current Bazel version.
```APIDOC
## versions.get
### Description
Returns the current Bazel version.
### Code Example
```starlark
load("@bazel_skylib//lib:versions.bzl", "versions")
current_version = versions.get()
```
```
--------------------------------
### create_directory_info Function
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/directory_providers_doc.md
The create_directory_info function is used to create an instance of the DirectoryInfo provider. It accepts keyword arguments to configure the directory information.
```APIDOC
## create_directory_info
### Description
Creates a DirectoryInfo provider.
### Parameters
- **kwargs** - Required - Accepts arbitrary keyword arguments to configure the DirectoryInfo.
```
--------------------------------
### native_test
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/native_binary_doc.md
Wraps a pre-built binary or script with a test rule. This allows it to be executed with 'bazel test' like any other test rule, and can also be augmented with runfiles.
```APIDOC
## native_test
### Description
Wraps a pre-built binary or script with a test rule.
You can "bazel test" this rule like any other test rule. You can also augment
the binary with runfiles.
### Rule Signature
```
load("@bazel_skylib//rules:native_binary.bzl", "native_test")
native_test(name, src, data, out, env)
```
### Attributes
* **name** (Name) - Required. A unique name for this target.
* **src** (Label) - Required. Path of the pre-built executable.
* **data** (List of labels) - Optional. Data dependencies. Defaults to `[]`.
* **out** (String) - Optional. An output name for the copy of the binary. Defaults to name.exe.
* **env** (Dictionary: String -> String) - Optional. Environment variables to set when running the binary. Defaults to `{}`.
```
--------------------------------
### string_setting
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/common_settings_doc.md
Defines a string-typed build setting that cannot be set directly on the command line. It supports allowed values and an optional make variable.
```APIDOC
## string_setting
### Description
A string-typed build setting that cannot be set on the command line.
### Signature
```
load("@bazel_skylib//rules:common_settings.bzl", "string_setting")
string_setting(name, make_variable, scope, values)
```
### Attributes
* **name** (Name) - Required - A unique name for this target.
* **make_variable** (String) - Optional - If set, the build setting's value will be available as a Make variable with this name.
* **scope** (String) - Optional - The scope indicates where a flag can propagate to. Defaults to "target".
* **values** (List of strings) - Optional - The list of allowed values for this setting. An error is raised if any other value is given. Defaults to `[]`.
```
--------------------------------
### string_flag
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/common_settings_doc.md
Defines a string-typed build setting that can be configured on the command line. It supports specifying allowed values and an optional make variable.
```APIDOC
## string_flag
### Description
A string-typed build setting that can be set on the command line.
### Signature
```
load("@bazel_skylib//rules:common_settings.bzl", "string_flag")
string_flag(name, make_variable, scope, values)
```
### Attributes
* **name** (Name) - Required - A unique name for this target.
* **make_variable** (String) - Optional - If set, the build setting's value will be available as a Make variable with this name.
* **scope** (String) - Optional - The scope indicates where a flag can propagate to. Defaults to "target".
* **values** (List of strings) - Optional - The list of allowed values for this setting. An error is raised if any other value is given. Defaults to `[]`.
```
--------------------------------
### string_list_flag
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/common_settings_doc.md
Defines a string list-typed build setting configurable on the command line. It allows for a list of strings to be set.
```APIDOC
## string_list_flag
### Description
A string list-typed build setting that can be set on the command line.
### Signature
```
load("@bazel_skylib//rules:common_settings.bzl", "string_list_flag")
string_list_flag(name, scope)
```
### Attributes
* **name** (Name) - Required - A unique name for this target.
* **scope** (String) - Optional - The scope indicates where a flag can propagate to. Defaults to "target".
```
--------------------------------
### modules.as_extension
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/modules_doc.md
Wraps a WORKSPACE dependency macro into a module extension. This function takes a macro and an optional documentation string, returning a module extension that generates repositories from the macro and uses `use_all_repos`.
```APIDOC
## modules.as_extension
### Description
Wraps a WORKSPACE dependency macro into a module extension.
### Signature
```starlark
load("@bazel_skylib//lib:modules.bzl", "modules")
modules.as_extension(macro, doc=None)
```
### Parameters
* **macro** (function) - Required - A [WORKSPACE dependency macro](https://bazel.build/rules/deploying#dependencies), i.e., a function with no required parameters that instantiates one or more repository rules.
* **doc** (string) - Optional - A description of the module extension that can be extracted by documentation generating tools. Defaults to `None`.
### Returns
A module extension that generates the repositories instantiated by the given macro and also uses [`use_all_repos`](#use_all_repos) to indicate that all of those repositories should be imported via `use_repo`. The extension is marked as reproducible if supported by the current version of Bazel and thus doesn't result in a lockfile entry.
### Example
```starlark
def rules_foo_deps(optional_arg = True):
some_repo_rule(name = "foobar")
http_archive(name = "bazqux")
rules_foo_deps_ext = modules.as_extension(rules_foo_deps)
```
```
--------------------------------
### Create a Partial Function Object
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/partial_doc.md
Use `partial.make` to create a partial function object. Arguments and keyword arguments provided here will be bound to the function and used when the partial object is called.
```Starlark
load("@bazel_skylib//lib:partial.bzl", "partial")
partial.make(func, *args, **kwargs)
```
--------------------------------
### Create an Analysis Test Rule
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/unittest_doc.md
Use `analysistest.make` to create a test rule from an implementation function. This is useful for verifying rule behavior by inspecting providers.
```Starlark
load("@bazel_skylib//lib:unittest.bzl", "analysistest")
analysistest.make(impl, expect_failure, attrs, fragments, config_settings, extra_target_under_test_aspects, doc)
```
```Starlark
def _your_test(ctx):
env = analysistest.begin(ctx)
# Assert statements go here
return analysistest.end(env)
your_test = analysistest.make(_your_test)
```
--------------------------------
### Configure Gazelle Plugin for bzl_library
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/README.md
Include this configuration in your BUILD.bazel file to enable the Gazelle plugin for generating bzl_library entries.
```starlark
load("@bazel_gazelle//:def.bzl", "DEFAULT_LANGUAGES", "gazelle", "gazelle_binary")
gazelle(
name = "gazelle",
gazelle = ":gazelle_bin",
)
gazelle_binary(
name = "gazelle_bin",
languages = DEFAULT_LANGUAGES + [
"@bazel_skylib_gazelle_plugin//bzl",
],
)
```
--------------------------------
### unittest.make
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/unittest_doc.md
Creates a unit test rule from its implementation function, handling boilerplate for rule creation and feedback.
```APIDOC
## unittest.make
### Description
Creates a unit test rule from its implementation function.
### Parameters
* **impl** (function) - Required - The implementation function of the unit test.
* **attrs** (dict) - Optional - An optional dictionary to supplement the attrs passed to the unit test's `rule()` constructor. Defaults to `{}`.
* **doc** (string) - Optional - A description of the rule that can be extracted by documentation generating tools. Defaults to `""`.
* **toolchains** (list) - Optional - An optional list to supplement the toolchains passed to the unit test's `rule()` constructor. Defaults to `[]`.
### Returns
A rule definition that should be stored in a global whose name ends in `_test`.
```
--------------------------------
### run_binary Rule
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/run_binary_doc.md
Defines and configures the run_binary rule for executing a binary as a build action.
```APIDOC
## run_binary
### Description
Runs a binary as a build action. This rule does not require Bash (unlike native.genrule()).
### Rule Signature
```
load("@bazel_skylib//rules:run_binary.bzl", "run_binary")
run_binary(
name,
outs,
srcs = [],
args = [],
env = {},
tool
)
```
### Attributes
* **name** (Name) - Required - A unique name for this target.
* **srcs** (List of labels) - Optional - Additional inputs of the action. These labels are available for `$(execpath)` and `$(location)` expansion in `args` and `env`.
* **outs** (List of labels) - Required - Output files generated by the action. These labels are available for `$(execpath)` and `$(location)` expansion in `args` and `env`.
* **args** (List of strings) - Optional - Command line arguments of the binary. Subject to `$(execpath)` and `$(location)` expansion.
* **env** (Dictionary: String -> String) - Optional - Environment variables of the action. Subject to `$(execpath)` and `$(location)` expansion.
* **tool** (Label) - Required - 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 a file that can be executed as a subprocess. This label is available for `$(execpath)` and `$(location)` expansion in `args` and `env`.
```
--------------------------------
### Create a Unit Test Rule
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/unittest_doc.md
Use `unittest.make` to wrap an implementation function into a Bazel test rule. This function handles boilerplate and captures the implementation name for test feedback. It supports custom attributes and toolchains for test dependencies.
```Starlark
load("@bazel_skylib//lib:unittest.bzl", "unittest")
def _your_test(ctx):
env = unittest.begin(ctx)
# Assert statements go here
return unittest.end(env)
your_test = unittest.make(_your_test)
```
--------------------------------
### bool_setting
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/common_settings_doc.md
Defines a boolean build setting that cannot be set on the command line. It returns a BuildSettingInfo with the value of the build setting.
```APIDOC
## bool_setting
### Description
A bool-typed build setting that cannot be set on the command line.
### Syntax
```starlark
load("@bazel_skylib//rules:common_settings.bzl", "bool_setting")
bool_setting(name, scope)
```
### Parameters
* **name** (Name) - Required - A unique name for this target.
* **scope** (String) - Optional - The scope indicates where a flag can propagate to. Defaults to `"target"`.
```
--------------------------------
### Create DirectoryInfo Provider
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/directory_providers_doc.md
Function to create a DirectoryInfo provider. It accepts arbitrary keyword arguments that are used to populate the provider's fields.
```bzl
load("@bazel_skylib//rules/directory:providers.bzl", "create_directory_info")
create_directory_info(**kwargs)
```
--------------------------------
### paths.join
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/paths_doc.md
Joins one or more path components intelligently, mimicking Python's `os.path.join` on POSIX.
```APIDOC
## paths.join
### Description
Joins one or more path components intelligently.
This function mimics the behavior of Python's `os.path.join` function on POSIX
platform. It returns the concatenation of `path` and any members of `others`,
inserting directory separators before each component except the first. The
separator is not inserted if the path up until that point is either empty or
already ends in a separator.
If any component is an absolute path, all previous components are discarded.
### Parameters
#### Path Parameters
- **path** (string) - Required - A path segment.
- **others** (list of strings) - Required - Additional path segments.
### Returns
- **string** - A string containing the joined paths.
```
--------------------------------
### paths.starts_with
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/paths_doc.md
Returns True if and only if path_b is an ancestor of path_a. Does not handle OS dependent case-insensitivity.
```APIDOC
## paths.starts_with
### Description
Returns True if and only if path_b is an ancestor of path_a.
### Parameters
#### Path Parameters
- **path_a** (string) - Required - The path to check.
- **path_b** (string) - Required - The potential ancestor path.
### Returns
- (boolean) - True if `path_b` is an ancestor of `path_a`, False otherwise.
```
--------------------------------
### bool_flag
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/common_settings_doc.md
Defines a boolean build setting that can be set on the command line. It returns a BuildSettingInfo with the value of the build setting.
```APIDOC
## bool_flag
### Description
A bool-typed build setting that can be set on the command line.
### Syntax
```starlark
load("@bazel_skylib//rules:common_settings.bzl", "bool_flag")
bool_flag(name, scope)
```
### Parameters
* **name** (Name) - Required - A unique name for this target.
* **scope** (String) - Optional - The scope indicates where a flag can propagate to. Defaults to `"target"`.
```
--------------------------------
### dicts.pick
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/dicts_doc.md
Creates a new dictionary containing only the specified keys from the original dictionary.
```APIDOC
## dicts.pick
### Description
Returns a new `dict` that has all the entries of `dictionary` with keys in `keys`.
### Method
Starlark function call
### Parameters
#### Path Parameters
- **dictionary** (dict) - Required - A `dict`.
- **keys** (sequence) - Required - A sequence of keys to pick.
### Returns
- **dict** - A new `dict` that has all the entries of `dictionary` with keys in `keys`.
```
--------------------------------
### analysistest.make
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/unittest_doc.md
Creates an analysis test rule from its implementation function, simplifying the process of defining tests for Bazel rules.
```APIDOC
## analysistest.make
### Description
Creates an analysis test rule from its implementation function.
An analysis test verifies the behavior of a "real" rule target by examining and asserting on the providers given by the real target.
### Method
Call
### Parameters
#### Path Parameters
- **impl** (function) - Required - The implementation function of the unit test.
- **expect_failure** (boolean) - Optional - If true, the analysis test will expect the target_under_test to fail. Assertions can be made on the underlying failure using asserts.expect_failure. Defaults to `False`.
- **attrs** (dict) - Optional - An optional dictionary to supplement the attrs passed to the unit test's `rule()` constructor. Defaults to `{}`.
- **fragments** (list) - Optional - An optional list of fragment names that can be used to give rules access to language-specific parts of configuration. Defaults to `[]`.
- **config_settings** (dict) - Optional - A dictionary of configuration settings to change for the target under test and its dependencies. This may be used to essentially change 'build flags' for the target under test, and may thus be utilized to test multiple targets with different flags in a single build. Defaults to `{}`.
- **extra_target_under_test_aspects** (list) - Optional - An optional list of aspects to apply to the target_under_test in addition to those set up by default for the test harness itself. Defaults to `[]`.
- **doc** (string) - Optional - A description of the rule that can be extracted by documentation generating tools. Defaults to `""`.
### Returns
A rule definition that should be stored in a global whose name ends in `_test`.
```
--------------------------------
### Changelog Template for New Releases
Source: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/maintainers_guide.md
A template for updating the CHANGELOG.md file when making a new release, including sections for new features, incompatible changes, and contributors.
```markdown
# Release $VERSION
**New Features**
- Feature
- Feature
**Incompatible Changes**
- Change
- Change
**Contributors**
Name 1, Name 2, Name 3 (alphabetically from `git log`)
```