Documentation

Globals

Objects, functions and modules registered in the global environment.

Actions

provider Actions()

(Note: This is a provider type. Don't instantiate it yourself; use it to retrieve a provider object from a Target.)

Provides access to the actions generated by a rule. There is one field, by_file, which is a dictionary from an output of the rule to its corresponding generating action.

This is designed for testing rules, and should not be accessed outside of test logic. This provider is only available for targets generated by rules that have _skylark_testable set to True.

DefaultInfo

provider DefaultInfo()

A provider that is provided by every rule, even if it iss not returned explicitly. A DefaultInfo accepts all special parameters that can be returned from rule implementation function in a struct, which are runfiles, data_runfiles, default_runfiles, output_groups, instrumented_files, and all providers that are available on built-in rules. Each instance of the default provider contains the following standard fields: data_runfiles, default_runfiles, files, and files_to_run. The values of these fields are equivalent to the values of the corresponding fields of the target the default provider belongs to.

False

bool

Literal for the boolean false.

None

None

Literal for the None value.

PACKAGE_NAME

string

The name of the package being evaluated. For example, in the BUILD file some/package/BUILD, its value will be some/package. If the BUILD file calls a function defined in a .bzl file, PACKAGE_NAME will match the caller BUILD file package. In .bzl files, do not access PACKAGE_NAME at the file-level (outside of functions), either directly or by calling a function at the file-level that accesses PACKAGE_NAME (PACKAGE_NAME is only defined during BUILD file evaluation).Here is an example of a .bzl file:
# a = PACKAGE_NAME  # not allowed outside functions
def extension():
  return PACKAGE_NAME
In this case, extension() can be called from a BUILD file (even indirectly), but not in a file-level expression in the .bzl file. When implementing a rule, use ctx.label to know where the rule comes from.

REPOSITORY_NAME

string

The name of the repository the rule or build extension is called from. For example, in packages that are called into existence by the WORKSPACE stanza local_repository(name='local', path=...) it will be set to @local. In packages in the main repository, it will be empty. It can only be accessed in functions (transitively) called from BUILD files, i.e. it follows the same restrictions as PACKAGE_NAME

True

bool

Literal for the boolean true.

all

bool all(elements)

Returns true if all elements evaluate to True or if the collection is empty.

Parameters

Parameter Description
elements

A string or a collection of elements.

any

bool any(elements)

Returns true if at least one element evaluates to True.

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=[])

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

function

the function implementing this aspect. Must have two parameters: Target (the target to which the aspect is applied) and ctx. Attributes of the target are available via ctx.rule field. The function is called during the analysis phase for each application of an aspect to a target.

attr_aspects

sequence of strings

List of attribute names. The aspect propagates along dependencies specified by attributes of a target with this name. The list can also contain a single string '*': in that case aspect propagates along all dependencies of a target.

attrs

dict

dictionary to declare all the attributes of the aspect. It maps from an attribute name to an attribute object (see attr module). Aspect attributes are available to implementation function as fields of ctx parameter. Implicit attributes starting with _ must have default values, and have type label or label_list. Explicit attributes must have type string, and must use the values restriction. If explicit attributes are present, the aspect can only be used with rules that have attributes of the same name and type, with valid values.

required_aspect_providers

sequence

provides

sequence

fragments

sequence of strings

List of names of configuration fragments that the aspect requires in target configuration.

host_fragments

sequence of strings

List of names of configuration fragments that the aspect requires in host configuration.

bool

bool bool(x)

Constructor for the bool type. It returns False if the object is None, False, an empty string, the number 0, or an empty collection. Otherwise, it returns True.

Parameters

Parameter Description
x

The variable to convert.

depset

depset depset(items=[], order="default")

Creates a depset. In the case that items is an iterable, its contents become the direct elements of the depset, with their left-to-right order preserved, and the depset has no transitive elements. In the case that items is a depset, it is made the sole transitive element of the new depset, and no direct elements are added. In the second case the given depset's order must match the order param or else one of the two must be "default". See the Depsets overview for more information.

Parameters

Parameter Description
items

An iterable whose items become the direct elements of the new depset, in left-to-right order; or alternatively, a depset that becomes the transitive element of the new depset.

order

string

The traversal strategy for the new depset. See here for the possible values.

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. Note that the iteration order for dictionaries is deterministic but unspecified, and not necessarily related to the order in which keys are given to this function.

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 strings: the names of the attributes and methods of the parameter object.

Parameters

Parameter Description
x

The object to check.

enumerate

list enumerate(list)

Returns a list of pairs (two-element tuples), with the index (int) and the item from the input list.
enumerate([24, 21, 84]) == [(0, 24), (1, 21), (2, 84)]

Parameters

Parameter Description
list

sequence

input list.

fail

