Globals
Objects, functions and modules registered in the global environment.Members
- all
- analysis_test_transition
- any
- aspect
- bind
- bool
- configuration_field
- depset
- dict
- dir
- enumerate
- exec_group
- fail
- getattr
- hasattr
- hash
- int
- len
- list
- max
- min
- provider
- range
- register_execution_platforms
- register_toolchains
- repository_rule
- repr
- reversed
- rule
- select
- sorted
- str
- tuple
- type
- workspace
- zip
all
bool all(elements)Returns true if all elements evaluate to True or if the collection is empty. Elements are converted to boolean using the bool function.
all(["hello", 3, True]) == True all([-1, 0, 1]) == False
Parameters
Parameter | Description |
---|---|
elements
|
A string or a collection of elements. |
analysis_test_transition
transition analysis_test_transition(settings)
Creates a configuration transition to be applied on an analysis-test rule's dependencies. This transition may only be applied on attributes of rules with analysis_test = True
. Such rules are restricted in capabilities (for example, the size of their dependency tree is limited), so transitions created using this function are limited in potential scope as compared to transitions created using transition.
This function is primarily designed to facilitate the Analysis Test Framework core library. See its documentation (or its implementation) for best practices.
Parameters
Parameter | Description |
---|---|
settings
|
A dictionary containing information about configuration settings which should be set by this configuration transition. Keys are build setting labels and values are their new post-transition values. All other settings are unchanged. Use this to declare specific configuration settings that an analysis test requires to be set in order to pass. |
any
bool any(elements)Returns true if at least one element evaluates to True. Elements are converted to boolean using the bool function.
any([-1, 0, 1]) == True any([False, 0, ""]) == False
Parameters
Parameter | Description |
---|---|
elements
|
A string or a collection of elements. |
aspect
Aspect aspect(implementation, attr_aspects=[], attrs=None, required_aspect_providers=[], provides=[], fragments=[], host_fragments=[], toolchains=[], incompatible_use_toolchain_transition=False, doc='', *, apply_to_generating_rules=False)Creates a new aspect. The result of this function must be stored in a global value. Please see the introduction to Aspects for more details.
Parameters
Parameter | Description |
---|---|
implementation
|
A Starlark function that implements this aspect, with exactly two parameters: Target (the target to which the aspect is applied) and ctx (the rule context which the targetis created from). Attributes of the target are available via the |
attr_aspects
|
List of attribute names. The aspect propagates along dependencies specified in the attributes of a target with these names. Common values here include |
attrs
|
A dictionary declaring all the attributes of the aspect. It maps from an attribute name to an attribute object, like `attr.label` or `attr.string` (see attr module). Aspect attributes are available to implementation function as fields of Implicit attributes starting with Explicit attributes must have type |
required_aspect_providers
|
This attribute allows this aspect to inspect other aspects. The value must be a list of providers, or a list of lists of providers. For example, A single list of providers will automatically be converted to a list containing one list of providers. That is, To make another aspect (e.g. |
provides
|
A list of providers that the implementation function must return. It is an error if the implementation function omits any of the types of providers listed here from its return value. However, the implementation function may return additional providers not listed here. Each element of the list is an |
fragments
|
List of names of configuration fragments that the aspect requires in target configuration. |
host_fragments
|
List of names of configuration fragments that the aspect requires in host configuration. |
toolchains
|
If set, the set of toolchains this rule requires. Toolchains will be found by checking the current platform, and provided to the rule implementation via |
incompatible_use_toolchain_transition
|
If set, this aspect will use the toolchain transition for toolchain dependencies. This is ignored if the --incompatible_use_toolchain_transition flag is set. |
doc
|
A description of the aspect that can be extracted by documentation generating tools. |
apply_to_generating_rules
|
If true, the aspect will, when applied to an output file, instead apply to the output file's generating rule. For example, suppose an aspect propagates transitively through attribute `deps` and it is applied to target `alpha`. Suppose `alpha` has `deps = [':beta_output']`, where `beta_output` is a declared output of a target `beta`. Suppose `beta` has a target `charlie` as one of its `deps`. If `apply_to_generating_rules=True` for the aspect, then the aspect will propagate through `alpha`, `beta`, and `charlie`. If False, then the aspect will propagate only to `alpha`. False by default. |
bind
None bind(name, actual=None)
Warning: use of bind()
is not recommended. See Consider removing bind for a long discussion if its issues and alternatives.
Gives a target an alias in the //external
package.
Parameters
Parameter | Description |
---|---|
name
|
The label under '//external' to serve as the alias name |
actual
|
The real label to be aliased |
None
.
bool
bool bool(x=False)Constructor for the bool type. It returns
False
if the object is None
, False
, an empty string (""
), the number 0
, or an empty collection (e.g. ()
, []
). Otherwise, it returns True
.
Parameters
Parameter | Description |
---|---|
x
|
The variable to convert. |
configuration_field
LateBoundDefault configuration_field(fragment, name)References a late-bound default value for an attribute of type label. A value is 'late-bound' if it requires the configuration to be built before determining the value. Any attribute using this as a value must be private.
Example usage:
Defining a rule attribute:
'_foo': attr.label(default=configuration_field(fragment='java', name='toolchain'))
Accessing in rule implementation:
def _rule_impl(ctx): foo_info = ctx.attr._foo ...
Parameters
Parameter | Description |
---|---|
fragment
|
The name of a configuration fragment which contains the late-bound value. |
name
|
The name of the value to obtain from the configuration fragment. |
depset
depset depset(x=None, order="default", *, direct=None, transitive=None, items=[])Creates a depset. The
direct
parameter is a list of direct elements of the depset, and transitive
parameter is a list of depsets whose elements become indirect elements of the created depset. The order in which elements are returned when the depset is converted to a list is specified by the order
parameter. See the Depsets overview for more information.
All elements (direct and indirect) of a depset must be of the same type, as obtained by the expression type(x)
.
Because a hash-based set is used to eliminate duplicates during iteration, all elements of a depset should be hashable. However, this invariant is not currently checked consistently in all constructors. Use the --incompatible_always_check_depset_elements flag to enable consistent checking; this will be the default behavior in future releases; see Issue 10313.
In addition, elements must currently be immutable, though this restriction will be relaxed in future.
The order of the created depset should be compatible with the order of its transitive
depsets. "default"
order is compatible with any other order, all other orders are only compatible with themselves.
Note on backward/forward compatibility. This function currently accepts a positional items
parameter. It is deprecated and will be removed in the future, and after its removal direct
will become a sole positional parameter of the depset
function. Thus, both of the following calls are equivalent and future-proof:
depset(['a', 'b'], transitive = [...]) depset(direct = ['a', 'b'], transitive = [...])
Parameters
Parameter | Description |
---|---|
x
|
A positional parameter distinct from other parameters for legacy support. If If See the documentation for these parameters for more details. |
order
|
The traversal strategy for the new depset. See here for the possible values. |
direct
|
A list of direct elements of a depset. |
transitive
|
A list of depsets whose elements will become indirect elements of the depset. |
items
|
Deprecated. This parameter is deprecated and will be removed soon. Please do not depend on it. It is disabled with |
dict
dict dict(args=[], **kwargs)Creates a dictionary from an optional positional argument and an optional set of keyword arguments. In the case where the same key is given multiple times, the last value will be used. Entries supplied via keyword arguments are considered to come after entries supplied via the positional argument.
Parameters
Parameter | Description |
---|---|
args
|
Either a dictionary or a list of entries. Entries must be tuples or lists with exactly two elements: key, value. |
kwargs
|
Dictionary of additional entries. |
dir
list dir(x)Returns a list of strings: the names of the attributes and methods of the parameter object.
Parameters
Parameter | Description |
---|---|
x
|
The object to check. |
enumerate
list enumerate(list, start=0)Returns a list of pairs (two-element tuples), with the index (int) and the item from the input sequence.
enumerate([24, 21, 84]) == [(0, 24), (1, 21), (2, 84)]
Parameters
Parameter | Description |
---|---|
list
|
input sequence. |
start
|
start index. |
exec_group
exec_group exec_group(toolchains=[], exec_compatible_with=[])experimental Creates an execution group which can be used to createactions for a specific execution platform during rule implementation. This is ongoing work and not yet functional - DO NOT USE.
Parameters
Parameter | Description |
---|---|
toolchains
|
Experimental The set of toolchains this execution group requires. |
exec_compatible_with
|
Experimental A list of constraints on the execution platform. |
fail
None fail(msg=None, attr=None)Raises an error that cannot be intercepted. It can be used anywhere, both in the loading phase and in the analysis phase.
Parameters
Parameter | Description |
---|---|
msg
|
Error to display for the user. The object is converted to a string. |
attr
|
The name of the attribute that caused the error. This is used only for error reporting. |
getattr
unknown getattr(x, name, default=unbound)Returns the struct's field of the given name if it exists. If not, it either returns
default
(if specified) or raises an error. getattr(x, "foobar")
is equivalent to x.foobar
.getattr(ctx.attr, "myattr") getattr(ctx.attr, "myattr", "mydefault")
Parameters
Parameter | Description |
---|---|
x
|
The struct whose attribute is accessed. |
name
|
The name of the struct attribute. |
default
|
The default value to return in case the struct doesn't have an attribute of the given name. |
hasattr
bool hasattr(x, name)Returns True if the object
x
has an attribute or method of the given name
, otherwise False. Example:hasattr(ctx.attr, "myattr")
Parameters
Parameter | Description |
---|---|
x
|
The object to check. |
name
|
The name of the attribute. |
hash
int hash(value)Return a hash value for a string. This is computed deterministically using the same algorithm as Java's
String.hashCode()
, namely: s[0] * (31^(n-1)) + s[1] * (31^(n-2)) + ... + s[n-1]Hashing of values besides strings is not currently supported.
Parameters
Parameter | Description |
---|---|
value
|
String value to hash. |
int
int int(x, base=unbound)Returns x as an int value.
- If
x
is already an int, it is returned as-is. - If
x
is a boolean, a true value returns 1 and a false value returns 0. - If
x
is a string, it must have the format<sign><prefix><digits>
.<sign>
is either"+"
,"-"
, or empty (interpreted as positive).<digits>
are a sequence of digits from 0 up tobase
- 1, where the letters a-z (or equivalently, A-Z) are used as digits for 10-35. In the case wherebase
is 2/8/16,<prefix>
is optional and may be 0b/0o/0x (or equivalently, 0B/0O/0X) respectively; if thebase
is any other value besides these bases or the special value 0, the prefix must be empty. In the case wherebase
is 0, the string is interpreted as an integer literal, in the sense that one of the bases 2/8/10/16 is chosen depending on which prefix if any is used. Ifbase
is 0, no prefix is used, and there is more than one digit, the leading digit cannot be 0; this is to avoid confusion between octal and decimal. The magnitude of the number represented by the string must be within the allowed range for the int type.
x
is any other type, or if the value is a string not satisfying the above format. Unlike Python's int()
function, this function does not allow zero arguments, and does not allow extraneous whitespace for string arguments.Examples:
int("123") == 123 int("-123") == -123 int("+123") == 123 int("FF", 16) == 255 int("0xFF", 16) == 255 int("10", 0) == 10 int("-0x10", 0) == -16
Parameters
Parameter | Description |
---|---|
x
|
The string to convert. |
base
|
The base used to interpret a string value; defaults to 10. Must be between 2 and 36 (inclusive), or 0 to detect the base as if |
len
int len(x)Returns the length of a string, sequence (such as a list or tuple), dict, or other iterable.
Parameters
Parameter | Description |
---|---|
x
|
The value whose length to report. |
list
list list(x=[])Returns a new list with the same elements as the given iterable value.
list([1, 2]) == [1, 2] list((2, 3, 2)) == [2, 3, 2] list({5: "a", 2: "b", 4: "c"}) == [5, 2, 4]
Parameters
Parameter | Description |
---|---|
x
|
The object to convert. |
max
unknown max(*args)Returns the largest one of all given arguments. If only one argument is provided, it must be a non-empty iterable.It is an error if elements are not comparable (for example int with string).
max(2, 5, 4) == 5 max([5, 6, 3]) == 6
Parameters
Parameter | Description |
---|---|
args
|
The elements to be checked. |
min
unknown min(*args)Returns the smallest one of all given arguments. If only one argument is provided, it must be a non-empty iterable. It is an error if elements are not comparable (for example int with string).
min(2, 5, 4) == 2 min([5, 6, 3]) == 3
Parameters
Parameter | Description |
---|---|
args
|
The elements to be checked. |
None print(sep=" ", *args)Prints
args
as debug output. It will be prefixed with the string "DEBUG"
and the location (file and line number) of this call. The exact way in which the arguments are converted to strings is unspecified and may change at any time. In particular, it may be different from (and more detailed than) the formatting done by str()
and repr()
.Using print
in production code is discouraged due to the spam it creates for users. For deprecations, prefer a hard error using fail()
whenever possible.
Parameters
Parameter | Description |
---|---|
sep
|
The separator string between the objects, default is space (" "). |
args
|
The objects to print. |
provider
Provider provider(doc='', *, fields=None)Creates a declared provider 'constructor'. The return value of this function can be used to create "struct-like" values. Example:
data = provider() d = data(x = 2, y = 3) print(d.x + d.y) # prints 5
See Rules (Providers) for a comprehensive guide on how to use providers.
Parameters
Parameter | Description |
---|---|
doc
|
A description of the provider that can be extracted by documentation generating tools. |
fields
|
If specified, restricts the set of allowed fields.
|
range
sequence range(start_or_stop, stop_or_none=None, step=1)Creates a list where items go from
start
to stop
, using a step
increment. If a single argument is provided, items will range from 0 to that element.range(4) == [0, 1, 2, 3] range(3, 9, 2) == [3, 5, 7] range(3, 0, -1) == [3, 2, 1]
Parameters
Parameter | Description |
---|---|
start_or_stop
|
Value of the start element if stop is provided, otherwise value of stop and the actual start is 0 |
stop_or_none
|
optional index of the first item not to be included in the resulting list; generation of the list stops before |
step
|
The increment (default is 1). It may be negative. |
register_execution_platforms
None register_execution_platforms(*platform_labels)Register an already-defined platform so that Bazel can use it as an execution platform during toolchain resolution.
Parameters
Parameter | Description |
---|---|
platform_labels
|
The labels of the platforms to register. |
None
.
register_toolchains
None register_toolchains(*toolchain_labels)Register an already-defined toolchain so that Bazel can use it during toolchain resolution. See examples of defining and registering toolchains.
Parameters
Parameter | Description |
---|---|
toolchain_labels
|
The labels of the toolchains to register. |
None
.
repository_rule
function repository_rule(implementation, *, attrs=None, local=False, environ=[], configure=False, remotable=False, doc='')Creates a new repository rule. Store it in a global value, so that it can be loaded and called from the WORKSPACE file.
Parameters
Parameter | Description |
---|---|
implementation
|
the function that implements this rule. Must have a single parameter, |
attrs
|
dictionary to declare all the attributes of the rule. It maps from an attribute name to an attribute object (see attr module). Attributes starting with |
local
|
Indicate that this rule fetches everything from the local system and should be reevaluated at every fetch. |
environ
|
Provides a list of environment variable that this repository rule depends on. If an environment variable in that list change, the repository will be refetched. |
configure
|
Indicate that the repository inspects the system for configuration purpose |
remotable
|
Experimental. This parameter is experimental and may change at any time. Please do not depend on it. It may be enabled on an experimental basis by setting |
doc
|
A description of the repository rule that can be extracted by documentation generating tools. |
repr
string repr(x)Converts any object to a string representation. This is useful for debugging.
repr("ab") == '"ab"'
Parameters
Parameter | Description |
---|---|
x
|
The object to convert. |
reversed
list reversed(sequence)Returns a list that contains the elements of the original sequence in reversed order.
reversed([3, 5, 4]) == [4, 5, 3]
Parameters
Parameter | Description |
---|---|
sequence
|
The sequence (list or tuple) to be reversed. |
rule
function rule(implementation, test=False, attrs=None, outputs=None, executable=False, output_to_genfiles=False, fragments=[], host_fragments=[], _skylark_testable=False, toolchains=[], incompatible_use_toolchain_transition=False, doc='', *, provides=[], exec_compatible_with=[], analysis_test=False, build_setting=None, cfg=None, exec_groups=None)Creates a new rule, which can be called from a BUILD file or a macro to create targets.
Rules must be assigned to global variables in a .bzl file; the name of the global variable is the rule's name.
Test rules are required to have a name ending in _test
, while all other rules must not have this suffix. (This restriction applies only to rules, not to their targets.)
Parameters
Parameter | Description |
---|---|
implementation
|
the Starlark function implementing this rule, must have exactly one parameter: ctx. The function is called during the analysis phase for each instance of the rule. It can access the attributes provided by the user. It must create actions to generate all the declared outputs. |
test
|
Whether this rule is a test rule, that is, whether it may be the subject of a |
attrs
|
dictionary to declare all the attributes of the rule. It maps from an attribute name to an attribute object (see attr module). Attributes starting with |
outputs
|
Deprecated. This parameter is deprecated and will be removed soon. Please do not depend on it. It is disabled with A schema for defining predeclared outputs. Unlike The value of this argument is either a dictionary or a callback function that produces a dictionary. The callback works similar to computed dependency attributes: The function's parameter names are matched against the rule's attributes, so for example if you pass Each entry in the dictionary creates a predeclared output where the key is an identifier and the value is a string template that determines the output's label. In the rule's implementation function, the identifier becomes the field name used to access the output's
In practice, the most common substitution placeholder is |
executable
|
Whether this rule is considered executable, that is, whether it may be the subject of a |
output_to_genfiles
|
If true, the files will be generated in the genfiles directory instead of the bin directory. Unless you need it for compatibility with existing rules (e.g. when generating header files for C++), do not set this flag. |
fragments
|
List of names of configuration fragments that the rule requires in target configuration. |
host_fragments
|
List of names of configuration fragments that the rule requires in host configuration. |
_skylark_testable
|
(Experimental) |
toolchains
|
If set, the set of toolchains this rule requires. Toolchains will be found by checking the current platform, and provided to the rule implementation via |
incompatible_use_toolchain_transition
|
If set, this rule will use the toolchain transition for toolchain dependencies. This is ignored if the --incompatible_use_toolchain_transition flag is set. |
doc
|
A description of the rule that can be extracted by documentation generating tools. |
provides
|
A list of providers that the implementation function must return. It is an error if the implementation function omits any of the types of providers listed here from its return value. However, the implementation function may return additional providers not listed here. Each element of the list is an |
exec_compatible_with
|
A list of constraints on the execution platform that apply to all targets of this rule type. |
analysis_test
|
If true, then this rule is treated as an analysis test. Note: Analysis test rules are primarily defined using infrastructure provided in core Starlark libraries. See Testing for guidance. If a rule is defined as an analysis test rule, it becomes allowed to use configuration transitions defined using analysis_test_transition on its attributes, but opts into some restrictions:
|
build_setting
|
If set, describes what kind of |
cfg
|
If set, points to the configuration transition the rule will apply to its own configuration before analysis. |
exec_groups
|
Experimental. This parameter is experimental and may change at any time. Please do not depend on it. It may be enabled on an experimental basis by setting |
select
unknown select(x, no_match_error='')
select()
is the helper function that makes a rule attribute configurable. See build encyclopedia for details.
Parameters
Parameter | Description |
---|---|
x
|
A dict that maps configuration conditions to values. Each key is a label string that identifies a config_setting instance. |
no_match_error
|
Optional custom error to report if no condition matches. |
sorted
list sorted(iterable, *, key=None, reverse=False)Sort a collection. Elements should all belong to the same orderable type, they are sorted by their value (in ascending order). It is an error if elements are not comparable (for example int with string).
sorted([3, 5, 4]) == [3, 4, 5]
Parameters
Parameter | Description |
---|---|
iterable
|
The iterable sequence to sort. |
key
|
An optional function applied to each element before comparison. |
reverse
|
Return results in descending order. |
str
string str(x)Converts any object to string. This is useful for debugging.
str("ab") == "ab" str(8) == "8"
Parameters
Parameter | Description |
---|---|
x
|
The object to convert. |
tuple
tuple tuple(x=())Returns a tuple with the same elements as the given iterable value.
tuple([1, 2]) == (1, 2) tuple((2, 3, 2)) == (2, 3, 2) tuple({5: "a", 2: "b", 4: "c"}) == (5, 2, 4)
Parameters
Parameter | Description |
---|---|
x
|
The object to convert. |
type
string type(x)Returns the type name of its argument. This is useful for debugging and type-checking. Examples:
type(2) == "int" type([1]) == "list" type(struct(a = 2)) == "struct"This function might change in the future. To write Python-compatible code and be future-proof, use it only to compare return values:
if type(x) == type([]): # if x is a list
Parameters
Parameter | Description |
---|---|
x
|
The object to check type of. |
workspace
None workspace(name, managed_directories={})
This function can only be used in a WORKSPACE
file and must be declared before all other functions in the WORKSPACE
file. Each WORKSPACE
file should have a workspace
function.
Sets the name for this workspace. Workspace names should be a Java-package-style description of the project, using underscores as separators, e.g., github.com/bazelbuild/bazel should use com_github_bazelbuild_bazel.
This name is used for the directory that the repository's runfiles are stored in. For example, if there is a runfile foo/bar
in the local repository and the WORKSPACE file contains workspace(name = 'baz')
, then the runfile will be available under mytarget.runfiles/baz/foo/bar
. If no workspace name is specified, then the runfile will be symlinked to bar.runfiles/foo/bar
.
Remote repository rule names must be valid workspace names. For example, you could have maven_jar(name = 'foo')
, but not maven_jar(name = 'foo.bar')
, as Bazel would attempt to write a WORKSPACE file for the maven_jar
containing workspace(name = 'foo.bar')
.
Parameters
Parameter | Description |
---|---|
name
|
the name of the workspace. Names must start with a letter and can only contain letters, numbers, and underscores. |
managed_directories
|
Dict (strings to list of strings) for defining the mappings between external repositories and relative (to the workspace root) paths to directories they incrementally update. Managed directories must be excluded from the source tree by listing them (or their parent directories) in the .bazelignore file. |
None
.
zip
list zip(*args)Returns a
list
of tuple
s, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The list has the size of the shortest input. With a single iterable argument, it returns a list of 1-tuples. With no arguments, it returns an empty list. Examples:zip() # == [] zip([1, 2]) # == [(1,), (2,)] zip([1, 2], [3, 4]) # == [(1, 3), (2, 4)] zip([1, 2], [3, 4, 5]) # == [(1, 3), (2, 4)]
Parameters
Parameter | Description |
---|---|
args
|
lists to zip. |