Language | Binary rules | Library rules | Test rules | Other rules | |
---|---|---|---|---|---|
Android | android_binary | android_library | android_test | android_device | android_manifest_merge android_resources |
Java | java_binary | java_import java_library |
java_test | java_plugin java_wrap_cc |
|
Shell | sh_binary | sh_library | sh_test | ||
Rules that do not apply to a specific programming language | |||||
General | filegroup | test_suite | genrule |
This section defines various terms and concepts that are common to many functions or build rules below.
Certain string attributes of some rules are split into multiple words according to the tokenization rules of the Bourne shell: unquoted spaces delimit separate words, and single- and double-quotes characters and backslashes are used to prevent tokenization.
Those attributes that are subject to this tokenization are explicitly indicated as such in their definitions in this document.
Attributes subject to "Make" variable expansion and Bourne shell
tokenization are typically used for passing arbitrary options to
compilers and other tools, such as the copts
attribute
of cc_library
, or the javacopts
attribute of
java_library
. Together these substitutions allow a
single string variable to expand into a configuration-specific list
of option words.
Some string attributes of a very few rules are subject to label
expansion: if those strings contain a valid build label as a
substring, such as //mypkg:target
, and that label is a
declared prerequisite of the current rule, it is expanded into the
pathname of the file represented by the target //mypkg:target
.
Example attributes include the cmd
attribute of
genrule, and the linkopts
attribute
of cc_library
. The details may vary significantly in
each case, over such issues as: whether relative labels are
expanded; how labels that expand to multiple files are
treated, etc. Consult the rule attribute documentation for
specifics.
This section describes attributes that are common to all build rules.
Please note that it is an error to list the same label twice in a list of
labels attribute.
deps
:
A list of dependencies of this rule.
(List of labels; optional)deps
are specific to the kind of this rule,
and the rule-specific documentation below goes into more detail.
At a minimum, though, the targets named via deps
will
appear in the *.runfiles
area of this rule, if it has
one.
Most often, a deps
dependency is used to allow one
module to use symbols defined in another module written in the
same programming language and separately compiled. Cross-language
dependencies are also permitted in many cases: for example,
a java_library
rule may depend on C++ code in
a cc_library
rule, by declaring the latter in
the deps
attribute. See the definition
of dependencies for more
information.
Almost all rules permit a deps
attribute, but where
this attribute is not allowed, this fact is documented under the
specific rule.
data
:
The list of files needed by this rule at runtime.
(List of labels; optional)data
attribute will appear in
the *.runfiles
area of this rule, if it has one. This
may include data files needed by a binary or library, or other
programs needed by it. See the
data dependencies section for more
information about how to depend on and use data files.
Almost all rules permit a data
attribute, but where
this attribute is not allowed, this fact is documented under the
specific rule.
deprecation
:
(String; optional)
This attribute has no effect on the way things are built, but it
may affect a build tool's diagnostic output. The build tool issues a
warning when a rule with a deprecation
attribute is
depended upon by another rule.
Intra-package dependencies are exempt from this warning, so that, for example, building the tests of a deprecated rule does not encounter a warning.
If a deprecated rule depends on another deprecated rule, no warning message is issued.
Once people have stopped using it, the package can be removed or marked as
obsolete
.
distribs
:
(List of strings; optional)BUILD
-file scope defaults defined by the
distribs()
directive.licenses
:
(List of strings; optional)BUILD
-file scope defaults defined by the
licenses()
directive.obsolete
:
(Boolean; optional; default 0)
As a transition, one can first mark a package as in
deprecation
.
This attribute is useful when you want to prevent a target from being used but are yet not ready to delete the sources.
testonly
:
(Boolean; optional; default 0 except as noted)Equivalently, a rule that is not testonly
is not allowed to
depend on any rule that is testonly
.
Tests (*_test
rules)
and test suites (test_suite rules)
are testonly
by default.
By virtue of
default_testonly
,
targets under javatests
are testonly
by default.
This attribute is intended to mean that the target should not be contained in binaries that are released to production.
Because testonly is enforced at build time, not run time, and propagates virally through the dependency tree, it should be applied judiciously. For example, stubs and fakes that are useful for unit tests may also be useful for integration tests involving the same binaries that will be released to production, and therefore should probably not be marked testonly. Conversely, rules that are dangerous to even link in, perhaps because they unconditionally override normal behavior, should definitely be marked testonly.
visibility
:
(List of labels; optional; default private)The visibility
attribute on a rule controls whether
the rule can be used by other packages. Rules are always visible to
other rules declared in the same package.
There are five forms (and one temporary form) a visibility label can take:
['//visibility:public']
: Anyone can use this rule.['//visibility:private']
: Only rules in this package
can use this rule. Rules in javatests/foo/bar
can always use rules in java/foo/bar
.
['//some/package:__pkg__', '//other/package:__pkg__']
:
Only rules in some/package
and other/package
(defined in some/package/BUILD
and
other/package/BUILD
) have access to this rule. Note that
sub-packages do not have access to the rule; for example,
//some/package/foo:bar
or
//other/package/testing:bla
wouldn't have access.
__pkg__
is a special target and must be used verbatim.
It represents all of the rules in the package.
['//project:__subpackages__', '//other:__subpackages__']
:
Only rules in packages project
or other
or
in one of their sub-packages have access to this rule. For example,
//project:rule
, //project/library:lib
or
//other/testing/internal:munge
are allowed to depend on
this rule (but not //independent:evil
)
['//some/package:my_package_group']
:
A package group is
a named set of package names. Package groups can also grant access rights
to entire subtrees, e.g.//myproj/...
.
The visibility specifications of //visibility:public
,
//visibility:private
and
//visibility:legacy_public
can not be combined with any other visibility specifications.
A visibility specification may contain a combination of package labels
(i.e. //foo:__pkg__) and package_groups.
If a rule does not specify the visibility attribute,
the default_visibility
attribute of the package
statement in the BUILD file containing the rule is used
(except exports_files and
cc_public_library, which always default to
public).
Example:
File //frobber/bin/BUILD
:
# This rule is visible to everyone java_binary( name = "executable", visibility = ["//visibility:public"], deps = [":library"], ) # This rule is visible only to rules declared in the same package java_library( name = "library", visibility = ["//visibility:private"], ) # This rule is visible to rules in package //object and //noun java_library( name = "subject", visibility = [ "//noun:__pkg__", "//object:__pkg__", ], ) # See package group //frobber:friends (below) for who can access this rule. java_library( name = "thingy", visibility = ["//frobber:friends"], )
File //frobber/BUILD
:
# This is the package group declaration to which rule //frobber/bin:thingy refers. # # Our friends are packages //frobber, //fribber and any subpackage of //fribber. package_group( name = "friends", packages = [ "//fribber/...", "//frobber", ], )
This section describes attributes that are common to all test rules.
args
:
Add these arguments to the --test_arg
when executed by bazel test
.
(List of strings; optional; subject to
"Make variable" substitution and
Bourne shell tokenization)--test_arg
values
specified on the bazel test
command line.flaky
:
Marks test as flaky. (Boolean; optional)local
:
Forces the test to be run locally. (Boolean; optional)tags=["local"]
).shard_count
:
Specifies the number of parallel shards
to use to run the test. (Non-negative integer less than or equal to 50;
optional)size
:
How "heavy" the test is
(String "enormous", "large" "medium" or "small",
default is "medium")timeout
:
How long the test is
normally expected to run before returning.
(String "eternal", "long", "moderate", or "short"
with the default derived from a test's size attribute)This section describes attributes that are common to all binary rules.
args
:
Add these arguments to the target when executed by
bazel run
.
(List of strings; optional; subject to
"Make variable" substitution and
Bourne shell tokenization)bazel run
command line.
Most binary rules permit an args
attribute, but where
this attribute is not allowed, this fact is documented under the
specific rule.
output_licenses
:
The licenses of the output files that this binary generates.
(List of strings; optional)tools
attribute of
a genrule
), this license declaration is used rather
than the union of the licenses of its transitive closure. This
argument is useful when a binary is used as a tool during the
build of a rule, and it is not desirable for its license to leak
into the license of that rule. If this attribute is missing, the
license computation proceeds as if the host dependency was a
regular dependency.
WARNING: in some cases (specifically, in genrules) the build tool cannot guarantee that the binary referenced by this attribute is actually used as a tool, and is not, for example, copied to the output. In these cases, it is the responsibility of the user to make sure that this is true.
When you define a build rule in a BUILD file, you are explicitly
declaring a new, named rule target in a package. Many build rule
functions also implicitly entail one or more output file
targets, whose contents and meaning are rule-specific.
For example, when you explicitly declare a
java_binary(name='foo', ...)
rule, you are also
implicitly declaring an output file
target foo_deploy.jar
as a member of the same package.
(This particular target is a self-contained Java archive suitable
for deployment.)
Implicit output targets are first-class members of the build
target graph. Just like other targets, they are built on demand,
either when specified in the top-level built command, or when they
are necessary prerequisites for other build targets. They can be
referenced as dependencies in BUILD files, and can be observed in
the output of analysis tools such as bazel query
.
For each kind of build rule, the rule's documentation contains a special section detailing the names and contents of any implicit outputs entailed by a declaration of that kind of rule.
Please note an important but somewhat subtle distinction between the
two namespaces used by the build system. Build
labels identify targets,
which may be rules or files, and file targets may be divided into
either source (or input) file targets and derived (or output) file
targets. These are the things you can mention in BUILD files,
build from the command-line, or examine using bazel query
;
this is the target namespace. Each file target corresponds
to one actual file on disk (the "file system namespace"); each rule
target may correspond to zero, one or more actual files on disk.
There may be files on disk that have no corresponding target; for
example, .o
object files produced during C++ compilation
cannot be referenced from within BUILD files or from the command line.
In this way, the build tool may hide certain implementation details of
how it does its job. This is explained more fully in
the BUILD Concept Reference.
A *_binary
rule compiles an application. This might be
an executable, a .jar
file, and/or a collection of scripts.
android_binary(name, deps, srcs, resources, aaptopts, debug_key, deprecation, dexopts, distribs, licenses, obsolete, proguard_generate_mapping, proguard_specs, strict_android_deps, tags, testonly, visibility)
Produces Android application package files (.apk).
name.apk
: An Android application
package file signed with debug keys and
zipaligned, it could be used to develop and debug your application.
You cannot release your application when signed with the debug keys.name_unsigned.apk
: An unsigned version of the
above file that could be signed with the release keys before release to
the public.
name_deploy.jar
: A Java archive containing the
transitive closure of this target.
The deploy jar contains all the classes that would be found by a classloader that searched the runtime classpath of this target from beginning to end.
name_proguard.jar
: A Java archive containing
the result of running ProGuard on the
name_deploy.jar
.
This output is only produced if
proguard_specs attribute is
specified.
name_proguard.map
: A mapping file result of
running ProGuard on the name_deploy.jar
.
This output is only produced if
proguard_specs attribute is
specified and
proguard_generate_mapping
is set.
name
: A unique name for this rule. (Name; required)deps
:
The list of other libraries to be linked in to the binary target.
(List of labels; optional)android_library
,
android_idl
, java_library
with
android
constraint and cc_library
wrapping or
producing .so
native libraries for the Android target platform.
srcs
:
The list of source files that are processed to create the target.
(List of labels; optional)
srcs
files of type .java
are compiled.
For readability's sake, it is not good to put the name of a
generated .java
source file into the srcs
.
Instead, put the depended-on rule name in the srcs
, as
described below.
srcs
files of type .srcjar
are unpacked and
compiled. (This is useful if you need to generate a set of .java files with
a genrule or build extension.)
This rule currently forces source and class compatibility with Java 6.
srcs
files of type .jar
are linked in.
(This is useful if you have third-party .jar
files
with no source.)
resources
:
The android_resources
target corresponding to this binary.
(Label; required)aaptopts
:
Additional command-line flags for the aapt tool when generating apk. This
is only used if this rule uses other android_library project with resources.
(List of strings; optional; subject to
"Make variable" substitution and
Bourne shell tokenization)
debug_key
:
File containing debug keystore to be used to sign debug apk.
(Label; optional).
Points to a location of debug keystore file that is different than default
debug key. Usually you do not want to use key other than default key, so
this attribute should be omitted.
dexopts
:
Additional command-line flags for the dx tool when generating classes.dex.
(List of strings; optional; subject to
"Make variable" substitution and
Bourne shell tokenization)proguard_generate_mapping
:
Whether to generate Proguard mapping file.
(Boolean; optional, default is 0)proguard_specs
is
specified. This file will list the mapping between the original and
obfuscated class, method, and field names.
WARNING: If you use this attribute, your Proguard specification
should contain neither -dontobfuscate
nor -printmapping
.
.
proguard_specs
:
Files to be used as Proguard specification.
(List of labels; optional)strict_android_deps
:
(Integer; optional; default is -1 (inherited))By default, javac will perform checks when compiling the java sources
in this library to verify that all explicitly mentioned classes were loaded
from directly specified deps
(rather than from the transitive
closure of all deps
), the transitive closure of
, and the transitive closure of
srcs
-less librariesexports
. This default can be overridden when set to 0.
java_binary(name, deps, srcs, data, resources, args, classpath_resources, create_executable, deploy_env, deploy_manifest_lines, deprecation, distribs, javacopts, jvm_flags, launcher, licenses, main_class, obsolete, output_licenses, plugins, runtime_deps, stamp, swigdeps, tags, testonly, use_testrunner, visibility)
Builds a Java archive ("jar file"), plus a wrapper shell script with the same name as the rule. The wrapper shell script uses a classpath that includes, among other things, a jar file for each library on which the binary depends.
name.jar
: A Java archive, containing the
class files and other resources corresponding to the binary's
direct dependencies.
name-src.jar
: An archive containing the sources ("source jar").name_deploy.jar
: A Java archive suitable
for deployment (only built if explicitly requested).
Building the <java_binary_name>_deploy.jar
target for your rule creates a self-contained
<java_binary_name>_deploy.jar
file with a manifest that
allows it to be run with the java -jar
command or with the
wrapper script's --singlejar
option. Using the wrapper script
is preferred, as it also passes the JVM
flags and the options to load SWIG libraries.
The deploy jar contains all the classes that would be found by a classloader that searched the classpath from the binary's wrapper script from beginning to end. It also contains the native libraries needed for SWIG dependencies; these are automatically unpacked and loaded into the JVM at runtime.
name_deploy-src.jar
: An archive containing the sources collected from
the transitive closure of the target. These will matches the classes in the
deploy.jar
, except for cases where jars have no matching source jar.name
: A unique name for this rule. (Name; required) Main.java
, then your name should
be Main
.
deps
:
The list of other libraries to be linked in to the target.
(List of labels; optional)deps
at Attributes common to all build
rules.
These can be
java_library
,
cc_library
, or
java_wrap_cc
rules.
If this rule has no srcs
, then it should have
only one deps
, the java_library
containing the .java
file suggested by this
rule's name
.
The following code snippet illustrates a common mistake:
java_binary( name = "DontDoThis", srcs = [ ...,"GeneratedJavaFile.java"
, # a generated .java file ], deps = [":generating_rule",
], # rule that generates that file )
This is better:
java_binary( name = "DoThisInstead", srcs = [ ..., ":generating_rule", ], )
More examples are below.
Why list the generating rule instead of file names in srcs
?
Because it is more resilient to future changes: if the generating rule
generates different files in the future, you only need to fix one
place--the outs
of the generating rule. Why not list the
generating rule in deps
? Because it is a no-op.
srcs
:
The list of source files that are processed to create the target.
(List of labels; required excepting
special cases described below)
srcs
files of type .java
are compiled.
For readability's sake, it is not good to put the name of a
generated .java
source file into the srcs
.
Instead, put the depended-on rule name in the srcs
, as
described below.
srcs
files of type .srcjar
are unpacked and
compiled. (This is useful if you need to generate a set of .java files with
a genrule or build extension.)
srcs
files of type .jar
are linked in.
(This is useful if you have third-party .jar
files
with no source.)
srcs
files of type .properties
are treated as
resources.
This argument is required, excepting special cases:
main_class
attribute specifies a class on the runtime classpath; oruse_testrunner
argumentresources
:
A list of data files to include in a Java jar.
(List of labels; optional).class
files produced by compilation. All
resources will be
placed in the jar in a directory corresponding to the build package
name, regardless of their original location on the filesystem. Resources
may be source files or derived files.
classpath_resources
:
(optional)
A list of resources that must be located at the root of the java
tree. This was introduced because some third party libraries required
that their resources be found on the classpath as exactly "myconfig.xml".
It is only allowed on binaries and not libraries, due to the danger of
namespace conflicts.
create_executable
:
Whether to build the executable wrapper script or not.
(Boolean; optional; default is 1)main_class
attribute.
deploy_env
:
A list of other java_binary
targets which represent the deployment
environment for this binary. Set this attribute when building a plugin
which will be loaded by another java_binary
.deploy_env
.
deploy_manifest_lines
:
A list of lines to add to the meta-inf/manifest.mf file generated for the
*_deploy.jar
target. The
contents of deploy_manifest_lines
are not subject to
"Make variable" substitution.
javacopts
:
Extra compiler options for this library.
(List of strings; optional; subject to
"Make variable" substitution and
Bourne shell tokenization)
These compiler options are passed to javac after the global compiler options.
jvm_flags
:
A list of flags to
embed in the wrapper script generated for running this binary.
(List of strings; optional; subject to
"Make variable" substitution and
Bourne shell tokenization)"$@"
so you can pass along other
arguments after the classname. However, arguments intended for parsing
by the JVM must be specified before the classname on the command
line. The contents of jvm_flags
are added to the wrapper
script before the classname is listed.
launcher
:
(Label; optional; default is empty.)cc_binary
.
Any cc_binary
that implements the Java Invocation AP can be a launcher
target.
The related
--java_launcher
bazel flag affects only those
java_binary
and java_test
targets that have
not specified a launcher
attribute.
If you build a deploy jar and specify a launcher target through either
this launcher
attribute or --java_launcher
Bazel
flag, then the deploy jar will be a single file that is both (a) a .jar
file that contains the appropriate classes, and (b) the executable
specified by the launcher target.
main_class
:
Name of class with main()
method to use as entry point.
(String) srcs=[...]
list.
Thus, with this attribute one can make an executable from a Java library
that already contains one or more main()
methods.
The value of the
main_class
attribute is a class name, not a source file.
The class must be available at runtime: it may be compiled by this rule
(from srcs
) or provided by direct or transitive dependencies
(through runtime_deps
or deps
). If the class is
unavailable, the binary will fail at runtime; there is no build-time check.
plugins
:
Java compiler plugins to run at compile-time.
(List of labels;
optional)java_plugin
specified in
the plugins attribute will be run whenever
this java_library
is built. A library may also inherit
plugins from dependencies that use
exported_plugins
.
Resources generated by the plugin will be included in the result jar of
the java_library
.
runtime_deps
:
Libraries to make available to the final binary or test at runtime only.
(List of labels; optional)deps
, these will appear on the runtime
classpath, but unlike them, not on the compile-time classpath.
Dependencies needed only at runtime should be here because
dependency-management tools may remove deps not needed at compile time.
Dependency-management tools should ignore targets that appear in both
runtime_deps
and deps
.
stamp
:
Enable link stamping.
(Integer; optional; default is -1)stamp = 1
: Stamp the build information into the
binary. Stamped binaries are only rebuilt when their dependencies
change. Use this if there are tests that depend on the build
information.stamp = 0
: Always replace build information by constant
values. This gives good build result caching.stamp = -1
: Embedding of build information is controlled
by the --[no]stamp Bazel
flag.swigdeps
:
(Boolean; optional; default 1)use_testrunner
:
Use the
You can use this to override the default
behavior. It is unlikely
you will want to do this. One use is for AllTest
rules that are invoked by another rule (to set up a database
before running the tests, for example). The AllTest
rule must be declared as a java_binary
, but should
still use the test runner as its main entry point.
sh_binary(name, deps, srcs, data, args, bash_version, deprecation, distribs, licenses, obsolete, output_licenses, random_tmpdir, tags, testonly, visibility)
The sh_binary
rule is used to declare executable
programs in interpreted languages such as the Bourne shell, or Bash,
Perl, Ruby, etc. (sh_binary
is a double misnomer: its
outputs aren't necessarily either shell programs or binary.) This
rule ensures that all dependencies are built, and appear in
the runfiles
area at execution time. We recommend that you name
your sh_binary()
rules after the name of the script
minus the extension (e.g. .sh
); do not give the rule
and the file the same name.
name.sar
: A self-contained binary (i.e. one that
packages all its dependencies).
name
: A unique name for this rule. (Name; required) foo.sh
, we recommend
that you name the rule foo
, but this is not required.
deps
:
The list of other "library" targets to be aggregated in to this executable program.
(List of labels; optional)deps
at Attributes common to all build rules.
You should use this attribute to list other
sh_library
rules that provide
interpreted program source code depended on by the code in
srcs
.
srcs
:
The shell script.
(A list of labels of length 1; required)data
attribute.
bash_version
:
The version of bash to package with this target's .sar file.
(String; optional; default is "system")"3"
, "4"
, and
"system"
. The first embeds bash 3. The second embeds
bash 4. The third doesn't embed anything, so the script runs with
whatever version is installed on the executing system.
random_tmpdir
:
Whether or not to extract .sar contents to a randomly chosen temp directory.
(Boolean; optional; default is 1)0
, the directory's name is computed from a hash of the
.sar file contents. This saves the need to redo extraction each time
the .sar is run, making startup time potentially much shorter. However,
it also increases the risk of failure due to the system removing files
from the temp dir.
For a simple shell script with no dependencies or data:
sh_binary( name = "foo", srcs = ["foo.sh"], )
A *_library()
rule compiles some sources into a library.
In general, a language_library
rule works like
the corresponding language_binary
rule, but
doesn't generate something executable.
android_library(name, deps, srcs, data, resources, deprecation, distribs, idl_import_root, idl_parcelables, idl_srcs, licenses, neverlink, obsolete, plugins, proguard_specs, strict_android_deps, tags, testonly, visibility)
This rule compiles and archives its sources into a .jar
file.
The Android runtime library android.jar
is implicitly put on
the compilation class path.
libname.jar
: A Java archive.libname-src.jar
: An archive containing the
sources ("source jar").name
: A unique name for this rule. (Name; required)deps
:
The list of other libraries to link against.
(List of labels; optional)android_library
,
java_library
with android
constraint and
cc_library
wrapping or producing .so
native libraries
for the Android target platform.
srcs
:
The list of source files that are processed to create the target.
(List of labels; optional)
srcs
files of type .java
are compiled.
For readability's sake, it is not good to put the name of a
generated .java
source file into the srcs
.
Instead, put the depended-on rule name in the srcs
, as
described below.
srcs
files of type .srcjar
are unpacked and
compiled. (This is useful if you need to generate a set of .java files with
a genrule or build extension.)
This rule currently forces source and class compatibility with Java 6.
srcs
files of type .jar
are linked in.
(This is useful if you have third-party .jar
files
with no source.)
resources
:
The android_resources
target assigned to this library.
(Label; optional)android_binary
depending on this library.
Only an android_resource
rule with the attribute
inline_constants
set to 0 can be used in this case.
idl_import_root
:
Package-relative path to the root of the java package tree containing idl
sources included in this library.
(String; optional)idl_parcelables
:
List of Android IDL definitions to supply as imports.
(List of labels; optional)android_library
target that depends on this library, directly
or via its transitive closure, but will not be translated to Java
or compiled.
Only .aidl
files that correspond directly to
.java
sources in this library should be included (e.g., custom
implementations of Parcelable), otherwise idl_srcs
should be
used.
idl_srcs
:
List of Android IDL definitions to translate to Java interfaces.
(List of labels; optional)srcs
.
These files will be made available as imports for any
android_library
target that depends on this library, directly
or via its transitive closure.
neverlink
:
Only use this library for compilation and not at runtime.
(Boolean; optional; default is 0)neverlink
will not be used in
.apk
creation. Useful if the library will be provided by the
runtime environment during execution.
plugins
:
Java compiler plugins to run at compile-time.
(List of labels;
optional)java_plugin
specified in
the plugins attribute will be run whenever
this android_library
is built. Resources generated by
the plugin will be included in the result jar of
the android_library
.
proguard_specs
:
Files to be used as Proguard specification.
(List of labels; optional)android_binary
target depending on this library.
The files included here must only have idempotent rules, namely -dontnote, -dontwarn,
assumenosideeffects, and rules that start with -keep. Other options can only appear in
android_binary
's proguard_specs, to ensure non-tautological merges.
strict_android_deps
:
(Integer; optional; default is -1 (inherited))When set to 1, javac will perform checks when compiling the java sources in
this library to verify that all explicitly mentioned classes were loaded from
directly specified deps
(rather than from the transitive closure
of all deps
). Set to 0 to mark target non-compliant in preparation
for future modification of default behavior, when 1 will become the default.
java_import(name, data, constraints, deprecation, distribs, exports, jars, licenses, neverlink, obsolete, srcjar, tags, testonly, visibility)
This rule allows the use of precompiled JAR files as libraries for
java_library
rules.
name
: A unique name for this rule. (Name; required)constraints
:
Extra constraints imposed on this rule as a Java library.
(List of strings; optional)exports
:
Targets to make available to users of this rule.
(List of labels; optional)jars
:
The list of JAR files provided to Java targets that depend on this target.
(List of labels; required)
neverlink
:
Only use this library for compilation and not at runtime.
(Boolean; optional; default is 0)tools.jar
for anything running on
a standard JDK.
srcjar
:
A JAR file that contains source code for the compiled JAR files.
(Label; optional)
java_library(name, deps, srcs, data, resources, constraints, deprecation, distribs, exported_plugins, exports, javacopts, licenses, neverlink, obsolete, plugins, runtime_deps, tags, testonly, visibility)
This rule compiles and links sources into a .jar
file.
libname.jar
: A Java archive containing the class files.libname-src.jar
: An archive containing the sources ("source jar").name
: A unique name for this rule. (Name; required)deps
:
The list of libraries to link into this library.
(List of labels; optional)deps
at Attributes common to all build rules.
For other java_library
rules listed in deps
,
the jars they build will be on the compile-time classpath for this rule;
also, the transitive closure of their deps
,
runtime_deps
, and exports
will be on the runtime
classpath.
By contrast, targets in the data
attribute are included
in the runfiles but on neither the compile-time nor runtime classpath.
srcs
:
The list of source files that are processed to create the library target.
(List of labels; optional)
srcs
files of type .java
are compiled.
For readability's sake, it is not good to put the name of a
generated .java
source file into the srcs
.
Instead, put the depended-on rule name in the srcs
, as
described below.
srcs
files of type .srcjar
are unpacked and
compiled. (This is useful if you need to generate a set of .java files with
a genrule or build extension.)
srcs
files of type .jar
are linked in.
(This is useful if you have third-party .jar
files
with no source.)
srcs
files of type .properties
are treated as
resources.
data
:
The list of files needed by this library at runtime.
(List of labels; optional)data
at Attributes common to all build rules.
When building a java_library
, the build tool
doesn't put these files anywhere; if the data
files are
generated files, the build tool generates them.
When building a test that depends upon this java_library
,
the build tool copies or links the data
files into the
runfiles area.
constraints
:
Extra constraints imposed on this library.
(List of strings; optional)
At the moment, the following constraints are supported:
android
: Specifies that this java_library is
Android-compatible. This means that the java_library does not
use Java APIs not supported by Android. If a java_library is
Android-compatible, the build tool will check that all dependent
java_libraries are marked as Android-compatible.
If an Android-compatible library depends on a java_library that is
not Android-compatible an error will be generated.
public
: Specifies that this java_library only
includes source code and resources that can be made public.
exported_plugins
:
The list of java_plugin
s
(e.g. annotation processors) to export to libraries that directly depend
on this library.
(List of labels; optional)The specified list of java_plugin
s will be applied to any
library which directly depends on this library, just as if that library had
explicitly declared these labels in
plugins
.
exports
:
The closure of all rules reached via exports
attributes are
considered direct dependencies of any rule that directly depends on the
target with exports
.
exports
are not direct deps of the rule they belong to.
neverlink
:
Only use this library for compilation and not at runtime.
(Boolean; optional; default is 0)tools.jar
for anything running on a standard JDK.
Note that neverlink = 1
does not prevent the compiler from
inlining material from this library into compilation targets that depend on
it, as permitted by the Java Language Specification (e.g., static
final
constants of String
or primitive type). The
preferred use case is therefore when the runtime library is identical to
the compilation library. If the runtime library differs from the
compilation library, then you must ensure that it differs only in places
that the JLS forbids compilers from inlining (and that must hold for all
future versions of the JLS).
sh_library(name, deps, srcs, data, deprecation, distribs, licenses, obsolete, tags, testonly, visibility)
The main use for this rule is to aggregate together a logical
"library" consisting of related scripts—programs in an
interpreted language that does not require compilation or linking,
such as the Bourne shell—and any data those programs need at
run-time. Such "libraries" can then be used from
the data
attribute of one or
more sh_binary
rules.
Historically, a second use was to aggregate a collection of data files
together, to ensure that they are available at runtime in
the .runfiles
area of one or more *_binary
rules (not necessarily sh_binary
).
However, the filegroup()
rule
should be used now; it is intended to replace this use of
sh_library
.
In interpreted programming languages, there's not always a clear
distinction between "code" and "data": after all, the program is
just "data" from the interpreter's point of view. For this reason
(and historical accident) this rule has three attributes which are
all essentially equivalent: srcs
, deps
and data
.
The recommended usage of each attribute is mentioned below. The
current implementation does not distinguish the elements of these lists.
All three attributes accept rules, source files and derived files.
name
: A unique name for this rule. (Name; required)deps
:
The list of other targets to be aggregated in to this "library" target.
(List of labels; optional)deps
at Attributes common to all build rules.
You should use this attribute to list other
sh_library
rules that provide
interpreted program source code depended on by the code in
srcs
.
srcs
:
The list of input files.
(List of labels,
optional)source
or .
command.
sh_library( name = "aggregator", data = [ ":aggregator_service_script", # a sh_binary with srcs ":deploy_aggregator", # another sh_binary with srcs ], )
A *_test
rule compiles a
test. See Common attributes for
tests for an explanation of the common attributes.
android_test(name, deps, srcs, data, resources, args, debug_key, deprecation, dexopts, distribs, flaky, licenses, local, obsolete, proguard_generate_mapping, proguard_specs, shard_count, size, strict_android_deps, tags, target_devices, testonly, timeout, visibility)
A android_test
rule runs Android tests. By default, it will
start an emulator, install the application under test along with the test
binary and any other needed Android binaries and run the tests defined in the
test package. An option to run the test on an existing device is available
to target_devices
users when running locally.
These tests require an Android device (virtual or physical) to run because they rely on Android libraries only available on the device.
name
: A unique name for this rule. (Name; required)deps
:
The list of other libraries and binaries to be linked in to the test
target. (List of labels; optional)
Permitted library types are: android_library
,
java_library
or java_import
with android
constraint, and
cc_library
wrapping or producing .so
native
libraries for the Android target platform.
deps
of type android_binary
are installed in
the emulator before running the tests, and the first in the list is
considered to be the proper application under test.
data
:
A collection of artifacts to be pushed onto the device's external storage
before the test is executed.
This option is only available when using target_devices
attribute.
proguard_specs
:
Files to be used as Proguard specification.
(List of labels; optional)target_devices
:
The android_device the test should run against.
(Label: required)
At this time only one android_device
is allowed in the target_devices
attribute.
java_test(name, deps, srcs, data, resources, args, classpath_resources, create_executable, deploy_manifest_lines, deprecation, distribs, flaky, javacopts, jvm_flags, launcher, licenses, local, main_class, obsolete, plugins, runtime_deps, shard_count, size, stamp, swigdeps, tags, test_class, testonly, timeout, use_testrunner, visibility)
A java_test()
rule compiles a Java test.
A test is binary wrapper around your test code.
The test runner's main method is invoked instead of
the main class being compiled.
name.jar
: A Java archive.name_deploy.jar
: A Java archive suitable
for deployment. (Only built if explicitly requested.)name
: A unique name for this rule. (Name; required)test_class
:
The Java class to be loaded by the test runner.
This attribute specifies the name of a Java class to be run by
this test. For JUnit3, this class needs to either be a subclass of
junit.framework.TestCase
or it needs to have a public
static suite()
method that returns a
junit.framework.Test
(or a subclass of Test
).
For JUnit4, proper
annotations should be used. If this argument is omitted, the Java class
whose name corresponds to the name
of this
java_test
rule will be used.
This attribute allows several java_test
rules to
share the same Test
(TestCase
, TestSuite
, ...). Typically
additional information is passed to it
(e.g. via jvm_flags=['-Dkey=value']
) so that its
behavior differs in each case, such as running a different
subset of the tests. This attribute also enables the use of
Java tests outside the javatests
tree.
See the section on java_binary()
arguments, with the caveats that
there is no main_class
argument.
It also supports all attributes common to
all test rules (*_test).
java_test
has this extra argument:
sh_test(name, deps, srcs, data, args, bash_version, deprecation, distribs, flaky, licenses, local, obsolete, shard_count, size, tags, testonly, timeout, visibility)
A sh_test()
rule creates a test. A test is
a wrapper around the tested code. If you're working with Perl and want to
write a unit test, then sh_test()
is the best
approach (though Perl is not supported).
name
: A unique name for this rule. (Name; required)
foo.sh
, we recommend
that you name the rule foo
, but this is not required.
bash_version
:
The version of bash to run this test with.
(String; optional; default is "system")"3"
, "4"
, and
"system"
. The first runs bash 3. The second runs
bash 4. The third runs with the executing system's default installation.
For a non-system bash, the output executable is a custom test runner that invokes the source script with the correct bash. For a system bash, the output executable is just the original source script.
See the section on sh_binary() for other arguments. Also see the attributes common to all test rules (*_test).
This section describes how to use or define a special class of string variables that are called the "Make" environment. Bazel defines a set of standard "Make" variables, and you can also define your own.
(The reason for the term "Make" is historical: the syntax and semantics of these variables are somewhat similar to those of GNU Make, and in the original implementation, were implemented by GNU Make. The scare-quotes are present because newer build tools support "Make" variables without being implemented using GNU Make; therefore it is important to read the specification below carefully to understand the differences.)
To see the list of all common "Make" variables and their values,
run bazel info --show_make_env
.
Build rules can introduce additional rule specific variables. One example is
the cmd
attribute of a genrule.
Variables can be referenced in attributes and other variables using either
$(FOO)
or varref('FOO')
, where FOO
is
the variable name. In the attribute documentation of rules, it is mentioned
when an attribute is subject to "Make" variable substitution. For those
attributes this means that any substrings of the form $(X)
within those attributes will be interpreted as references to the "Make"
variable X, and will be replaced by the appropriate value of that
variable for the applicable build configuration. The parens may be omitted
for variables whose name is a single character.
It is an error if such attributes contain embedded strings of the
form $(X)
where X is not the name of a
"Make" variable, or unclosed references such as $(
not
matched by a corresponding )
.
Within such attributes, literal dollar signs must be escaped
as $$
to prevent this expansion.
Those attributes that are subject to this substitution are explicitly indicated as such in their definitions in this document.
Bazel defines a set of "Make" variables for you.
The build system also provides a consistent PATH for genrules and tests which need to execute shell commands. For genrules, you can indirect your commands using the Make variables below. For basic Unix utilities, prefer relying on the PATH variable to guarantee correct results. For genrules involving compiler and platform invocation, you must use the Make variable syntax. The same basic command set is also available during tests. Simply rely on the PATH.
Bazel uses a tiny Unix distribution to guarantee consistent behavior of
build and test steps which execute shell code across all build execution
hosting environments but it does not enforce a pure chroot. As such, do
not use hard coded paths, such as
/usr/bin/foo
. Binaries referenced in hardcoded paths are not
hermetic and can lead to unexpected and non-reproducible build behavior.
Command Variables for genrules
Note that in general, you should simply refer to many common utilities as bare commands that the $PATH variable will correctly resolve to hermetic versions for you.
Path Variables
BINDIR
: The base of the generated binary tree for the target
architecture. (Note that a different tree may be used for
programs that run during the build on the host architecture,
to support cross-compiling. If you want to run a tool from
within a genrule, the recommended way of specifying the path to
the tool is to use $(location toolname)
,
where toolname must be listed in the tools
attribute for the genrule.GENDIR
: The base of the generated code
tree for the target architecture.JAVABASE
:
The base directory containing the Java utilities.
It will have a "bin" subdirectory.Architecture Variables
ABI
: The C++ ABI version. ANDROID_CPU
: The Android target architecture's cpu. JAVA_CPU
: The Java target architecture's cpu. TARGET_CPU
: The target architecture's cpu. Other Variables available to the cmd attribute of a genrule
OUTS
: The outs
list. If you have only one output
file, you can also use $@
.SRCS
: The srcs
list (or more
precisely, the pathnames of the files corresponding to
labels in the srcs
list). If you have only one
source file, you can also use $<
.<
: srcs
, if it is a single file.@
: outs
, if it is a single file.@D
: The output directory. If there is only
one filename in outs
, this expands to the
directory containing that file. If there are multiple
filenames, this variable instead expands to the package's root
directory in the genfiles
tree, even if all
the generated files belong to the same subdirectory!
If the genrule needs to generate temporary intermediate files
(perhaps as a result of using some other tool like a compiler)
then it should attempt to write the temporary files to
@D
(although /tmp
will also be
writable), and to remove any such generated temporary files.
Especially, avoid writing to directories containing inputs -
they may be on read-only filesystems. You may want to use Python-style variable assignments rather than "Make" variables, because they work in more use cases and are less surprising. "Make" variables will work in the cmd attribute of genrules and in the key of the abi_deps attribute of a limited number of rules, but only in very few other places.
To define your "Make" own variables, first call vardef() to define your variable, then call varref(name) to retrieve it. varref can be embedded as part of a larger string. Custom "Make" variables differ from ordinary "Python" variables in the BUILD language in two important ways:
$(FOO)
.
varref defers evaluation until after BUILD file evaluation.vardef(name, value, platform)
Define a variable for use within this BUILD
file only.
This variable can then be used by varref().
The value of the variable can be overridden on the command line by using the
--define
flag.
Arguments
name
: The name of the variable.
(String; required)value
: The value to assign to this variable.
(String; required)platform
: Conditionally define this variable for a given
platform.
(String; optional)vardef
binds the name
to value
if we're
compiling for platform
.
Notes
Because references to "Make" variables are expanded after
BUILD file evaluation, the relative order of vardef
statements and rule declarations is unimportant; it is order of
vardef
statements relative to each other, and hence the
state of the "Make" environment at the end of evaluation that
matters.
If there are multiple matching vardef
definitions for
the same variable, the definition that wins is
the last matching definition
that specifies a platform, unless there are no matching
definitions that specify a platform, in which case the definition
that wins is the last definition without
a platform.
varref(name)
varref("FOO")
is equivalent of writing "$(FOO)". It is used to
dereference variables defined with vardef
as well as predefined variables.
In rule attributes that are subject to "Make" variable
substitution, the string produced by varref(name)
will expand to the value of variable name.
varref(name)
may not be used in rule attributes that are
not subject to "Make" variable substitution.
Arguments
name
: The name of the variable to dereference.
Notes
varref
can access either local or global variables.
It prefers the local variable, if both a local and a global exist with
the same name.
Examples
See vardef() examples.
filegroup(name, srcs, data, deprecation, distribs, licenses, obsolete, output_licenses, path, tags, testonly, visibility)
Use filegroup
to give a convenient name to a
collection of targets. These can then be referenced from other
rules, e.g. the srcs
attribute of a genrule, or
the data
attribute of a *_binary rule.
Motivation: this mechanism aims to replace the practice of referencing directory names as data dependencies. Referencing directory names is unsound as the build system does not have full knowledge of all files below the directory, so it may or may not rebuild as these files change. When combined with glob, filegroup can ensure that all files are explicitly known to the build system.
name
: A unique name for this rule. (Name; required)srcs
:
The list of targets that are members of the file group.
(List of labels; optional)
It is common to use the result of a glob
expression for the value of the srcs
attribute.
If a glob matches a source file with the same name as a build rule,
the rule will override the file.
data
:
The list of files needed by this rule at runtime.
(List of labels; optional)data
attribute will be considered
belonging to the runfiles of the filegroup rule. This means in practice
that when the filegroup is put in the data
attribute of a
rule, the files referred to by this attribute will also be considered to be
data of the rule referring to the filegroup
. See the
data dependencies section for more
information about how to depend on and use data files.
path
:
An optional string giving a path to the files in the group.
(String; optional)To create a filegroup consisting of two source files, do
filegroup( name = "mygroup", srcs = [ "a_file.txt", "another_file.txt", ], )
Or, use a glob to grovel a testdata directory:
filegroup( name = "exported_testdata", srcs = glob([ "testdata/*.dat", "testdata/logs/*.log", ]), )
To make use of these definitions, reference the filegroup with a label from any rule:
cc_library( name = "my_library", srcs = ["foo.cc"], data = [ "//my_package:exported_testdata", "//my_package:mygroup", ], )
test_suite(name, deprecation, distribs, licenses, obsolete, tags, testonly, tests, visibility)
A test_suite
defines a set of tests that are considered
"useful" to humans. This allows projects to define sets of tests,
such as "tests you must run before checkin", "our project's stress
tests" or "all small tests."
name
: A unique name for this rule. (Name; required)tests
:
A list of test suites and test targets of any language.
You can freely mix languages and rule styles. Thus any
*_test
will work, but not an *_binary
that
happens to run a test. Filtering by the specified tags
will
be applied only to the tests in this attribute, but not to test suites or
tests included from other test suites. The tests
and
suites
attributes can be used interchangeably.
If the tests
and the suites
parameters are both
unspecified or empty, the rule will default to including all test rules in
the current BUILD file that are not tagged as manual
or
marked as obsolete
. These rules are still subject to
tag
filtering.
android_device(name, cache, default_properties, deprecation, distribs, horizontal_resolution, licenses, obsolete, ram, screen_density, system_image, tags, testonly, vertical_resolution, visibility, vm_heap)
This rule creates an android emulator configured with the given specifications. This emulator may be started via a bazel run command or by executing the generated script directly.
name_images/userdata.dat
:
Contains image files and snapshots to start the emulatorname_images/emulator-meta-data.pb
:
Contains serialized information necessary to pass on to the emulator to
restart it.name
: A unique name for this rule. (Name; required)cache
:
The size in megabytes of the emulator's cache partition. The minimum value
of this is 16 megabytes.
default_properties
:
default_properties
A single properties file to be placed in /default.prop on the emulator. This
allows the rule author to further configure the emulator to appear more like
a real device (In particular controlling its UserAgent strings and other
behaviour that might cause an application or server to behave differently to
a specific device). The properties in this file will override read only
properties typically set by the emulator such as ro.product.model.
horizontal_resolution
:
horizontal_resolution
:
The horizontal screen resolution in pixels to emulate. The minimum value is 240.
ram
:
The amount of ram in megabytes to emulate for the device. This is for the
entire device, not just for a particular app installed on the device. The
minimum value is 64 megabytes.
screen_density
:
The density of the emulated screen in pixels per inch. The minimum value of
this is 30 ppi.
system_image
:
A filegroup containing the following files:
vertical_resolution
:
The vertical screen resolution in pixels to emulate. The minimum value is 240.
vm_heap
:
The size in megabytes of the virtual machine heap Android will use for each
process. The minimum value is 16 megabytes.
android_manifest_merge(name, deps, srcs, deprecation, distribs, exclude_permissions, licenses, obsolete, tags, testonly, visibility)
This rule merges an AndroidManifest.xml
file with other android
manifests that your app depends on (mergees). Other manifests might come
from android libraries that your project depends on (e.g.: userfeedback
library), or on your test manifest used to produce test version of your app's
binary. Optionally, permissions from the mergees can be excluded.
name/AndroidManifest.xml
:
Merged android manifest file.name
: A unique name for this rule. (Name; required)deps
:
The list of AndroidManifest.xml files to be merged into the main
AndroidManifest.xml
(merger).
(List of labels; required)AndroidManifest files of type .xml
.
Other android_manifest_merge targets are allowed here.
Mergee(s) will be merged into the merger. Class references from the mergee(s) that are not in a fully qualified format.
Duplicates from the mergees (that also exist in the merger) will be omitted during the merge. (e.g.: Duplicate permissions entries)
Mergees contribute following elements to the merger:
From Manifest element:
instrumentation
, permission
,
uses-permission
, uses-feature
From Application element:
activity
, provider
, receiver
,
service
, uses-library
srcs
:
The list of one manifest file to merge other manifest files (mergees) into.
(labels; required)
AndroidManifest file of type .xml
.
Usually it is your main app's manifest. This is the merger manifest file -
Manifest that other manifests (mergees) would be merged into.
Your app will use merger's package name, versioning, application attributes
and permissions. This srcs list is allowed to have only one label.
exclude_permissions
:
exclude_permissions
:
The permission(s) to be excluded from the mergee(s).
(List of strings; optional)android_resources(name, resources, assets, assets_dir, custom_package, deprecation, distribs, exports_manifest, inline_constants, licenses, manifest, obsolete, rename_manifest_package, tags, testonly, visibility)
Generates name.srcjar
which contains R.java,
Manifest.java and any other java resources generated by aapt.
name.srcjar
: A .srcjar
file
containing all java generated sources.name.ap_
: An Android application package file
containing the manifest, all resources and assets.name
: A unique name for this rule. (Name; required)resources
:
The list of resources to be packaged.
(List of labels; optional)glob
of all files under the
res
directory.
If you depend on resources in other packages, you should reference their
rules or exported files here. This enables bazel to resolve any conflicts
with file names or attribute names.assets
:
The list of assets to be packaged.
(List of labels; optional)glob
of all files under the
assets
directory. You can also reference other rules or
exported files in the other packages, as long as all their outputs are
under the assets_dir
directory in the corresponding package.
assets_dir
:
The string giving the path to the files in assets
.
(String; optional)assets
and assets_dir
describe packaged
assets and either both attributes should be provided or none of them.
custom_package
:
Java package for which java sources will be generated.
(String; optional)exports_manifest
:
Whether to export manifest entries to android_binary
targets
that depend on this target. uses-permissions
attributes are never exported.
(Boolean; optional; default is 0)inline_constants
:
Let the compiler inline the constants defined in the generated java sources.
(Boolean; optional; default is 1)android_resources
rules
used directly by an android_library
(android library project)
and for any android_binary
that has an android library project
in its transitive closure.
manifest
:
The name of the Android manifest file.
Current Android toolchain expects AndroidManifest.xml
name.
(Label; required)rename_manifest_package
:
Changes the app package name.
(String; optional)Please see examples under android_binary.
Here is an example of combining multiple assets sources. Let
//java/android/o/BUILD
contain
exports_files(["assets/other"])
Then in the other package you can say:
android_resources( name = "r", assets = [ "assets/source", "//java/android/o:assets/other", ], assets_dir = "assets", manifest = "AndroidManifest.xml", )
android_resources( name = "r", assets = glob(["assets/**"]) assets_dir = "moreassets", manifest = "AndroidManifest.xml", )
genrule(name, srcs, outs, cmd, deprecation, distribs, executable, heuristic_label_expansion, licenses, local, message, obsolete, output_licenses, output_to_bindir, stamp, tags, testonly, tools, visibility)
A genrule
generates one or more files, where the generation of
those files is done with custom shell commands running in bash. While this
makes them very flexible, they are also difficult to use correctly.
While genrules run during a build, their outputs are often used after the build, for deployment or testing. The build system uses the host configuration to describe the machines on which the build runs, and the target configuration to describe the machines on which the output of the build is supposed to run. It provides options to configure each of these, and it segregates the corresponding files into separate directories to avoid conflicts.
For genrules, the build system ensures that dependencies are built
appropriately - srcs
are built (if necessary) for the target
configuration, tools are built for the host configuration, and the output is
considered to be for the target configuration. It also provides
"Make" variable that genrule
commands can pass to the corresponding tools.
It is intentional that genrule does not have a deps attribute - other built-in rules use language-dependent meta information passed between the rules to automatically determine how to handle dependent rules, but this level of automation is not possible for genrules. Genrules work purely at the file and runfiles level.
Host-host compilation - in some cases, the build system needs to run
genrules such that the output can also be run during the build. In that case,
the build system automatically builds the srcs
and
outs
for the host configuration, and sets the variables
accordingly.
Genrules are executed in a sandbox that only allows access to declared inputs. Genrules that are run locally are currently an exception, but this may change in the future, i.e., local genrules will also be run in a sandbox. The declared output files from a genrule are copied out of the sandbox, whereas all other files are dropped.
Furthermore, the build system sets environment variables it sets
PATH
to point to a set of standard utilities). At least awk, bash, echo, diff, find,
grep, gzip, m4, md5sum, patch, perl, sed, tar, and xargs are provided.
It sets LANG
to en_US
. No other
environment variables are set; in particular, no environment variables are
passed through from the build system invocation.
The genrule command is executed in a bash shell. The bash
shell is configured to fail when a command fails (set -e
); at
some point in the future, it will also fail when a command in a pipline fails
(set -o pipefail
). Genrules should not access the network (except
to create connections between processes running within the same genrule on the
same machine), though this is not currently enforced in all cases.
The build system automatically deletes any existing output files, but creates any necessary parent directories before it runs a genrule. It also removes any output files in case of a failure.
$(location)
extensively, including for outputs and
sources. Due to the segregation of output files for different
configurations, genrules cannot rely on hard-coded paths.
$$
evaluates to a $
, a literal dollar-sign - so,
to invoke a shell command containing dollar-signs such as
ls $(dirname $x)
, one must escape it thus:
ls $$(dirname $$x)
.
local = 1
at your own risk.
name
: A unique name for this rule. (Name; required) srcs
or deps
section of other BUILD
rules. If the rule generates source files, you should use the
srcs
attribute.
srcs
:
A list of inputs for this rule.
(List of labels; optional)
The build system ensures these prerequisites are built before
running the genrule command; they are built using the same
configuration as the original build request. The names of the
files of these prerequisites are available to the command as a
space-separated list in $(SRCS)
; alternatively the
path of an individual srcs
target //x:y
can be obtained using $(location //x:y)
.
Most rules, when used in genrule.srcs
, behave the same way:
their outputs are made available to the genrule
.
outs
:
A list of files generated by this command.
(List of filenames; required)All output files must be generated into the same directory and must not cross package boundaries. Output filenames are interpreted as relative to the package root.
If the executable
flag is set, outs
must
contain exactly one label.
cmd
:
The command to run.
(String; required; subject to
"Make" variable substitution.)$(location
label)
are replaced by the path to the file
denoted by label. If label is malformed, or
not a declared dependency of this rule, or expands to a
number of files other than exactly one, an error is raised.
label need not be in canonical form:
foo
, :foo
and
//thispkg:foo
are all equivalent. It may also
be the name of an output file from the outs
attribute, in which case only the unqualified
form foo
(no //
or :
) may be used.
$(locations
label)
are replaced by the space separated paths
to the files denoted by label. If label is malformed,
or not a declared dependency of this rule, or expands to no
files, an error is raised.
This is essentially the same substitution as
$(location)
, but without the upper limit on the
number of files.
Thirdly, if heuristic_label_expansion
is enabled, a
heuristic pass is applied to the string to replace all occurrences of
the labels occurring in the srcs
, tools
and
data
attributes of the rule, by their
corresponding filenames.
(In effect, this is the same substitution as
$(location)
, but in some cases, the heuristic
may fail to detect certain labels, for example, when
constructing a command-line such as $(JAVA) -classpath
label1:label2:label3 foo.jar
.
We recommend that in all new code, the explicit
$(location)
form is used in preference to the
heuristic.)
Note that outs
are not included in
this substitution. Output files are
always generated into a predictable location (available via
$(@D)
, see below).
$(JAVA)
, $(JAVAC)
and
$(JAVABASE)
expand under the
host configuration, so Java invocations that run as part of a
build step can correctly load shared libraries and other dependencies.
The command may refer to binaries; it should use a label for this. The following
variables are available within the cmd
sublanguage:
vardef
).
executable
:
Declare output to be executable.
(Boolean; optional; default is 0) Setting this flag to 1 means the output is an executable file and can be
run using the bazel run
command. The genrule must produce
exactly one output in this case. If this attribute is set, bazel
run
will try executing the file regardless of its file type.
Note that for legacy compatibility the use of this attribute is not
always necessary for bazel run
to work. If the output is
.sh
),bazel run
will execute the target even if this flag is
set to 0 or unset. For new targets, please explicitly specify this
attribute as needed.
Unfortunately there is no way to declare data dependencies yet (but it is being worked on).
heuristic_label_expansion
:
Whether to perform heuristic label expansion
(Boolean; optional; default is true)$(location)
to expand
labels.
message
:
A progress message
(String; optional)echo
or other
print statements in your cmd
command, as this allows
the build tool to control whether such progress messages are
printed or not.
output_licenses
:
See common attributes
output_to_bindir
:
Place output files in the bin
directory.
(Boolean; optional; default is 0) bin
directory instead of the genfiles
directory.
stamp
:
Whether to give access to build stamp information to the genrule
(Boolean; optional; default is false)stamp = 1
: Always make the build information available to
the genrule. Use this with caution, since this potentially affects
caching if many things depend on this genrule.stamp = 0
: Never make build information available to
the genrule.The build information files are available as
bazel-out/build-info.txt
and
bazel-out/build-changelist.txt
.
Note that the handling of this attribute is different from that of every other rule.
tools
:
A list of tool dependencies for this rule.
(List of
labels; optional)tools
target //x:y
can be obtained using $(location
//x:y)
.
Any binaries or tools to be executed by cmd
must appear in this list, not in srcs
, to ensure they
are built in the correct configuration.
The following example shows how to process
genrule( name = "concat_all_files", srcs = [ "//some:file", "//other:file", ], outs = ["concatenated.txt"], cmd = "cat $(location //some:file) $(location //other:file) > $@" )
java_plugin(name, deps, srcs, data, resources, deprecation, distribs, generates_api, javacopts, licenses, neverlink, obsolete, plugins, processor_class, tags, testonly, visibility)
java_plugin() defines plugins for the Java compiler run by Bazel.
At the moment, the only supported kind of plugins are annotation
processors. A java_library
or java_binary
rule can run plugins by depending on them via the
plugins
attribute. A java_library
can also export
plugins automatically to libraries that directly depend on it using
exported_plugins
.
libname.jar
: A Java archive.name
: A unique name for this rule. (Name; required)generates_api
:
This attribute marks annotation processors that generate API code.
(Boolean; optional, default is 0)processor_class
:
(Name; optional)java_plugin
will not contribute an
annotation processor to the Java compiler's annotation processing,
but its runtime classpath will still be included on the compiler's
annotation processor path.
Arguments are identical to java_library(),
except for the addition of the processor_class
argument.
java_wrap_cc(name, deps, srcs, data, copts, deprecation, distribs, javacopts, legacy_override_module, licenses, obsolete, package, plugins, swig_includes, swig_top, tags, testonly, visibility)
java_wrap_cc() turns a .swig
file and some C++ libraries into
a Java swigging. The outputs are a static archive file and a Java archive that
provides the Java interface. The archive file is linked into the swigdeps.so
shared library, or if using a java launcher,
linked into the launcher itself.
libname.jar
: A Java archive.name
: A unique name for this rule. (Name; required)deps
:
The libraries to compile into the module.
(List of labels; required)deps
at Attributes common to all build
rules.
These can be C++ libraries, Java libraries, or other
java_wrap_cc
rules. Plain files such as .i
or
.swig
files are currently also allowed, but should be avoided,
if possible.
srcs
:
A list of one swig
source.
(List of labels; required)
javacopts
:
See java_binary
legacy_override_module
:
(Boolean; optional; default 1)-module main
option is passed to the swig tool,
which overrides any module declaration in the source file. This option can
be used to disable that behavior.
package
:
(String; optional; default current_package.target_name)swig_includes
:
(Label list; optional)swig_top
:
(Label; optional)filegroup
containing
the file swig
.
This function declares metadata that applies to every subsequent rule in the package.
The package function is used at most once within a build package (BUILD file). It is recommended that the package function is called at the top of the file, before any rule.
default_visibility
:
The default visibility of the rules in this package.
(List of labels; optional)Every rule in this package has the visibility specified in this
attribute, unless otherwise specified in the visibility
attribute of the rule. For detailed information about the syntax of this
attribute, see the documentation of the visibility
attribute.
default_obsolete
:
The default value of obsolete
property
for all rules in this package. (Boolean; optional; default is 0)
default_deprecation
:
Sets the default deprecation
message
for all rules in this package. (String; optional)
default_testonly
:
Sets the default testonly
property
for all rules in this package. (Boolean; optional; default is 0 except as noted)
In packages under javatests
the default value is 1.
//foo:target
. Individual visibility declarations
on a rule, if present, override this specification.
package(default_visibility = ["//foo:target"])
package_group(name, packages, includes)
This function defines a set of build packages. Package groups are used for visibility control. You can grant access to a rule to one or more package groups, every rule, or only to rules declared in the same package. For more detailed description of the visibility system, see the visibility attribute.
name
:
A unique name for this rule.
(Name; required)
packages
:
A complete enumeration of packages in this group.
(List of Package; optional)Packages should be referred to using their full names,
starting with a double slash. For
example, //foo/bar/main
is a valid element
of this list.
You can also specify wildcards: the specification
//foo/...
specifies every package under
//foo
, including //foo
itself.
If this attribute is missing, the package group itself will contain no packages (but it can still include other package groups).
includes
:
Other package groups that are included in this one.
(List of labels; optional)The labels in this attribute must refer to other package
groups. Packages in referenced package groups are taken to be part
of this package group. This is transitive, that is, if package
group a
contains package group b
,
and b
contains package group c
, every
package in c
will also be a member of a
.
package_group
declaration specifies a
package group called "tropical" that contains tropical fruits.
package_group( name = "tropical", packages = [ "//fruits/mango", "//fruits/orange", "//fruits/papaya/...", ], )The following declarations specify the package groups of a fictional application:
package_group( name = "fooapp", includes = [ ":controller", ":model", ":view", ], ) package_group( name = "model", packages = ["//fooapp/database"], ) package_group( name = "view", packages = [ "//fooapp/swingui", "//fooapp/webui", ], ) package_group( name = "controller", packages = ["//fooapp/algorithm"], )
# Description: ...
Each BUILD file should contain a Description
comment.
Description comments may contain references to other documentation. A string that starts with "http" will become a link. HTML markup is allowed in description comments, but please keep the BUILD files readable. We encourage you to list the URLs of relevant design docs and howtos in these description comments.
distribs(distrib_methods)
distribs()
specifies the default distribution method (or
methods) of the build rules in a BUILD
file. The distribs()
directive
should appear close to the beginning of the BUILD
file,
before any build rules, as it sets the BUILD
-file scope
default for build rule distribution methods.
The argument, distrib_methods
,
is a list of distribution-method strings.
exports_files([label, ...], visibility, licenses)
exports_files()
specifies a list of files belonging to
this package that are exported to other packages but not otherwise
mentioned in the BUILD file.
The BUILD file for a package may only refer to files belonging to another
package if they are mentioned somewhere in the other packages's BUILD file,
whether as an input to a rule or an explicit or implicit output from a rule.
The remaining files are not associated with a specific rule but are just "data",
and for these, exports_files
ensures that they may be referenced by
other packages. (One kind of data for which this is particularly useful are
shell and Perl scripts.)
Note: A BUILD file only consisting of exports_files()
statements
is needless though, as there are no BUILD rules that could own any files.
The files listed can already be accessed through the containing package and
exported from there if needed.
The argument is a list of names of files within the current package. A
visibility declaration can also be specified; in this case, the files will be
visible to the targets specified. If no visibility is specified, the files
will be visible to every package, even if a package default visibility was
specified in the package
function. The
licenses can also be specified.
glob(include, exclude=[], exclude_directories=1)
Glob is a helper function that can be used anywhere a list of filenames
is expected. It takes one or two lists of filename patterns containing
the *
wildcard: as per the Unix shell, this wildcard
matches any string excluding the directory separator /
.
In addition filename patterns can contain the recursive **
wildcard. This wildcard will match zero or more complete
path segments separated by the directory separator /
.
This wildcard can only be used as a complete path segment. For example,
"x/**/*.java"
is legal, but "test**/testdata.xml"
and "**.java"
are both illegal. No other wildcards are supported.
Glob returns a list of every file in the current build package that:
include
. exclude
(default []).
If the exclude_directories
argument is enabled (1), files of
type directory will be omitted from the results (default 1).
There are several important limitations and caveats:
+
to add it to the result of the
glob()
call.
**/*.cc
in package
x
does not include x/y/z.cc
if
x/y
exists as a package (either as
x/y/BUILD
, or somewhere else on the package-path). This
means that the result of the glob expression actually depends on the
existence of BUILD files — that is, the same glob expression would
include x/y/z.cc
if there was no package called
x/y
.
In general, you should try to provide an appropriate extension (e.g. *.html) instead of using a bare '*' for a glob pattern. The more explicit name is both self documenting and ensures that you don't accidentally match backup files, or emacs/vi/... auto-save files.
Include all txt files in directory testdata except experimental.txt. Note that files in subdirectories of testdata will not be included. If you want those files to be included, use a recursive glob (**).
java_test( name = "myprog", srcs = ["myprog.java"], data = glob( ["testdata/*.txt"], exclude = ["testdata/experimental.txt"], ), )
Create a library built from all java files in this directory and all subdirectories except those whose path includes a directory named testing. Subdirectories containing a BUILD file are ignored. This should be a very common pattern.
java_library( name = "mylib", srcs = glob( ["**/*.java"], exclude = ["**/testing/**"], ), )
Make the test depend on all txt files in the testdata directory, its subdirectories
java_test( name = "mytest", srcs = ["mytest.java"], data = glob(["testdata/**/*.txt"]), )
licenses(license_types)
licenses()
specifies the default license type (or types)
of the build rules in a BUILD
file. The licenses()
directive should appear close to the
beginning of the BUILD
file, before any build rules, as it
sets the BUILD
-file scope default for build rule license
types.
The argument, license_types
,
is a list of license-type strings.
include(name)
include()
incorporates build
language definitions from an external file into the evaluation of the
current BUILD
file.