None fail(msg, 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

string

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. Built-in methods cannot currently be retrieved in this way; doing so will result in an error if a default is not given. 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

string

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

String value to hash.

int

int int(x, base=10)

Converts a value to int. If the argument is a string, it is converted using the given base and raises an error if the conversion fails. The base can be between 2 and 36 (inclusive) and defaults to 10. The value can be prefixed with 0b/0o/ox to represent values in base 2/8/16. If such a prefix is present, a base of 0 can be used to automatically determine the correct base:
int("0xFF", 0) == int("0xFF", 16) == 255
If the argument is a bool, it returns 0 (False) or 1 (True). If the argument is an int, it is simply returned.
int("123") == 123

Parameters

Parameter Description
x

The string to convert.

base

int

The base of the string.

len

int len(x)

Returns the length of a string, list, tuple, depset, or dictionary.

Parameters

Parameter Description
x

The object to check length of.

list

list list(x)

Converts a collection (e.g. list, tuple or dictionary) to a list.
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.

Parameters

Parameter Description
args

sequence

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.

Parameters

Parameter Description
args

sequence

The elements to be checked.

print

None print(*args, *, sep=' ')

Prints args as output. It will be prefixed with the string "WARNING" and the location (file and line number) of this call. It can be used for debugging.

Using print in production code is discouraged due to the spam it creates for users. For deprecations, prefer a hard error using fail() when possible.

Parameters

Parameter Description
sep

string

The separator string between the objects, default is space (" ").

args

The objects to print.

provider

provider provider()

Creates a declared provider 'constructor'. The return value of thisfunction can be used to create "struct-like" values. Example:
data = provider()
d = data(x = 2, y = 3)
return d.x + d.y # returns 5

range

list 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

int

Value of the start element if stop is provided, otherwise value of stop and the actual start is 0

stop_or_none

int

optional index of the first item not to be included in the resulting list; generation of the list stops before stop is reached.

step

int

The increment (default is 1). It may be negative.

repository_rule

function repository_rule(implementation, *, attrs=None, local=False, environ=[])

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

function

the function implementing this rule, has to have exactly one parameter: repository_ctx. The function is called during loading phase for each instance of the rule.

attrs

dict

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 _ are private, and can be used to add an implicit dependency on a label to a file (a repository rule cannot depend on a generated artifact). The attribute name is implicitly added and must not be specified.

local

bool

Indicate that this rule fetches everything from the local system and should be reevaluated at every fetch.

environ

sequence of strings

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.

repr

string repr(x)

Converts any object to a string representation. This is useful for debugging.
str("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.

Parameters

Parameter Description
sequence

The sequence to be reversed (string, list or tuple).

rule

function rule(implementation, test=False, attrs=None, outputs=None, executable=False, output_to_genfiles=False, fragments=[], host_fragments=[], _skylark_testable=False)

Creates a new rule. Store it in a global value, so that it can be loaded and called from BUILD files.

Parameters

Parameter Description
implementation

function

the 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

bool

Whether this rule is a test rule. If True, the rule must end with _test (otherwise it must not), and there must be an action that generates ctx.outputs.executable.

attrs

dict

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 _ are private, and can be used to add an implicit dependency on a label. The attribute name is implicitly added and must not be specified. Attributes visibility, deprecation, tags, testonly, and features are implicitly added and cannot be overriden.

outputs

dict

outputs of this rule. It is a dictionary mapping from string to a template name. For example: {"ext": "%{name}.ext"}.
The dictionary key becomes an attribute in ctx.outputs. Similar to computed dependency rule attributes, you can also specify the name of a function that returns the dictionary. This function can access all rule attributes that are listed as parameters in its function signature. For example, outputs = _my_func with def _my_func(srcs, deps): has access to the attributes 'srcs' and 'deps' (if defined).

executable

bool

whether this rule is marked as executable or not. If True, there must be an action that generates ctx.outputs.executable.

output_to_genfiles

bool

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

sequence of strings

List of names of configuration fragments that the rule requires in target configuration.

host_fragments

sequence of strings

List of names of configuration fragments that the rule requires in host configuration.

_skylark_testable

bool

(Experimental)

If true, this rule will expose its actions for inspection by rules that depend on it via an Actions provider. The provider is also available to the rule itself by calling ctx.created_actions().

This should only be used for testing the analysis-time behavior of Skylark rules. This flag may be removed in the future.

select

unknown select(x, no_match_error='')

Creates a SelectorValue from the dict parameter.

Parameters

Parameter Description
x

dict

The parameter to convert.

no_match_error

string

Optional custom error to report if no condition matches.

set

depset set(items=[], order="default")

A temporary alias for depset. Deprecated in favor of depset.

Parameters

Parameter Description
items

Same as for depset.

order

string

Same as for depset.

sorted

list sorted(self)

Sort a collection. Elements should all belong to the same orderable type, they are sorted by their value (in ascending order).

Parameters

Parameter Description
self

This collection.

str

string str(x)

Converts any object to string. This is useful for debugging.
str("ab") == "ab"

Parameters

Parameter Description
x

The object to convert.

struct

struct struct(**kwargs)

Creates an immutable struct using the keyword arguments as attributes. It is used to group multiple values together. Example:
s = struct(x = 2, y = 3)
return s.x + getattr(s, "y")  # returns 5

Parameters

Parameter Description
kwargs

the struct attributes.

tuple

tuple tuple(x)

Converts a collection (e.g. list, tuple or dictionary) to a tuple.
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

sequence workspace(name)

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. Names must start with a letter and can only contain letters, numbers, and underscores.

Parameters

Parameter Description
name

string

the name of the workspace.

zip

list zip(*args)

Returns a list of tuples, 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.